// =================================================================
// pw-screens-coins.jsx — Publisher Admin · Coins & Wallets
// =================================================================

const ledgerDate = (l) => l.created_at || l.at;
const ledgerReason = (l) => l.reason || l.event || "wallet entry";

const AssignCoinsPanel = ({ user, onAssign }) => {
  const [coins, setCoins] = React.useState(50);
  const [reason, setReason] = React.useState("Support bonus");
  const [mode, setMode] = React.useState("add");
  React.useEffect(() => { setCoins(50); setReason("Support bonus"); setMode("add"); }, [user?.id]);
  if (!user) return null;
  const signed = Math.abs(Number(coins || 0)) * (mode === "subtract" ? -1 : 1);
  const canSave = signed !== 0 && reason.trim();
  return (
    <div className="pw-adjust">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
        <div>
          <div style={{ fontWeight: 600, color: "var(--ink)" }}>Assign additional coins</div>
          <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 2 }}>Recorded in wallet ledger and audit history.</div>
        </div>
        <SegmentedControl value={mode} onChange={setMode} options={[{ label: "Add", value: "add" }, { label: "Correct", value: "subtract" }]}/>
      </div>
      <FieldGroup cols={2}>
        <FieldRow label="Coins">
          <NumberStepper value={Math.abs(Number(coins || 0))} onChange={setCoins} min={1} max={100000} step={10} suffix="coins"/>
        </FieldRow>
        <FieldRow label="Preview">
          <CoinChip amount={signed} tone={signed < 0 ? "neg" : "pos"}/>
        </FieldRow>
      </FieldGroup>
      <FieldRow label="Audit reason">
        <Input value={reason} onChange={e => setReason(e.target.value)} placeholder="Reason shown in audit history"/>
      </FieldRow>
      <Btn kind="primary" disabled={!canSave} icon={<IconCoin size={15}/>} onClick={() => onAssign({ delta_coins: signed, reason })} style={{ justifyContent: "center" }}>
        Assign coins
      </Btn>
      <style>{`
        .pw-adjust { display: flex; flex-direction: column; gap: 14px; border: 1px solid var(--line); border-radius: var(--r-md); padding: 14px; background: var(--panel-2); }
      `}</style>
    </div>
  );
};

const ReaderWalletDrawer = ({ user, onClose, onAssign }) => {
  const [detail, setDetail] = React.useState(user);
  React.useEffect(() => {
    if (!user) return;
    setDetail(user);
    if (window.__api.getConfig().live) {
      window.__api.read("getUserLedger", { params: { id: user.id || user.user_id }, query: { limit: 100 } })
        .then(res => setDetail(prev => ({ ...prev, ledger: res.entries || [] })))
        .catch(() => {});
    }
  }, [user?.id, user?.user_id]);
  React.useEffect(() => { if (user) setDetail(user); }, [user?.balance_coins, (user?.ledger || []).length]);
  const current = detail || user;
  return (
    <Drawer open={!!user} onClose={onClose} title="Reader wallet details" width={680}>
      {current && (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <div className="pw-reader-head">
            <span style={{ display: "inline-flex", alignItems: "center", gap: 12, minWidth: 0 }}>
              <Avatar name={current.email} size={42}/>
              <span style={{ minWidth: 0 }}>
                <strong style={{ color: "var(--ink)" }}>{current.email}</strong>
                <span style={{ display: "block", marginTop: 3, fontSize: 12.5, color: "var(--muted)", fontFamily: "var(--mono)" }}>{current.id || current.user_id}</span>
              </span>
            </span>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontSize: 11.5, color: "var(--muted)" }}>Wallet balance</div>
              <CoinChip amount={current.balance_coins}/>
            </div>
          </div>

          <AssignCoinsPanel user={current} onAssign={onAssign}/>

          <Card title="Audit history" subtitle="Wallet ledger entries for this reader." padded={false}>
            <DataTable rows={(current.ledger || []).map((r, i) => ({ ...r, _key: r.entry_id || `${r.at || r.created_at || "row"}-${r.event || r.reason || "entry"}-${i}` }))} keyField="_key" rowsPerPage={8} density="compact"
              empty={<EmptyState icon={<IconReceipt size={28}/>} title="No ledger history" description="Coin activity will appear here."/>}
              columns={[
                { key: "created_at", label: "Date", render: r => <span style={{ fontFamily: "var(--mono)", fontSize: 12 }}>{fmt.date(ledgerDate(r))}</span> },
                { key: "reason", label: "Reason", render: r => <span style={{ color: "var(--ink-2)" }}>{String(ledgerReason(r)).replace(/_/g, " ")}</span> },
                { key: "delta_coins", label: "Coins", align: "right", accessor: r => r.delta_coins ?? r.delta,
                  render: r => <CoinChip amount={Number(r.delta_coins ?? r.delta ?? 0)} tone={Number(r.delta_coins ?? r.delta ?? 0) < 0 ? "neg" : "pos"}/> },
              ]}/>
          </Card>
        </div>
      )}
      <style>{`
        .pw-reader-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 14px; border: 1px solid var(--line); border-radius: var(--r-md); padding: 14px; background: var(--panel); }
      `}</style>
    </Drawer>
  );
};

