import React from "react";

export function Combobox({ items = [], value, defaultValue, onValueChange, placeholder = "Select…", searchPlaceholder = "Search…", emptyMessage = "No results.", disabled, className = "" }) {
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState("");
  const [internal, setInternal] = React.useState(defaultValue);
  const ref = React.useRef(null);
  const val = value !== undefined ? value : internal;
  const selected = items.find((i) => i.value === val);
  const shown = items.filter((i) => String(i.label).toLowerCase().includes(query.toLowerCase()));
  React.useEffect(() => {
    if (!open) return undefined;
    const away = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", away);
    return () => document.removeEventListener("mousedown", away);
  }, [open]);
  const pick = (v) => { if (value === undefined) setInternal(v); if (onValueChange) onValueChange(v); setOpen(false); setQuery(""); };
  return (
    <span ref={ref} style={{ position: "relative", display: "inline-block", width: "100%" }}>
      <button type="button" className={["o-select", className].filter(Boolean).join(" ")} data-slot="combobox-trigger" disabled={disabled}
        aria-haspopup="listbox" aria-expanded={open} onClick={() => setOpen(!open)}>
        <span className={["o-select__value", selected ? "" : "o-select__placeholder"].filter(Boolean).join(" ")}>{selected ? selected.label : placeholder}</span>
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m7 15 5 5 5-5" /><path d="m7 9 5-5 5 5" /></svg>
      </button>
      {open ? (
        <div className="o-popup" data-slot="combobox-popup" style={{ position: "absolute", zIndex: 50, insetInlineStart: 0, top: "calc(100% + 4px)", minWidth: "100%", overflow: "hidden" }}>
          <div className="o-command">
            <div className="o-command__input-row">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /></svg>
              <input className="o-command__input" style={{ height: "36px" }} autoFocus value={query} placeholder={searchPlaceholder} onChange={(e) => setQuery(e.target.value)} />
            </div>
            <div className="o-command__list o-scroll">
              {shown.length === 0 ? <div className="o-command__empty">{emptyMessage}</div> : shown.map((item) => (
                <div key={item.value} role="option" aria-selected={item.value === val} className="o-menu__item" style={{ display: "grid", gridTemplateColumns: "1rem 1fr" }} onClick={() => pick(item.value)}>
                  <span className="o-menu__check">{item.value === val ? <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5.252 12.7 10.2 18.63 18.748 5.37" /></svg> : null}</span>
                  <span>{item.label}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      ) : null}
    </span>
  );
}
