// CommandPalette + FilterPanel + CSV password modal

// ──────────────────────────────────────────────────────────────────
// COMMAND PALETTE
// ──────────────────────────────────────────────────────────────────
function CommandPalette({ open, onClose, onRun }) {
  const [q, setQ] = React.useState("");
  const [active, setActive] = React.useState(0);
  const inputRef = React.useRef(null);
  const commands = window.AKEFIN_DATA.commands;

  // Filter
  const filtered = q
    ? commands.filter(c => c.label.toLowerCase().includes(q.toLowerCase()) || c.id.includes(q.toLowerCase()))
    : commands;

  // Group by kind
  const groups = {};
  filtered.forEach(c => {
    if (!groups[c.kind]) groups[c.kind] = [];
    groups[c.kind].push(c);
  });
  const groupOrder = ["action", "batch", "nav", "search", "setting"];
  const groupLabels = { action: "ACTIONS", batch: "BATCH", nav: "NAVIGATE", search: "SEARCH", setting: "SETTINGS" };

  // Flat ordered list for keyboard nav
  const flat = [];
  groupOrder.forEach(g => { if (groups[g]) flat.push(...groups[g]); });

  React.useEffect(() => { setActive(0); }, [q]);
  React.useEffect(() => {
    if (open) {
      setQ("");
      setTimeout(() => inputRef.current?.focus(), 10);
    }
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") { onClose(); }
      else if (e.key === "ArrowDown") { e.preventDefault(); setActive(a => Math.min(flat.length - 1, a + 1)); }
      else if (e.key === "ArrowUp")   { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
      else if (e.key === "Enter")     { e.preventDefault(); if (flat[active]) onRun(flat[active]); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, flat, active, onClose, onRun]);

  if (!open) return null;

  let idx = -1;
  return (
    <div className="cp-overlay" onClick={onClose}>
      <div className="cp-panel" onClick={e => e.stopPropagation()}>
        <div className="cp-head">
          <Icon name="search" size={14} color="var(--fg-muted)" />
          <input ref={inputRef} type="text" value={q} onChange={e => setQ(e.target.value)}
            placeholder="Search commands · accounts · payees…" />
          <span className="cp-kbd">ESC</span>
        </div>
        <div className="cp-body">
          {groupOrder.filter(g => groups[g]?.length).map(g => (
            <div key={g} className="cp-group">
              <div className="cp-group-label">{groupLabels[g]}</div>
              {groups[g].map(c => {
                idx++;
                const isActive = idx === active;
                return (
                  <button key={c.id}
                    className={`cp-item ${isActive ? "active" : ""}`}
                    onMouseEnter={() => setActive(idx)}
                    onClick={() => onRun(c)}>
                    <span className="cp-icon"><Icon name={c.icon} size={14} color="currentColor" /></span>
                    <span className="cp-label">{c.label}</span>
                    <span className="cp-hint">{c.hint}</span>
                  </button>
                );
              })}
            </div>
          ))}
          {flat.length === 0 && (
            <div className="cp-empty">No commands match · try "approve" or "import"</div>
          )}
        </div>
        <div className="cp-foot">
          <span><span className="cp-key">↑↓</span> navigate</span>
          <span><span className="cp-key">⏎</span> run</span>
          <span><span className="cp-key">esc</span> close</span>
          <span style={{ marginLeft: "auto" }}>{flat.length} commands</span>
        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────
// FILTER PANEL — for review queue
// ──────────────────────────────────────────────────────────────────
const DEFAULT_FILTERS = {
  dateRange: "all",
  dateFrom: "",
  dateTo: "",
  categories: new Set(),
  tiers: new Set(),
  confidenceMin: 0,
  ccy: new Set(),
};

function FilterPanel({ open, filters, setFilters, onClose, onApply, activeCount }) {
  const cats = window.AKEFIN_DATA.categories;
  if (!open) return null;

  const toggleSet = (key, val) => {
    setFilters(prev => {
      const s = new Set(prev[key]);
      s.has(val) ? s.delete(val) : s.add(val);
      return { ...prev, [key]: s };
    });
  };

  return (
    <div className="filter-panel">
      <div className="filter-row">
        <div className="filter-eyebrow">DATE</div>
        <div className="filter-options">
          {["today", "7d", "30d", "this-month", "all", "custom"].map(d => (
            <button key={d}
              className={`filter-pill ${filters.dateRange === d ? "active" : ""}`}
              onClick={() => setFilters(f => ({ ...f, dateRange: d }))}>
              {d === "7d" ? "LAST 7d" : d === "30d" ? "LAST 30d" : d.replace("-", " ").toUpperCase()}
            </button>
          ))}
          {filters.dateRange === "custom" && (
            <span className="filter-custom-dates">
              <input className="filter-date" type="date" value={filters.dateFrom} onChange={e => setFilters(f => ({...f, dateFrom: e.target.value}))} />
              <span className="muted">→</span>
              <input className="filter-date" type="date" value={filters.dateTo} onChange={e => setFilters(f => ({...f, dateTo: e.target.value}))} />
            </span>
          )}
        </div>
      </div>

      <div className="filter-row">
        <div className="filter-eyebrow">CATEGORY</div>
        <div className="filter-options">
          {cats.map(c => (
            <button key={c}
              className={`filter-pill ${filters.categories.has(c) ? "active" : ""}`}
              onClick={() => toggleSet("categories", c)}>
              {c}
            </button>
          ))}
        </div>
      </div>

      <div className="filter-row">
        <div className="filter-eyebrow">TIER</div>
        <div className="filter-options">
          {["rules", "llm", "agent", "unmatched"].map(t => (
            <button key={t}
              className={`filter-pill tier-${t} ${filters.tiers.has(t) ? "active" : ""}`}
              onClick={() => toggleSet("tiers", t)}>
              {t.toUpperCase()}
            </button>
          ))}
        </div>
      </div>

      <div className="filter-row">
        <div className="filter-eyebrow">CCY</div>
        <div className="filter-options">
          {["KRW", "TRY", "JPY", "EUR", "USD"].map(c => (
            <button key={c}
              className={`filter-pill ${filters.ccy.has(c) ? "active" : ""}`}
              onClick={() => toggleSet("ccy", c)}>
              {c}
            </button>
          ))}
        </div>
      </div>

      <div className="filter-row">
        <div className="filter-eyebrow">MIN CONFIDENCE</div>
        <div className="filter-slider-wrap">
          <input className="filter-slider" type="range" min="0" max="1" step="0.05"
            value={filters.confidenceMin}
            onChange={e => setFilters(f => ({...f, confidenceMin: parseFloat(e.target.value)}))} />
          <span className="filter-conf-val mono">{filters.confidenceMin.toFixed(2)}</span>
        </div>
      </div>

      <div className="filter-foot">
        <span className="filter-active-count">
          {activeCount > 0 ? `${activeCount} filter${activeCount > 1 ? "s" : ""} active` : "No active filters"}
        </span>
        <div style={{ flex: 1 }}></div>
        <button className="btn" onClick={() => setFilters({ ...DEFAULT_FILTERS, categories: new Set(), tiers: new Set(), ccy: new Set() })}>CLEAR</button>
        <button className="btn primary" onClick={onClose}>DONE</button>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────
// CSV IMPORT MODAL — with password
// ──────────────────────────────────────────────────────────────────
function CsvImportModal({ open, onClose, onSubmit }) {
  const [file, setFile] = React.useState(null);
  const [password, setPassword] = React.useState("");
  const [entity, setEntity] = React.useState("personal");
  const [showPw, setShowPw] = React.useState(false);

  if (!open) return null;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div className="modal-eyebrow">IMPORT · TIER 0</div>
          <h2 className="modal-title">Import Toss CSV</h2>
          <button className="modal-close" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div className="modal-body">
          <div className="form-field">
            <label className="form-lbl">CSV FILE</label>
            <div className="file-drop">
              <Icon name="import" size={16} color="var(--fg-muted)" />
              <span className="file-drop-text">
                {file
                  ? <span className="mono">{file}</span>
                  : <>Drop CSV here, or <button className="file-pick" onClick={() => setFile("toss-export-2026-03.csv")}>choose file</button></>}
              </span>
              <span className="file-meta">.csv · UTF-8</span>
            </div>
          </div>

          <div className="form-field">
            <label className="form-lbl">PASSWORD <span className="form-lbl-note">— Toss exports are usually encrypted with your account password</span></label>
            <div className="pw-input">
              <input
                type={showPw ? "text" : "password"}
                placeholder="Required for encrypted exports"
                value={password}
                onChange={e => setPassword(e.target.value)}
              />
              <button className="pw-toggle" onClick={() => setShowPw(s => !s)}>{showPw ? "HIDE" : "SHOW"}</button>
            </div>
            <div className="form-help">Password is held in memory only · never written to disk or git · cleared on import complete</div>
          </div>

          <div className="form-field">
            <label className="form-lbl">ENTITY</label>
            <div className="entity-radio">
              {[
                { id: "personal", label: "Personal", color: "var(--entity-personal)" },
                { id: "tfox",     label: "9TFox",    color: "var(--entity-9tfox)" },
                { id: "finacode", label: "Finacode", color: "var(--entity-finacode)" },
              ].map(e => (
                <label key={e.id} className={`entity-radio-item ${entity === e.id ? "active" : ""}`}>
                  <input type="radio" name="entity" checked={entity === e.id} onChange={() => setEntity(e.id)} />
                  <span className="stripe" style={{ background: e.color }}></span>
                  <span>{e.label}</span>
                </label>
              ))}
            </div>
          </div>

          <div className="form-field">
            <label className="form-lbl">PIPELINE</label>
            <div className="pipeline-stack term-frame" style={{ marginBottom: 0 }}>
              <div className="term-frame-body" style={{ paddingTop: 8, paddingBottom: 8 }}>
                <span className="m">→</span> decrypt (password)
                {"\n"}<span className="m">→</span> parse 247 rows estimated
                {"\n"}<span className="m">→</span> tier 1: 47 active rules
                {"\n"}<span className="m">→</span> tier 2: LLM (gpt-4o-mini)
                {"\n"}<span className="m">→</span> tier 3: agent (claude-haiku)
                {"\n"}<span className="m">→</span> stage unmatched for review
              </div>
            </div>
          </div>
        </div>
        <div className="modal-foot">
          <Btn onClick={onClose}>CANCEL</Btn>
          <div style={{ flex: 1 }}></div>
          <Btn variant="primary" onClick={() => { onSubmit({ file, password, entity }); }}>
            <Icon name="import" size={13} /> RUN IMPORT
          </Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CommandPalette, FilterPanel, CsvImportModal, DEFAULT_FILTERS });
