import React from "react";

export function Autocomplete({ items = [], value, defaultValue = "", onValueChange, placeholder = "Start typing…", emptyMessage = "No results.", className = "", ...props }) {
  const [internal, setInternal] = React.useState(defaultValue);
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const val = value !== undefined ? value : internal;
  const shown = items.filter((i) => String(i.label).toLowerCase().includes(String(val).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 set = (v) => { if (value === undefined) setInternal(v); if (onValueChange) onValueChange(v); };
  return (
    <span ref={ref} style={{ position: "relative", display: "inline-block", width: "100%" }} className={className}>
      <span className="o-input" data-slot="input-control">
        <input className="o-input__control" data-slot="autocomplete-input" value={val} placeholder={placeholder}
          onFocus={() => setOpen(true)} onChange={(e) => { set(e.target.value); setOpen(true); }} {...props} />
      </span>
      {open ? (
        <div className="o-popup" data-slot="autocomplete-popup" style={{ position: "absolute", zIndex: 50, insetInlineStart: 0, top: "calc(100% + 4px)", minWidth: "100%" }}>
          <div className="o-menu o-scroll" style={{ maxHeight: "16rem" }}>
            {shown.length === 0 ? <div className="o-command__empty">{emptyMessage}</div> : shown.map((item) => (
              <div key={item.value} className="o-menu__item" onClick={() => { set(String(item.label)); setOpen(false); }}>{item.label}</div>
            ))}
          </div>
        </div>
      ) : null}
    </span>
  );
}
