/**
 * CustomSelect — lightweight, accessible custom dropdown replacement for native <select>.
 *
 * CSS Variables (apply on a parent element to customize):
 * --seekora-select-bg           — background color (default: #fff)
 * --seekora-select-color        — text color (default: inherit)
 * --seekora-select-border       — border color (default: rgba(128,128,128,0.3))
 * --seekora-select-hover-bg     — option hover background (default: #f3f4f6)
 * --seekora-select-active-bg    — selected option background (default: #eff6ff)
 * --seekora-select-active-color — selected option text color (default: inherit)
 * --seekora-select-radius       — border radius (default: 6px)
 * --seekora-select-font-size    — font size (default: 0.875rem)
 */
import React, { useState, useRef, useCallback, useEffect, useId } from 'react';
import { clsx } from 'clsx';
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
export const CustomSelect = ({ value, onChange, options, placeholder = 'Select...', className, style, theme: customTheme, 'aria-label': ariaLabel, disabled = false, }) => {
    const [isOpen, setIsOpen] = useState(false);
    const [activeIndex, setActiveIndex] = useState(-1);
    const containerRef = useRef(null);
    const menuRef = useRef(null);
    const instanceId = useId();
    const t = customTheme || {};
    const selectedOption = options.find((o) => o.value === value);
    const displayLabel = selectedOption?.label ?? placeholder;
    // Close on click outside
    useEffect(() => {
        if (!isOpen)
            return;
        const handleMouseDown = (e) => {
            if (containerRef.current && !containerRef.current.contains(e.target)) {
                setIsOpen(false);
                setActiveIndex(-1);
            }
        };
        document.addEventListener('mousedown', handleMouseDown);
        return () => document.removeEventListener('mousedown', handleMouseDown);
    }, [isOpen]);
    // Scroll active item into view
    useEffect(() => {
        if (!isOpen || activeIndex < 0 || !menuRef.current)
            return;
        const item = menuRef.current.children[activeIndex];
        item?.scrollIntoView?.({ block: 'nearest' });
    }, [activeIndex, isOpen]);
    const toggle = useCallback(() => {
        if (disabled)
            return;
        setIsOpen((prev) => {
            if (!prev) {
                // Opening — highlight current selection
                const idx = options.findIndex((o) => o.value === value);
                setActiveIndex(idx >= 0 ? idx : 0);
            }
            return !prev;
        });
    }, [disabled, options, value]);
    const selectOption = useCallback((opt) => {
        if (opt.disabled)
            return;
        onChange(opt.value);
        setIsOpen(false);
        setActiveIndex(-1);
    }, [onChange]);
    // Find next non-disabled index in given direction
    const findNextEnabled = (from, dir) => {
        let idx = from;
        for (let i = 0; i < options.length; i++) {
            idx += dir;
            if (idx < 0)
                idx = options.length - 1;
            if (idx >= options.length)
                idx = 0;
            if (!options[idx].disabled)
                return idx;
        }
        return from;
    };
    const handleKeyDown = useCallback((e) => {
        if (disabled)
            return;
        if (!isOpen) {
            if (['ArrowDown', 'ArrowUp', 'Enter', ' '].includes(e.key)) {
                e.preventDefault();
                toggle();
            }
            return;
        }
        switch (e.key) {
            case 'ArrowDown':
                e.preventDefault();
                setActiveIndex((prev) => findNextEnabled(prev, 1));
                break;
            case 'ArrowUp':
                e.preventDefault();
                setActiveIndex((prev) => findNextEnabled(prev, -1));
                break;
            case 'Enter':
            case ' ':
                e.preventDefault();
                if (activeIndex >= 0 && !options[activeIndex].disabled) {
                    selectOption(options[activeIndex]);
                }
                break;
            case 'Escape':
                e.preventDefault();
                setIsOpen(false);
                setActiveIndex(-1);
                break;
            case 'Home':
                e.preventDefault();
                setActiveIndex(findNextEnabled(-1, 1));
                break;
            case 'End':
                e.preventDefault();
                setActiveIndex(findNextEnabled(options.length, -1));
                break;
            case 'Tab':
                setIsOpen(false);
                setActiveIndex(-1);
                break;
        }
    }, [disabled, isOpen, activeIndex, options, toggle, selectOption]);
    const menuId = `seekora-select-menu-${instanceId}`;
    return (React.createElement("div", { ref: containerRef, className: clsx('seekora-select', className), style: { position: 'relative', display: 'inline-block', ...style }, onKeyDown: handleKeyDown },
        React.createElement("button", { type: "button", role: "combobox", "aria-haspopup": "listbox", "aria-expanded": isOpen, "aria-controls": menuId, "aria-label": ariaLabel, "aria-activedescendant": isOpen && activeIndex >= 0
                ? `${menuId}-opt-${activeIndex}`
                : undefined, disabled: disabled, onClick: toggle, className: clsx('seekora-select__trigger', t.trigger), style: {
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                gap: 8,
                width: '100%',
                padding: '8px 12px',
                fontSize: 'var(--seekora-select-font-size, 0.875rem)',
                lineHeight: 1.4,
                border: '1px solid var(--seekora-select-border, rgba(128,128,128,0.3))',
                borderRadius: 'var(--seekora-select-radius, 6px)',
                backgroundColor: 'var(--seekora-select-bg, #fff)',
                color: 'var(--seekora-select-color, inherit)',
                cursor: disabled ? 'not-allowed' : 'pointer',
                outline: 'none',
                textAlign: 'left',
                fontFamily: 'inherit',
                opacity: disabled ? 0.5 : 1,
            } },
            React.createElement("span", { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, displayLabel),
            React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", style: {
                    flexShrink: 0,
                    transition: 'transform 0.15s ease',
                    transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                } },
                React.createElement("path", { d: "M2.5 4.5L6 8L9.5 4.5", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }))),
        isOpen && (React.createElement("div", { ref: menuRef, id: menuId, role: "listbox", className: clsx('seekora-select__menu', t.menu), style: {
                position: 'absolute',
                top: '100%',
                left: 0,
                right: 0,
                zIndex: 9999,
                marginTop: 4,
                padding: '4px 0',
                border: '1px solid var(--seekora-select-border, rgba(128,128,128,0.3))',
                borderRadius: 'var(--seekora-select-radius, 6px)',
                backgroundColor: 'var(--seekora-select-bg, #fff)',
                boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                maxHeight: 220,
                overflowY: 'auto',
            } }, options.map((opt, idx) => {
            const isSelected = opt.value === value;
            const isHighlighted = idx === activeIndex;
            return (React.createElement("div", { key: opt.value, id: `${menuId}-opt-${idx}`, role: "option", "aria-selected": isSelected, "aria-disabled": opt.disabled || undefined, className: clsx('seekora-select__option', t.option, isSelected && 'seekora-select__option--selected', isHighlighted && (t.optionActive || 'seekora-select__option--highlighted'), opt.disabled && (t.optionDisabled || 'seekora-select__option--disabled')), onMouseEnter: () => !opt.disabled && setActiveIndex(idx), onMouseDown: (e) => {
                    e.preventDefault(); // Prevent blur
                    if (!opt.disabled)
                        selectOption(opt);
                }, style: {
                    padding: '6px 12px',
                    fontSize: 'var(--seekora-select-font-size, 0.875rem)',
                    cursor: opt.disabled ? 'not-allowed' : 'pointer',
                    backgroundColor: isHighlighted
                        ? 'var(--seekora-select-hover-bg, #f3f4f6)'
                        : isSelected
                            ? 'var(--seekora-select-active-bg, #eff6ff)'
                            : 'transparent',
                    color: opt.disabled
                        ? 'rgba(128,128,128,0.5)'
                        : isSelected
                            ? 'var(--seekora-select-active-color, inherit)'
                            : 'var(--seekora-select-color, inherit)',
                    fontWeight: isSelected ? 500 : 400,
                    opacity: opt.disabled ? 0.5 : 1,
                    transition: 'background-color 0.1s ease',
                } }, opt.label));
        })))));
};
