/* Traces list screen */

const TracesList = ({ onOpenTrace }) => {
  const [verdictFilter, setVerdictFilter] = React.useState("all");
  const [appFilter, setAppFilter] = React.useState("all");
  const [density, setDensity] = React.useState("comfortable");
  const [search, setSearch] = React.useState("");

  const allRows = React.useMemo(() => {
    // Synthesize 24 rows from the recentTraces seed
    const seed = SCENARIO.recentTraces;
    return seed.concat(seed.slice(0, 6).map((t, i) => ({ ...t, time: `10:${(10 - i).toString().padStart(2, "0")}`, id: t.id.replace(/\d/, () => String(i)) }))).slice(0, 18);
  }, []);

  const filtered = allRows.filter((r) => {
    if (verdictFilter !== "all" && (r.verdict === "contradicted" ? "contra" : r.verdict) !== verdictFilter) return false;
    if (appFilter !== "all" && r.app !== appFilter) return false;
    if (search && !`${r.id} ${r.app} ${r.purpose}`.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  return (
    <>
      <header className="page-header">
        <div className="page-header__inner">
          <div className="page-header__eyebrow">Workspace</div>
          <h1>Traces</h1>
          <p className="page-header__sub">Every LLM call wrapped by Attestia in this tenant.</p>
        </div>
        <div className="page-actions">
          <Button variant="secondary" size="sm" icon={window.Icon.download({ size: 14 })}>Export</Button>
          <Button variant="secondary" size="sm" icon={window.Icon.fileCheck({ size: 14 })}>Generate pack from selection</Button>
        </div>
      </header>

      <div className="toolbar">
        <div className="search-input">
          {window.Icon.search({ size: 14 })}
          <input placeholder="Search by trace ID, user-tag, or text…" value={search} onChange={(e) => setSearch(e.target.value)} />
          <kbd className="kbd">/</kbd>
        </div>
      </div>

      <div className="toolbar" style={{ marginBottom: "var(--space-3)" }}>
        <FilterChip
          label="Verdict"
          options={[
            { v: "all", label: "All" },
            { v: "verified", label: "Verified" },
            { v: "partial", label: "Partial" },
            { v: "unverif", label: "Unverifiable" },
            { v: "contra", label: "Contradicted" },
          ]}
          value={verdictFilter}
          onChange={setVerdictFilter}
        />
        <FilterChip
          label="App"
          options={[{ v: "all", label: "All apps" }].concat(SCENARIO.apps.map((a) => ({ v: a.name, label: a.name })))}
          value={appFilter}
          onChange={setAppFilter}
        />
        <FilterChip
          label="Date"
          options={[{ v: "7d", label: "Last 7 days" }, { v: "30d", label: "Last 30 days" }, { v: "q", label: "This quarter" }]}
          value="7d"
          onChange={() => {}}
        />
        <span className="spacer" />
        <span className="text-xs muted">Showing {filtered.length} of 24,891</span>
        <div className="segmented density-toggle">
          <button className={density === "comfortable" ? "active" : ""} onClick={() => setDensity("comfortable")}>Comfortable</button>
          <button className={density === "compact" ? "active" : ""} onClick={() => setDensity("compact")}>Compact</button>
        </div>
      </div>

      <div data-density={density}>
        <Card padded={false}>
          <table className="table">
            <thead>
              <tr>
                <th style={{ width: 36 }}><input type="checkbox" /></th>
                <th style={{ width: 80 }}>Time</th>
                <th style={{ width: 160 }}>Trace ID</th>
                <th>App</th>
                <th>Purpose</th>
                <th>Verdict</th>
                <th style={{ width: 90, textAlign: "right" }}>Tokens</th>
                <th style={{ width: 80, textAlign: "right" }}>Cost</th>
                <th style={{ width: 32 }} />
              </tr>
            </thead>
            <tbody>
              {filtered.map((t, i) => (
                <tr key={i} className="clickable" onClick={() => onOpenTrace(t.id)}>
                  <td onClick={(e) => e.stopPropagation()}><input type="checkbox" /></td>
                  <td className="mono text-sm muted">{t.time}</td>
                  <td><span className="hash-chip" style={{ background: "transparent", border: "none", padding: 0 }}>{t.id}</span></td>
                  <td className="fw-500">{t.app}</td>
                  <td><span className="tr-purpose">{t.purpose}</span></td>
                  <td><Verdict kind={t.verdict === "contradicted" ? "contra" : t.verdict} /></td>
                  <td className="mono text-sm tabular" style={{ textAlign: "right" }}>{t.tokens.toLocaleString()}</td>
                  <td className="mono text-sm tabular" style={{ textAlign: "right" }}>{t.cost}</td>
                  <td style={{ color: "var(--ink-4)" }}>{window.Icon.chevronRight({ size: 14 })}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: "var(--space-4)", fontSize: 12.5, color: "var(--ink-3)" }}>
        <span>Page 1 of 1,245</span>
        <div className="row gap-2">
          <Button variant="secondary" size="sm" disabled>← Prev</Button>
          <Button variant="secondary" size="sm">Next →</Button>
        </div>
      </div>
    </>
  );
};

const FilterChip = ({ label, options, value, onChange }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);
  const current = options.find((o) => o.v === value);
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        className={`filter-chip ${value !== "all" && value !== "7d" ? "filter-chip--active" : ""}`}
        onClick={() => setOpen((o) => !o)}
      >
        <span className="muted">{label}:</span>
        <span>{current?.label}</span>
        {window.Icon.chevronDown({ size: 12 })}
      </button>
      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 4px)", left: 0, zIndex: 200,
          background: "var(--paper)", border: "1px solid var(--rule)",
          borderRadius: "var(--radius-md)", padding: 4, minWidth: 160,
          boxShadow: "var(--shadow-md)"
        }}>
          {options.map((o) => (
            <button
              key={o.v}
              onClick={() => { onChange(o.v); setOpen(false); }}
              style={{
                width: "100%", padding: "8px 10px", fontSize: 13,
                background: value === o.v ? "var(--paper-alt)" : "transparent",
                border: "none", borderRadius: 4, textAlign: "left",
                color: "var(--ink-1)", fontWeight: value === o.v ? 600 : 400,
              }}
            >{o.label}</button>
          ))}
        </div>
      )}
    </div>
  );
};

window.TracesList = TracesList;
