@props([
    'disabled' => false,
    'readonly' => false,
    'helper' => '',
    'value' => '',
    'name' => null,
    'id' => null,
    'placeholder' => '#000000',
])

<div x-data="colorInput({ initial: @js($value) })" class="sm:max-w-lg">
    <div class="relative">
        <input type="text"
               x-model="color"
               name="{{ $name }}"
               id="{{ $id }}"
               placeholder="{{ $placeholder }}"
               {{ $disabled ? 'disabled' : '' }}
               {{ $readonly ? 'readonly' : '' }}
               class="block w-full rounded-md border border-gray-300 py-1.5 pl-9 pr-3 text-gray-900 shadow-sm placeholder:text-gray-400 sm:text-sm sm:leading-6 {{ $disabled || $readonly ? 'bg-gray-100' : '' }}">

        <button type="button" @click.prevent="$refs.nativePicker.click()" class="absolute left-2 top-1/2 -translate-y-1/2 h-5 w-5 rounded-full border border-gray-300 shadow-sm" :style="{ backgroundColor: color }" aria-label="Pick color"></button>
        <input x-ref="nativePicker" type="color" x-model="color" class="sr-only" {{ $disabled ? 'disabled' : '' }} {{ $readonly ? 'readonly' : '' }}>
    </div>

    @if($helper)
        <p class="flex items-start mt-2 text-xs text-slate-400">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 mr-1.5">
                <path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12ZM12 8.25a.75.75 0 0 1 .75.75v3.75a.75.75 0 0 1-1.5 0V9a.75.75 0 0 1 .75-.75Zm0 8.25a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z" clip-rule="evenodd" />
            </svg>
            {{ $helper }}
        </p>
    @endif
</div>

<script>
    document.addEventListener('alpine:init', () => {
        window.colorInput = function ({ initial }) {
            return {
                color: initial || '#000000',
                init() {
                    this.$watch('color', (val) => {
                        if (!/^#([0-9a-fA-F]{3}){1,2}$/.test(val)) return;
                    })
                },
            }
        }
    })
</script>