const CoinsScreen = ({ data, setData }) => {
  const [selected, setSelected] = React.useState(null);
  const [q, setQ] = React.useState("");
  const [status, setStatus] = React.useState("all");
  const [balance, setBalance] = React.useState("all");
  const users = data.users || [];
  const ledgerRows = users.flatMap(u => (u.ledger || []).map(l => ({ ...l, user: u.email })));
  const walletTotal = users.reduce((a, u) => a + Number(u.balance_coins || 0), 0);
  const coinsGranted = ledgerRows.filter(l => Number(l.delta ?? l.delta_coins ?? 0) > 0).reduce((a, l) => a + Number(l.delta ?? l.delta_coins ?? 0), 0);
  const coinsSpent = Math.abs(ledgerRows.filter(l => Number(l.delta ?? l.delta_coins ?? 0) < 0).reduce((a, l) => a + Number(l.delta ?? l.delta_coins ?? 0), 0));
  const manualCount = ledgerRows.filter(l => ["manual_grant", "support_adjustment", "manual_adjustment"].includes(l.event || l.reason)).length;
  const rows = users.filter(u => {
    const hay = `${u.email} ${u.id || u.user_id} ${u.status || ""}`.toLowerCase();
    const b = Number(u.balance_coins || 0);
    const statusOk = status === "all" || (u.status || "active") === status;
    const balanceOk = balance === "all" || (balance === "zero" ? b === 0 : balance === "low" ? b > 0 && b < 100 : b >= 100);
    return (!q || hay.includes(q.toLowerCase())) && statusOk && balanceOk;
  });

  const assign = ({ delta_coins, reason }) => {
    if (!selected) return;
    const userId = selected.id || selected.user_id;
    const entry = { at: new Date().toISOString(), event: "manual_adjustment", delta: delta_coins, reason };
    const idempotency = `adjust:${userId}:${Date.now()}`;
    window.__api.write("adjustUserCoins",
      d => ({ ...d, users: (d.users || []).map(u => (u.id || u.user_id) === userId
        ? { ...u, balance_coins: Number(u.balance_coins || 0) + delta_coins, ledger: [entry, ...(u.ledger || [])] }
        : u) }),
      { params: { id: userId }, body: { delta_coins, reason, idempotency_key: idempotency }, ok: "Coins assigned", err: "Couldn’t assign coins" });
    setSelected(prev => prev ? { ...prev, balance_coins: Number(prev.balance_coins || 0) + delta_coins, ledger: [entry, ...(prev.ledger || [])] } : prev);
  };

  return (
    <Screen>
      <PageHead icon={IconCoin} title="Coins & Wallets" subtitle="Search readers, review wallet history, and assign audited coin adjustments from reader details." />

      <KpiGrid>
        <StatCard label="Wallet balances" value={fmt.compact(walletTotal)} sub="coins outstanding" icon={<IconCoin size={16}/>}/>
        <StatCard label="Readers" value={fmt.compact(users.length)} sub="wallet accounts" icon={<IconUsers size={16}/>}/>
        <StatCard label="Coins granted" value={fmt.compact(coinsGranted)} sub="ledger credits" icon={<IconCheck size={16}/>}/>
        <StatCard label="Coins spent" value={fmt.compact(coinsSpent)} sub="ledger debits" icon={<IconGift size={16}/>}/>
        <StatCard label="Manual adjustments" value={manualCount} sub="audit entries" icon={<IconPencil size={16}/>}/>
      </KpiGrid>

      <Toolbar search={q} onSearchChange={setQ} searchPlaceholder="Search readers">
        <Select value={status} onChange={setStatus} style={{ width: 150 }} options={[{ label: "All statuses", value: "all" }, { label: "Active", value: "active" }, { label: "Paused", value: "paused" }]}/>
        <Select value={balance} onChange={setBalance} style={{ width: 170 }} options={[{ label: "All balances", value: "all" }, { label: "Zero", value: "zero" }, { label: "Low (<100)", value: "low" }, { label: "100+", value: "healthy" }]}/>
      </Toolbar>

      <Card title="Reader wallets" subtitle="Open a reader to view full audit history and assign coins." padded={false}>
        <DataTable rows={rows} keyField="id" rowsPerPage={8} onRowClick={setSelected}
          defaultSort={{ key: "balance_coins", dir: "desc" }}
          empty={<EmptyState icon={<IconUsers size={30}/>} title="No readers" description="No reader wallets match your filters."/>}
          columns={[
            { key: "email", label: "Reader", render: r => (
              <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}><Avatar name={r.email} size={26}/><span style={{ color: "var(--ink)" }}>{r.email}</span></span>) },
            { key: "status", label: "Status", render: r => <StatusPill status={r.status || "active"}/> },
            { key: "created_at", label: "Registered", align: "right", render: r => <span style={{ fontFamily: "var(--mono)", fontSize: 12 }}>{r.created_at ? fmt.date(r.created_at) : "—"}</span> },
            { key: "balance_coins", label: "Balance", align: "right", render: r => <CoinChip amount={r.balance_coins}/> },
            { key: "ledger", label: "History", sortable: false, align: "right", accessor: r => (r.ledger || []).length,
              render: r => <span style={{ fontSize: 12.5, color: "var(--muted)" }}>{(r.ledger || []).length} entries</span> },
            { key: "_v", label: "", sortable: false, align: "right", render: () => <IconChevR size={14} style={{ color: "var(--muted-2)" }}/> },
          ]}/>
      </Card>

      <ReaderWalletDrawer user={selected} onClose={() => setSelected(null)} onAssign={assign}/>
    </Screen>
  );
};

Object.assign(window, { CoinsScreen, ReaderWalletDrawer, AssignCoinsPanel });
