/**
 * Dropdown primitive — select replacement with search/filter
 * options: [{ label, value, disabled? }]
 */
const { html } = window;
const { useState, useRef, useEffect, useCallback, useMemo } = hooks;

export function Dropdown({ options = [], value, onChange, placeholder = 'Select...', searchable = false }) {
    const [open, setOpen] = useState(false);
    const [search, setSearch] = useState('');
    const [focusIdx, setFocusIdx] = useState(-1);
    const wrapRef = useRef(null);
    const inputRef = useRef(null);

    const filtered = useMemo(() => {
        if (!search) return options;
        const q = search.toLowerCase();
        return options.filter(o => o.label.toLowerCase().includes(q));
    }, [options, search]);

    const selected = options.find(o => o.value === value);

    // Close on outside click
    useEffect(() => {
        if (!open) return;
        const handler = (e) => {
            if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
        };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, [open]);

    // Focus search on open
    useEffect(() => {
        if (open && searchable && inputRef.current) inputRef.current.focus();
        if (open) setFocusIdx(-1);
        if (!open) setSearch('');
    }, [open, searchable]);

    const select = useCallback((opt) => {
        if (opt.disabled) return;
        if (onChange) onChange(opt.value);
        setOpen(false);
    }, [onChange]);

    const onKeyDown = useCallback((e) => {
        if (!open) {
            if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') {
                e.preventDefault();
                setOpen(true);
            }
            return;
        }
        const count = filtered.length;
        switch (e.key) {
            case 'ArrowDown':
                e.preventDefault();
                setFocusIdx(i => Math.min(i + 1, count - 1));
                break;
            case 'ArrowUp':
                e.preventDefault();
                setFocusIdx(i => Math.max(i - 1, 0));
                break;
            case 'Enter':
                e.preventDefault();
                if (focusIdx >= 0 && focusIdx < count) select(filtered[focusIdx]);
                break;
            case 'Escape':
                setOpen(false);
                break;
        }
    }, [open, filtered, focusIdx, select]);

    return html`
        <div class="sw-dropdown ${open ? 'sw-dropdown--open' : ''}" ref=${wrapRef} onKeyDown=${onKeyDown}>
            <button class="sw-dropdown__trigger" type="button"
                    onClick=${() => setOpen(!open)}
                    aria-haspopup="listbox" aria-expanded=${open}>
                <span class="sw-dropdown__value">${selected ? selected.label : placeholder}</span>
                <span class="sw-dropdown__chevron">\u25be</span>
            </button>
            ${open && html`
                <div class="sw-dropdown__list" role="listbox">
                    ${searchable && html`
                        <input class="sw-dropdown__search sw-input" ref=${inputRef}
                               placeholder="Search..."
                               value=${search}
                               onInput=${(e) => { setSearch(e.target.value); setFocusIdx(0); }} />
                    `}
                    ${filtered.map((opt, i) => html`
                        <div class="sw-dropdown__option ${opt.value === value ? 'sw-dropdown__option--selected' : ''} ${opt.disabled ? 'sw-dropdown__option--disabled' : ''} ${i === focusIdx ? 'sw-dropdown__option--focused' : ''}"
                             role="option"
                             aria-selected=${opt.value === value}
                             onMouseEnter=${() => setFocusIdx(i)}
                             onClick=${() => select(opt)}>
                            ${opt.label}
                        </div>
                    `)}
                    ${filtered.length === 0 && html`
                        <div class="sw-dropdown__empty">No results</div>
                    `}
                </div>
            `}
        </div>
    `;
}
