// Swaps list view — full table with filters

const { useState: useStateS } = React;

function ViewSwaps({ data, onSelectSwap }) {
  const { swaps, now } = data;
  const [filter, setFilter] = useStateS("active");
  const [direction, setDirection] = useStateS("all");
  const [query, setQuery] = useStateS("");

  let rows = swaps;
  if (filter === "active") rows = rows.filter((s) => !ZW.TERMINAL.has(s.state));
  if (filter === "terminal") rows = rows.filter((s) => ZW.TERMINAL.has(s.state));
  if (filter === "refund") rows = rows.filter((s) => ZW.REFUND_BRANCH.includes(s.state) || ZW.CLAIM_BRANCH.includes(s.state));
  if (filter === "stuck") rows = rows.filter((s) => s.stuck);
  if (direction !== "all") rows = rows.filter((s) => s.direction === direction);
  if (query) rows = rows.filter((s) => s.id.includes(query) || s.counterparty.includes(query));

  rows = [...rows].sort((a, b) => b.updatedAt - a.updatedAt);

  const filterTabs = [
    { id: "active", label: "Active", count: swaps.filter((s) => !ZW.TERMINAL.has(s.state)).length },
    { id: "stuck", label: "Stuck", count: swaps.filter((s) => s.stuck).length },
    { id: "refund", label: "Refund", count: swaps.filter((s) => ZW.REFUND_BRANCH.includes(s.state) || ZW.CLAIM_BRANCH.includes(s.state)).length },
    { id: "terminal", label: "Terminal", count: swaps.filter((s) => ZW.TERMINAL.has(s.state)).length },
    { id: "all", label: "All", count: swaps.length },
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", padding: 14, gap: 12, height: "100%", minHeight: 0 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, flex: "none" }}>
        <div style={{ display: "flex", gap: 4, background: "var(--bg-1)", padding: 3, borderRadius: 6, border: "1px solid var(--line-soft)" }}>
          {filterTabs.map((t) => (
            <button key={t.id} onClick={() => setFilter(t.id)}
              style={{
                background: filter === t.id ? "var(--bg-3)" : "transparent",
                border: "1px solid " + (filter === t.id ? "var(--line)" : "transparent"),
                color: filter === t.id ? "var(--fg-0)" : "var(--fg-2)",
                padding: "5px 10px", fontSize: 12, fontWeight: 500, borderRadius: 4, cursor: "pointer",
                display: "inline-flex", alignItems: "center", gap: 6,
              }}>
              {t.label}
              <span className="mono" style={{ fontSize: 10, color: "var(--fg-3)" }}>{t.count}</span>
            </button>
          ))}
        </div>
        <div style={{ display: "flex", gap: 4, background: "var(--bg-1)", padding: 3, borderRadius: 6, border: "1px solid var(--line-soft)" }}>
          {["all", "btc-to-zec", "zec-to-btc"].map((d) => (
            <button key={d} onClick={() => setDirection(d)}
              style={{
                background: direction === d ? "var(--bg-3)" : "transparent",
                border: "1px solid " + (direction === d ? "var(--line)" : "transparent"),
                color: direction === d ? "var(--fg-0)" : "var(--fg-2)",
                padding: "5px 10px", fontSize: 12, borderRadius: 4, cursor: "pointer",
              }}>
              {d === "all" ? "All directions" : d}
            </button>
          ))}
        </div>
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="search swap_id or counterparty…"
          className="mono"
          style={{
            flex: 1, maxWidth: 320,
            background: "var(--bg-1)", border: "1px solid var(--line)",
            borderRadius: 6, padding: "6px 10px", color: "var(--fg-0)", fontSize: 12,
            fontFamily: "var(--mono)",
            outline: "none",
          }}
        />
        <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--fg-3)" }}>
          {rows.length} of {swaps.length}
        </span>
        <Button size="sm" icon="↻">Refresh</Button>
        <Button size="sm" icon="⤓">Export CSV</Button>
      </div>

      <Panel padded={false} style={{ flex: 1, minHeight: 0 }} scrollable>
        <SwapsTable rows={rows} onSelect={onSelectSwap} now={now} />
      </Panel>
    </div>
  );
}

