import React from "react";

export function Command({ groups = [], placeholder = "Type a command or search…", emptyMessage = "No results found.", onSelect, className = "" }) {
  const [query, setQuery] = React.useState("");
  const filtered = groups
    .map((grp) => ({ label: grp.label, items: grp.items.filter((i) => String(i.label).toLowerCase().includes(query.toLowerCase())) }))
    .filter((grp) => grp.items.length > 0);
  return (
    <div className={["o-command", className].filter(Boolean).join(" ")} data-slot="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" data-slot="command-input" value={query} placeholder={placeholder} onChange={(e) => setQuery(e.target.value)} />
      </div>
      <div className="o-command__list o-scroll" data-slot="command-list" role="listbox">
        {filtered.length === 0 ? <div className="o-command__empty">{emptyMessage}</div> : filtered.map((grp) => (
          <div key={grp.label || "ungrouped"} role="group">
            {grp.label ? <div className="o-menu__label">{grp.label}</div> : null}
            {grp.items.map((item) => (
              <div key={item.value || item.label} role="option" aria-selected={false} className="o-menu__item" data-slot="command-item"
                onClick={() => onSelect && onSelect(item)}>{item.icon}{item.label}{item.shortcut ? <span className="o-menu__shortcut">{item.shortcut}</span> : null}</div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}
