// Withdrawal Risk-Tier Approval — tabbed by tier (Medium & High default open).
// Each row: user, USD amount + sparkline, destination + chain + risk badge,
// KYC tier, AML band, inline approve/reject/EDD buttons.
// High-tier rows expand to show full EDD form inline (no nav).

function WithdrawalApprovals({ withdrawals, auditorMode }) {
  const [tier, setTier] = React.useState("medium");
  const [expanded, setExpanded] = React.useState(new Set());

  const byTier = {
    low:    withdrawals.filter(w => w.tier === "low"),
    medium: withdrawals.filter(w => w.tier === "medium"),
    high:   withdrawals.filter(w => w.tier === "high"),
  };
  const rows = byTier[tier];

  // High-tier rows expand by default
  React.useEffect(() => {
    if (tier === "high") setExpanded(new Set(byTier.high.map(w => w.id)));
    else setExpanded(new Set());
  }, [tier]);

  const toggle = (id) => {
    const s = new Set(expanded);
    s.has(id) ? s.delete(id) : s.add(id);
    setExpanded(s);
  };

  const totalAmt = rows.reduce((s, w) => s + w.amount, 0);

  return (
    <>
      <div className="app-subheader">
        <div className="subheader-title">Withdrawal Approvals</div>
        <div className="subheader-meta">{rows.length} pending · {formatUsd(totalAmt)} total</div>
        <div className="subheader-spacer" />
        <Segmented value={tier} onChange={setTier} options={[
          { value: "low",    label: "Low",    count: byTier.low.length },
          { value: "medium", label: "Medium", count: byTier.medium.length },
          { value: "high",   label: "High",   count: byTier.high.length },
        ]} />
        <Btn variant="outlined" icon={IDownload}>Export</Btn>
      </div>

      <div className="fbar">
        <span className="fg-3" style={{fontSize:11.5}}>
          {tier === "low"    && <><b style={{color:"var(--fg)"}}>Low tier · &lt; $5,000</b> &nbsp;·&nbsp; Auto-approved · logged · not surfaced</>}
          {tier === "medium" && <><b style={{color:"var(--fg)"}}>Medium tier · $5,000 – $25,000</b> &nbsp;·&nbsp; One-click reviewer approval</>}
          {tier === "high"   && <><b style={{color:"var(--fg)"}}>High tier · &gt; $25,000</b> &nbsp;·&nbsp; Compliance officer + <Term id="EDD">EDD</Term> <Term id="Attestation">attestation</Term> required</>}
        </span>
        <span className="fbar-spacer" />
        <FilterChip label="Chain" value="Any" />
        <FilterChip label="Asset" value="Any" />
        <FilterChip label="Dest. risk" value="Any" />
      </div>

      <div className="tbl-wrap">
        <div className="tbl-scroll">
          <table className="tbl">
            <thead>
              <tr>
                <th className="sticky-first" style={{paddingLeft:16}}>Withdrawal</th>
                <th>User</th>
                <th className="numeric">Amount</th>
                <th>Activity (30d)</th>
                <th>Destination</th>
                <th><Term id="KYC">KYC</Term></th>
                <th><Term id="AML">AML</Term></th>
                <th>Time</th>
                <th className="col-narrow">{/* actions */}</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((w, i) => {
                const isExp = expanded.has(w.id);
                return (
                  <React.Fragment key={w.id}>
                    <tr className={isExp ? "is-row-open" : ""} onClick={() => toggle(w.id)}>
                      <td className="sticky-first mono" style={{paddingLeft:16, color:"var(--fg-2)"}}>
                        <span style={{display:"inline-flex", alignItems:"center", gap:6}}>
                          {tier === "high" ? <IChevronD size={11} style={{ transform: isExp ? "" : "rotate(-90deg)", transition: "transform 0.1s" }}/> : null}
                          {w.id}
                        </span>
                      </td>
                      <td>
                        <span style={{display:"inline-flex", alignItems:"center", gap:8}}>
                          <Flag code={w.country} />
                          <span className="fg-1" style={{fontWeight:500}}>{w.user}</span>
                        </span>
                      </td>
                      <td className="numeric mono" style={{ fontWeight: w.amount >= 25000 ? 600 : 500, color: w.amount >= 25000 ? "var(--fg)" : "var(--fg-1)" }}>
                        {formatUsd(w.amount)}
                      </td>
                      <td>
                        <Sparkline data={window.sparkline(i*173 + w.amount, 30)} tone={w.amlBand === "High" ? "amber" : "fg-3"} />
                      </td>
                      <td>
                        <span className="dest-cell">
                          <ChainGlyph chain={w.chain} />
                          <span>{w.dest}</span>
                          <span className={`dest-risk dest-risk-${w.destRisk}`}>{w.destRisk}</span>
                        </span>
                      </td>
                      <td><span className="cell-kind-pill" style={{borderColor:"var(--line-soft)"}}>{w.kycTier}</span></td>
                      <td><StatusPill status={w.amlBand.toLowerCase()} /></td>
                      <td className="mono fg-3" style={{fontSize:11}}>{formatTime(w.ts)}</td>
                      <td className="col-narrow" onClick={e => e.stopPropagation()}>
                        <div className="row-actions">
                          {tier !== "high" ? (
                            <>
                              <Btn variant="filled" tone="accent" size="xs" icon={ICheck} disabled={auditorMode}>Approve</Btn>
                              <Btn variant="outlined" size="xs" disabled={auditorMode}>EDD</Btn>
                              <Btn variant="outlined" danger size="xs" icon={IX} disabled={auditorMode}>Reject</Btn>
                            </>
                          ) : (
                            <Btn variant="outlined" size="xs">{isExp ? "Collapse" : "Expand"}</Btn>
                          )}
                        </div>
                      </td>
                    </tr>
                    {tier === "high" && isExp && (
                      <tr className="wd-row-expanded">
                        <td colSpan={9}>
                          <HighTierEDD w={w} auditorMode={auditorMode} />
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                );
              })}
            </tbody>
          </table>
        </div>
        <div className="tbl-foot">
          <span>Showing <b>{rows.length}</b> withdrawals in <b style={{textTransform:"capitalize"}}>{tier}</b> tier</span>
          <span className="tbl-foot-spacer" />
          <span>Total: <b className="mono">{formatUsd(totalAmt)}</b></span>
        </div>
      </div>
    </>
  );
}

function HighTierEDD({ w, auditorMode }) {
  const [sof, setSof]      = React.useState("Salary");
  const [purpose, setPurp] = React.useState("Personal expenses");
  const [thirdParty, setTP]= React.useState("No");
  const [notes, setNotes]  = React.useState("");
  const [att, setAtt]      = React.useState(false);

  return (
    <div className="wd-edd">
      <div className="wd-edd-col">
        <h4><Term id="SoF">Source of Funds</Term></h4>
        <div className="wd-edd-field">
          <label>Declared origin</label>
          <select value={sof} onChange={e => setSof(e.target.value)} disabled={auditorMode}>
            <option>Salary</option>
            <option>Investment proceeds</option>
            <option>Business income</option>
            <option>Inheritance / gift</option>
            <option>Sale of property</option>
            <option>Loan / credit facility</option>
          </select>
        </div>
        <div className="wd-edd-field">
          <label>Supporting documentation</label>
          <div className="row" style={{gap:6, flexWrap:"wrap"}}>
            <span className="cell-kind-pill" style={{background:"var(--green-bg)", color:"var(--green-fg)", borderColor:"var(--green-bg)"}}>Bank statement · 2026-04</span>
            <span className="cell-kind-pill" style={{background:"var(--green-bg)", color:"var(--green-fg)", borderColor:"var(--green-bg)"}}>Audited financials · 2025</span>
            <span className="cell-kind-pill">Wire reference · {w.id}</span>
          </div>
        </div>
        <div className="wd-edd-field">
          <label>Purpose of transfer</label>
          <input value={purpose} onChange={e => setPurp(e.target.value)} disabled={auditorMode} />
        </div>
      </div>

      <div className="wd-edd-col">
        <h4>Destination Assessment</h4>
        <div className="wd-edd-field">
          <label>Wallet ownership</label>
          <select defaultValue="Self-custody (declared)" disabled={auditorMode}>
            <option>Self-custody (declared)</option>
            <option>Exchange — Coinbase Prime</option>
            <option>Exchange — Kraken</option>
            <option>Counterparty (third party)</option>
          </select>
        </div>
        <div className="wd-edd-field">
          <label>Third-party transfer</label>
          <select value={thirdParty} onChange={e => setTP(e.target.value)} disabled={auditorMode}>
            <option>No</option>
            <option>Yes — counterparty disclosed</option>
            <option>Yes — counterparty unknown (blocks)</option>
          </select>
        </div>
        <div className="wd-edd-field">
          <label>Chainalysis / Etherscan</label>
          <div className="row" style={{gap:6}}>
            <span className={`dest-risk dest-risk-${w.destRisk}`}>{w.destRisk} risk</span>
            <span className="fg-3" style={{fontSize:11}}>· Score 12/100 · No sanctioned exposure</span>
            <span className="right" style={{marginLeft:"auto"}}>
              <Btn variant="outlined" size="xs" icon={IExternal}>Open trace</Btn>
            </span>
          </div>
        </div>
      </div>

      <div className="wd-edd-col">
        <h4>Officer <Term id="Attestation">Attestation</Term></h4>
        <div className="wd-edd-field">
          <label>Internal note <span style={{color:"var(--red-fg)"}}>*</span></label>
          <textarea
            rows={4}
            placeholder="EDD review summary, attestation reasoning, any deviation from policy…"
            value={notes}
            onChange={e => setNotes(e.target.value)}
            disabled={auditorMode}
          />
        </div>
        <label className="check" style={{fontSize:11.5}}>
          <input type="checkbox" checked={att} onChange={e => setAtt(e.target.checked)} disabled={auditorMode} />
          <span className="check-box"><ICheck size={10} /></span>
          <span>I attest that <Term id="EDD">EDD</Term> has been performed per <Mono dim>§4.3</Mono> and the transfer is approved.</span>
        </label>
      </div>

      <div className="wd-edd-foot">
        <Mono dim>Audit reference {w.id} · alva.brennan@agio</Mono>
        <span className="right" style={{marginLeft:"auto"}} />
        <Btn variant="outlined" danger icon={IX} disabled={auditorMode}>Reject</Btn>
        <Btn variant="outlined" icon={ISend} disabled={auditorMode}>Request additional EDD</Btn>
        <Btn variant="filled" tone="accent" icon={ICheck}
          disabled={!notes.trim() || !att || auditorMode}>
          Approve {formatUsd(w.amount)}
        </Btn>
      </div>
    </div>
  );
}

Object.assign(window, { WithdrawalApprovals });