function SwapsTable({ rows, onSelect, now }) {
  const cols = "150px 90px 70px 1fr 110px 100px 70px 70px 80px";
  return (
    <div>
      <div style={{
        display: "grid", gridTemplateColumns: cols,
        padding: "9px 14px", fontSize: 10.5, color: "var(--fg-2)",
        letterSpacing: 0.4, textTransform: "uppercase", fontWeight: 600,
        borderBottom: "1px solid var(--line-soft)",
        position: "sticky", top: 0, background: "var(--bg-1)", zIndex: 1,
      }}>
        <span>Swap ID</span><span>Dir</span><span>Role</span>
        <span>State</span>
        <span style={{ textAlign: "right" }}>Amount</span>
        <span style={{ textAlign: "right" }}>USD</span>
        <span style={{ textAlign: "right" }}>P&L</span>
        <span style={{ textAlign: "right" }}>Age</span>
        <span style={{ textAlign: "right" }}>CSV</span>
      </div>
      {rows.map((s) => {
        const csvSecs = ZW.isFiniteNumber(s.csvDeadline) ? (s.csvDeadline - now) / 1000 : null;
        const csvWarn = csvSecs != null && csvSecs < 30 * 60;
        return (
          <div key={s.id} onClick={() => onSelect(s.id)}
            style={{
              display: "grid", gridTemplateColumns: cols,
              padding: "10px 14px", fontSize: 12.5, alignItems: "center",
              borderBottom: "1px solid var(--line-soft)", cursor: "pointer",
              background: s.stuck ? "color-mix(in oklch, var(--warn) 6%, transparent)" : "transparent",
            }}
            onMouseEnter={(e) => (e.currentTarget.style.background = "var(--bg-2)")}
            onMouseLeave={(e) => (e.currentTarget.style.background = s.stuck ? "color-mix(in oklch, var(--warn) 6%, transparent)" : "transparent")}>
            <span className="mono" style={{ fontSize: 12 }}>
              {s.stuck && <span style={{ color: "var(--warn)", marginRight: 4 }}>●</span>}
              {s.id}
            </span>
            <DirectionChip direction={s.direction} />
            <Badge tone={s.role === "alice" ? "alice" : "bob"} subtle>{s.role}</Badge>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <FSMStepperMini state={s.state} />
              <StateChip state={s.state} />
            </div>
            <span className="mono" style={{ textAlign: "right" }}>
              {s.direction === "btc-to-zec"
                ? <>{ZW.fmtSats(s.btcSats)}<span style={{ color: "var(--btc)", fontSize: 10, marginLeft: 3 }}>BTC</span></>
                : <>{ZW.fmtZats(s.zecZats)}<span style={{ color: "var(--zec)", fontSize: 10, marginLeft: 3 }}>ZEC</span></>}
            </span>
            <span className="mono" style={{ textAlign: "right", color: "var(--fg-2)" }}>{ZW.fmtUsd(s.usdValue)}</span>
            <span className="mono" style={{ textAlign: "right", color: s.pnlUsd ? "var(--ok)" : "var(--fg-3)" }}>
              {ZW.isFiniteNumber(s.pnlUsd) ? "+" + ZW.fmtUsd(s.pnlUsd) : ZW.NA}
            </span>
            <span className="mono" style={{ textAlign: "right", color: "var(--fg-2)", fontSize: 11 }}>{ZW.fmtRelTime(s.startedAt, now)}</span>
            <span className="mono" style={{ textAlign: "right", color: csvWarn ? "var(--warn)" : "var(--fg-3)", fontSize: 11 }}>
              {csvSecs != null ? ZW.fmtCountdown(csvSecs) : ZW.NA}
            </span>
          </div>
        );
      })}
      {rows.length === 0 && <Empty>No swaps match this filter.</Empty>}
    </div>
  );
}

Object.assign(window, { ViewSwaps });
