// TransactionHistory.jsx — Account → Transaction history.
//
// Renée lens:
//   · C-2: every row names its type + facility + account, never a wall of
//     identical entries.
//   · C-4: no KPI-card overload — the page is a grouped timeline. Summary
//     facts live as a single metadata line under the title.
//   · C-5: sentence case, declarative; colour used sparingly (green = yield,
//     red = liquidation / failure). Everything else reads calm.
//   · C-3: loading / empty / error states.
//
// Each row expands to a disclosure with the full tx hash, block, network fee,
// and the compliance-gate result — the "evaluated on every action" story.

const TX_TYPE_BUCKET = {
  borrow: "borrow", repay: "repay",
  deposit: "collateral", withdraw: "collateral",
  supply: "lending", redeem: "lending", yield: "lending",
  liquidation: "other", claim: "other",
};

const toneColor = (tone) =>
  tone === "success" ? "var(--success)" :
  tone === "danger"  ? "var(--danger)"  : "var(--fg)";

const statusVariant = (status) =>
  status === "confirmed" ? "healthy" :
  status === "pending"   ? "at-risk" :
  status === "failed"    ? "frozen"  : "neutral";

const statusLabel = (status) =>
  status === "confirmed" ? "Confirmed" :
  status === "pending"   ? "Pending"   :
  status === "failed"    ? "Failed"    : status;

const TxRow = ({ tx, first }) => {
  const [open, setOpen] = React.useState(false);
  const iconBg = tx.tone === "success" ? "var(--green-10)" :
                 tx.tone === "danger"  ? "var(--red-10)"   : "var(--bg-alt)";
  const iconColor = tx.tone === "success" ? "var(--success)" :
                    tx.tone === "danger"  ? "var(--danger)"  : "var(--fg-muted)";
  return (
    <div style={{ borderTop: first ? "none" : "1px solid var(--border)" }}>
      <button onClick={() => setOpen(!open)} className="tx-row" style={{
        all: "unset", cursor: "pointer", width: "100%",
        display: "grid",
        gridTemplateColumns: "40px 1fr auto auto 20px",
        gap: 16, alignItems: "center",
        padding: "16px 24px",
        transition: "background var(--motion-fast)",
      }}
      onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-alt)"}
      onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
        <span style={{
          width: 36, height: 36, borderRadius: 9,
          background: iconBg, color: iconColor,
          display: "grid", placeItems: "center", flexShrink: 0,
        }}>
          <Icon name={tx.icon} size={16} stroke={1.5}/>
        </span>

        <div className="tx-main" style={{ minWidth: 0 }}>
          <div style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>
            {tx.label}
          </div>
          <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            {tx.facility}{tx.account ? <> · <span className="addr" style={{ fontSize: 12 }}>{tx.account}</span></> : null}
          </div>
        </div>

        <div className="tx-amount" style={{ textAlign: "right" }}>
          {tx.amount ? (
            <>
              <div className="tnum" style={{
                font: '600 15px/20px "Inter", sans-serif', color: toneColor(tx.tone),
              }}>{tx.amount}{tx.token ? <span style={{ color: "var(--fg-subtle)", fontWeight: 400 }}> {tx.token}</span> : null}</div>
              <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-faint)" }}>{tx.time}</div>
            </>
          ) : (
            <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{tx.time}</div>
          )}
        </div>

        <div className="tx-status">
          <StatusPill variant={statusVariant(tx.status)} dot={tx.status !== "confirmed"}>
            {statusLabel(tx.status)}
          </StatusPill>
        </div>

        <span style={{
          color: "var(--fg-faint)", justifySelf: "end",
          transform: open ? "rotate(90deg)" : "none",
          transition: "transform var(--motion-fast)",
        }}>
          <Icon name="chevron" size={14}/>
        </span>
      </button>

      {open && (
        <div style={{
          padding: "0 24px 18px 80px",
          display: "grid", gridTemplateColumns: "auto 1fr", columnGap: 16, rowGap: 8,
          font: '400 12px/18px "Inter", sans-serif',
        }}>
          <span style={{ color: "var(--fg-subtle)" }}>Transaction</span>
          <MonoAddr full={tx.hash} />
          <span style={{ color: "var(--fg-subtle)" }}>Block</span>
          <span className="addr tnum" style={{ color: "var(--fg-muted)" }}>{tx.block}</span>
          <span style={{ color: "var(--fg-subtle)" }}>Network fee</span>
          <span className="tnum" style={{ color: "var(--fg-muted)" }}>{tx.fee}</span>
          <span style={{ color: "var(--fg-subtle)" }}>Compliance gate</span>
          <span style={{
            color: tx.status === "failed" ? "var(--red-80)" :
                   tx.status === "pending" ? "var(--gold-80)" : "var(--green-80)",
            display: "inline-flex", alignItems: "center", gap: 6,
          }}>
            <Icon name={tx.status === "failed" ? "cross" : tx.status === "pending" ? "clock" : "check"} size={12} stroke={2}/>
            {tx.gate}
          </span>
        </div>
      )}
    </div>
  );
};

const TransactionHistory = ({ data, state = "live", onRetry }) => {
  const [filter, setFilter] = React.useState("all");
  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error")   return <PageError title="Couldn't load your transactions" body="Activity is read from the indexer; this might be a transient indexing delay." onRetry={onRetry} />;
  if (state === "empty") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
        <div>
          <Eyebrow>Account</Eyebrow>
          <h1 style={{ margin: "6px 0 6px", font: '700 32px/36px "Figtree", sans-serif', letterSpacing: "-0.015em", color: "var(--fg)" }}>Transaction history</h1>
          <div style={{ font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
            Every borrow, repay, deposit, withdraw, and lending action on your wallet.
          </div>
        </div>
        <section className="card" style={{ padding: 0 }}>
          <EmptyState
            icon="activity"
            title="No transactions yet"
            body="Once you borrow, deposit, or supply to a lending pool, your activity will appear here as a running ledger."
          />
        </section>
      </div>
    );
  }

  const filtered = data.items.filter((tx) =>
    filter === "all" ? true : TX_TYPE_BUCKET[tx.type] === filter
  );
  const groups = data.groups
    .map((g) => ({ label: g, items: filtered.filter((tx) => tx.group === g) }))
    .filter((g) => g.items.length > 0);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      {/* Header */}
      <div data-annot-note="C-4 metadata line, no KPI overload">
        <Eyebrow>Account</Eyebrow>
        <h1 style={{
          margin: "6px 0 6px",
          font: '700 32px/36px "Figtree", sans-serif',
          letterSpacing: "-0.015em", color: "var(--fg)",
        }}>Transaction history</h1>
        <div style={{
          font: '400 14px/22px "Inter", sans-serif', color: "var(--fg-subtle)",
          display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap",
        }}>
          <span className="tnum">{data.count} transactions</span>
          {data.pending > 0 && (
            <>
              <span style={{ color: "var(--fg-faint)" }}>·</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 5, color: "var(--gold-80)" }}>
                <span style={{ width: 6, height: 6, borderRadius: 3, background: "var(--gold-60)" }} />
                <span className="tnum">{data.pending}</span> pending
              </span>
            </>
          )}
        </div>
      </div>

      {/* Toolbar */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
        <SegmentControl
          value={filter}
          onChange={setFilter}
          options={[
            { value: "all",        label: "All",        count: data.items.length },
            { value: "borrow",     label: "Borrows",    count: data.items.filter(t => TX_TYPE_BUCKET[t.type] === "borrow").length },
            { value: "repay",      label: "Repayments", count: data.items.filter(t => TX_TYPE_BUCKET[t.type] === "repay").length },
            { value: "collateral", label: "Collateral", count: data.items.filter(t => TX_TYPE_BUCKET[t.type] === "collateral").length },
            { value: "lending",    label: "Lending",    count: data.items.filter(t => TX_TYPE_BUCKET[t.type] === "lending").length },
          ]}
        />
        <button className="btn btn--secondary btn--sm" type="button">
          <Icon name="external" size={13} stroke={1.6}/> Export CSV
        </button>
      </div>

      {/* Grouped timeline */}
      {groups.length === 0 ? (
        <section className="card" style={{ padding: 0 }}>
          <EmptyState
            icon="search"
            title="No transactions of this type"
            body="Adjust the filter above to see another category of activity."
            secondary={{ label: "Show all", onClick: () => setFilter("all") }}
          />
        </section>
      ) : (
        groups.map((g) => (
          <section key={g.label} data-annot-note="C-2 distinguishable rows">
            <div style={{
              font: '500 11px/16px "Inter", sans-serif',
              letterSpacing: "0.06em", textTransform: "uppercase",
              color: "var(--fg-subtle)", marginBottom: 8, paddingLeft: 2,
            }}>{g.label}</div>
            <section className="card" style={{ padding: 0, overflow: "hidden" }}>
              {g.items.map((tx, i) => (
                <TxRow key={i} tx={tx} first={i === 0} />
              ))}
            </section>
          </section>
        ))
      )}
    </div>
  );
};

Object.assign(window, { TransactionHistory, TxRow });
