// astrail-extras.jsx — Astrail demo additions
// Accounting fields on payout lines, recipient AML screening, Xero / CSV export,
// auditor payout report, idle-funds (Aave) module, compliance & accounting settings,
// new-run flow (CSV upload or address book).
// All data is demo data. Loads after nvx-settings.jsx and before nvx-app.jsx.

// ── Helpers ─────────────────────────────────────────────────────
const fakeHex = (seed, len = 64) => {
  let h = 2166136261;
  for (let i = 0; i < seed.length; i++) { h ^= seed.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
  let out = '';
  while (out.length < len) {
    h ^= h << 13; h >>>= 0; h ^= h >>> 17; h ^= h << 5; h >>>= 0;
    out += h.toString(16).padStart(8, '0');
  }
  return out.slice(0, len);
};
const txHashFor = (run) => run.chain === 'EVM' ? '0x' + fakeHex('tx' + run.id) : fakeHex('tx' + run.id);
const shortHash = (h, a = 6, b = 4) => h.length > a + b + 1 ? `${h.slice(0, a)}…${h.slice(-b)}` : h;
const runDateLabel = (run) => new Date(run.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
const xeroDate = (iso) => { const d = new Date(iso); return `${String(d.getDate()).padStart(2, '0')}/${String(d.getMonth() + 1).padStart(2, '0')}/${d.getFullYear()}`; };
const csvCell = (v) => { const s = v == null ? '' : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
const toCsv = (rows) => rows.map(r => r.map(csvCell).join(',')).join('\n');
const downloadFile = (name, text, mime = 'text/csv;charset=utf-8') => {
  const blob = new Blob(['﻿' + text], { type: mime });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = name; document.body.appendChild(a); a.click();
  setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 200);
};
const periodOf = (run) => {
  const m = run.name.match(/^(January|February|March|April|May|June|July|August|September|October|November|December) (\d{4})/);
  if (m) return `${m[1].slice(0, 3)} ${m[2]}`;
  return run.name;
};

// Accounting data per recipient (demo)
const ACCT = {
  1: { doc: 'CTR-2024-017', kind: 'Salary' },
  2: { doc: 'CTR-2025-003', kind: 'Salary' },
  3: { doc: 'CTR-2023-041', kind: 'Salary' },
  4: { doc: 'CTR-2025-022', kind: 'Salary (part-time)' },
  5: { doc: 'INV-EK-0412',  kind: 'Affiliate commission', risk: 'low', score: 12 },
  6: { doc: 'CTR-2024-031', kind: 'Salary' },
  7: { doc: 'INV-GP-0098',  kind: 'Affiliate commission', risk: 'high', score: 87,
       note: '34% of incoming funds from an exchange on the OFAC SDN list' },
  8: { doc: 'INV-HA-2604',  kind: 'Server hosting' },
};

const SIGNER_TIMES = {
  'PR-023': ['Apr 1, 2026 · 09:41', 'Apr 1, 2026 · 11:02'],
  'PR-022': ['Mar 15, 2026 · 10:05', 'Mar 15, 2026 · 10:47'],
  'PR-021': ['Mar 1, 2026 · 09:20', 'Mar 1, 2026 · 12:15'],
  'PR-020': ['Feb 15, 2026 · 14:02', 'Feb 15, 2026 · 16:30'],
  'PR-018': ['Jan 1, 2026 · 10:11', 'Jan 1, 2026 · 10:58'],
};

// Lines of a run with accounting + AML + on-chain data
const buildRunLines = (run) => {
  const { MOCK } = window;
  const period = periodOf(run);
  const isDone = run.status === 'confirmed';
  return MOCK.payrollRecipients.map((r, i) => {
    const a = ACCT[r.id] || { doc: '', kind: 'Payment' };
    const risk = isDone ? 'clear' : (a.risk === 'high' ? 'high' : 'clear');
    return {
      ...r,
      address: run.chain === 'EVM' ? '0x' + fakeHex('addr' + r.id, 40) : r.address,
      doc: a.doc,
      purpose: `${a.kind} · ${period}`,
      risk, riskScore: risk === 'high' ? a.score : (a.risk === 'high' ? 9 : (a.score || 4 + (r.id * 3) % 9)),
      riskNote: risk === 'high' ? a.note : null,
      transferIndex: i,
      status: isDone ? 'confirmed' : 'pending',
    };
  });
};

const runMeta = (run) => {
  const isTron = run.chain === 'Tron';
  return {
    wallet: isTron ? 'Tron Treasury (multisig 2 of 3)' : 'Operations Safe (2 of 3)',
    walletAddr: isTron ? 'TQx7wW3fK9pZ2m8sJv1hR6cN4bY5aE8dLu' : '0x8B3a' + fakeHex('safe', 30) + 'c41D',
    contract: isTron ? 'Astrail batch contract (TRON)' : 'Safe MultiSend 1.4.1 (canonical, deployed by Safe)',
    token: isTron ? 'USDT (TRC-20)' : 'USDT (ERC-20)',
    explorer: isTron ? 'Tronscan' : 'Etherscan',
    fee: isTron ? '152 TRX (≈ $38.40), energy rented' : '0.0061 ETH (≈ $21.70)',
    feeUsd: isTron ? 38.4 : 21.7,
    block: isTron ? 71_204_388 + run.id.charCodeAt(4) * 1000 : 22_418_090 + run.id.charCodeAt(4) * 100,
  };
};

// ── Small UI bits ───────────────────────────────────────────────
const RiskPill = ({ risk, score }) => {
  if (risk === 'high') return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 999, background: 'var(--col-error-bg)', color: 'var(--col-error)', whiteSpace: 'nowrap' }}>
      High risk · {score}
    </span>);
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 999, background: 'var(--col-success-bg)', color: 'var(--col-success)', whiteSpace: 'nowrap' }}>
      Clear · {score}
    </span>);
};

const KV = ({ k, v, mono, w = 170 }) =>
  <div style={{ display: 'flex', gap: 12, padding: '6px 0', borderBottom: '1px solid var(--col-border-s)', fontSize: 13 }}>
    <span style={{ width: w, flexShrink: 0, color: 'var(--col-text-3)' }}>{k}</span>
    <span style={{ color: 'var(--col-text)', fontWeight: 500, wordBreak: 'break-all', fontVariantNumeric: 'tabular-nums', ...(mono ? { fontFamily: "'SF Mono','Fira Code',monospace", fontSize: 12 } : {}) }}>{v}</span>
  </div>;

// ── Exports ─────────────────────────────────────────────────────
const exportXero = (run, lines, addToast) => {
  const meta = runMeta(run);
  const hash = txHashFor(run);
  const paid = lines.filter(l => l.risk !== 'high');
  const rows = [['*Date', '*Amount', 'Payee', 'Description', 'Reference']];
  paid.forEach(l => rows.push([xeroDate(run.date), (-l.amount).toFixed(2), l.name, l.purpose, `${l.doc} | ${run.id} | tx ${hash} #${l.transferIndex + 1}`]));
  rows.push([xeroDate(run.date), (-meta.feeUsd).toFixed(2), run.chain === 'Tron' ? 'TRON network' : 'Ethereum network', `Network fee · ${run.name}`, `${run.id} | tx ${hash}`]);
  downloadFile(`astrail-${run.id}-xero-bank-statement.csv`, toCsv(rows));
  addToast && addToast('Xero bank statement CSV downloaded', 'success');
};

const exportLinesCsv = (run, lines, addToast) => {
  const hash = run.status === 'confirmed' ? txHashFor(run) : '';
  const rows = [['run_id', 'run_name', 'date', 'network', 'token', 'recipient', 'address', 'amount', 'invoice_or_contract', 'purpose', 'aml_result', 'aml_score', 'tx_hash', 'transfer_no', 'status']];
  lines.forEach(l => rows.push([run.id, run.name, run.date, run.chain, 'USDT', l.name, l.address, l.amount.toFixed(2), l.doc, l.purpose, l.risk, l.riskScore, hash, hash ? l.transferIndex + 1 : '', l.risk === 'high' ? 'excluded' : l.status]));
  downloadFile(`astrail-${run.id}-payout-lines.csv`, toCsv(rows));
  addToast && addToast('Payout CSV downloaded', 'success');
};

const exportRunsCsv = (runs, addToast) => {
  const rows = [['run_id', 'name', 'date', 'network', 'recipients', 'total_usdt', 'status', 'tx_hash']];
  runs.forEach(r => rows.push([r.id, r.name, r.date, r.chain, r.recipients, r.total.toFixed(2), r.status, r.status === 'confirmed' ? txHashFor(r) : '']));
  downloadFile('astrail-payout-runs.csv', toCsv(rows));
  addToast && addToast('Runs CSV downloaded', 'success');
};

// ── Audit log (hash-chained) ────────────────────────────────────
const buildAuditLog = (run) => {
  const isDone = run.status === 'confirmed';
  const times = SIGNER_TIMES[run.id] || ['May 1, 2026 · 10:22', null];
  const d = runDateLabel(run);
  const entries = [
    { actor: 'A. Kovalenko (Accountant)', action: `drafted ${run.id} from CSV, ${run.recipients} lines`, time: `${d} · 09:14` },
    { actor: 'System', action: 'pre-flight: addresses valid, balance sufficient, AML screening by AMLBot', time: `${d} · 09:14` },
    { actor: 'Alice Johnson (Owner)', action: `signed in ${run.chain === 'Tron' ? 'TronLink' : 'Safe app'} (1 of 2)`, time: times[0] },
  ];
  if (isDone) {
    entries.push({ actor: 'Boris Kovalev (Approver)', action: 'signed in wallet (2 of 2) — threshold met', time: times[1] });
    entries.push({ actor: 'System', action: `executed on-chain, block ${runMeta(run).block.toLocaleString('en-US')}`, time: times[1] });
    entries.push({ actor: 'System', action: 'reconciled with chain: all transfers found, amounts match', time: times[1] });
  } else {
    entries.push({ actor: 'System', action: 'approval request sent to Boris Kovalev', time: times[0] });
  }
  let prev = '0'.repeat(64);
  return entries.map(e => { const h = fakeHex(prev + e.actor + e.action + e.time); const out = { ...e, prev, hash: h }; prev = h; return out; });
};

// ── Payout report modal (for auditors) ──────────────────────────
const PayoutReportModal = ({ run, lines, onClose, addToast }) => {
  const meta = runMeta(run);
  const isDone = run.status === 'confirmed';
  const hash = txHashFor(run);
  const log = buildAuditLog(run);
  const total = lines.filter(l => l.risk !== 'high').reduce((s, l) => s + l.amount, 0);
  const th = { textAlign: 'left', fontSize: 11, fontWeight: 600, color: 'var(--col-text-3)', padding: '6px 8px', borderBottom: '1px solid var(--col-border)' };
  const td = { fontSize: 12, padding: '6px 8px', borderBottom: '1px solid var(--col-border-s)', color: 'var(--col-text)', verticalAlign: 'top' };
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal astrail-print-area" onClick={e => e.stopPropagation()} style={{ width: 860, maxWidth: '94vw', maxHeight: '90vh', overflowY: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 18 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, color: 'var(--col-text-3)', marginBottom: 4 }}>Payout report · Astrail</div>
            <div className="modal-title" style={{ marginBottom: 2 }}>{run.name} · {run.id}</div>
            <div style={{ fontSize: 13, color: 'var(--col-text-2)' }}>Acme Corp Pte. Ltd. · generated {new Date().toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}</div>
          </div>
          <div className="no-print" style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn-secondary btn-sm" onClick={() => exportLinesCsv(run, lines, addToast)}><IcoDownload size={13} /> CSV</button>
            <button className="btn btn-secondary btn-sm" onClick={() => exportXero(run, lines, addToast)}><IcoDownload size={13} /> Xero CSV</button>
            <button className="btn btn-primary btn-sm" onClick={() => window.print()}>Print / PDF</button>
            <button className="btn btn-ghost btn-sm" onClick={onClose}><IcoX size={14} /></button>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 20 }}>
          <div>
            <KV k="Status" v={isDone ? 'Executed and reconciled' : 'Awaiting signatures (1 of 2)'} />
            <KV k="Paid from" v={meta.wallet} />
            <KV k="Wallet address" v={meta.walletAddr} mono />
            <KV k="Network · token" v={`${run.chain === 'Tron' ? 'TRON' : 'Ethereum'} · ${meta.token}`} />
            <KV k="Batch executed via" v={meta.contract} />
          </div>
          <div>
            <KV k="Total paid" v={`${fmtFull(isDone ? run.total : total)} USDT`} />
            <KV k="Recipients" v={`${run.recipients} (first 8 shown)`} />
            <KV k="Network fee" v={isDone ? meta.fee : 'estimate ' + meta.fee} />
            <KV k="Transaction hash" v={isDone ? hash : '— not executed yet'} mono />
            <KV k="Block" v={isDone ? meta.block.toLocaleString('en-US') : '—'} />
          </div>
        </div>

        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--col-text)', marginBottom: 8 }}>Payout lines</div>
        <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: 20 }}>
          <thead><tr>
            <th style={th}>#</th><th style={th}>Recipient</th><th style={th}>Address</th><th style={th}>Invoice / contract</th><th style={th}>Purpose</th><th style={th}>AML</th><th style={{ ...th, textAlign: 'right' }}>Amount</th>
          </tr></thead>
          <tbody>
            {lines.map((l, i) =>
              <tr key={l.id} style={l.risk === 'high' ? { opacity: 0.55 } : null}>
                <td style={td}>{isDone ? i + 1 : '—'}</td>
                <td style={td}>{l.name}</td>
                <td style={{ ...td, fontFamily: "'SF Mono','Fira Code',monospace", fontSize: 11 }}>{truncAddr(l.address, 8, 6)}</td>
                <td style={td}>{l.doc}</td>
                <td style={td}>{l.purpose}</td>
                <td style={td}>{l.risk === 'high' ? 'Flagged — excluded' : `Clear (${l.riskScore})`}</td>
                <td style={{ ...td, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{fmtFull(l.amount)}</td>
              </tr>)}
          </tbody>
        </table>

        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--col-text)', marginBottom: 4 }}>Approval and audit log</div>
        <div style={{ fontSize: 12, color: 'var(--col-text-3)', marginBottom: 8 }}>Append-only: each entry stores the hash of the previous one, so any edit breaks the chain.</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr><th style={th}>Time</th><th style={th}>Actor</th><th style={th}>Action</th><th style={th}>Entry hash</th></tr></thead>
          <tbody>
            {log.map((e, i) =>
              <tr key={i}>
                <td style={{ ...td, whiteSpace: 'nowrap' }}>{e.time}</td>
                <td style={td}>{e.actor}</td>
                <td style={td}>{e.action}</td>
                <td style={{ ...td, fontFamily: "'SF Mono','Fira Code',monospace", fontSize: 11 }}>{shortHash(e.hash, 8, 6)}</td>
              </tr>)}
          </tbody>
        </table>
        <div style={{ marginTop: 16, fontSize: 12, color: 'var(--col-text-3)', lineHeight: 1.5 }}>
          Astrail is non-custodial: funds never left the company wallet before execution, and every transfer was signed by the company's own signers. Amounts and hashes can be verified on {meta.explorer}.
        </div>
      </div>
    </div>);
};

// ── Recipients table with accounting + AML (used in run detail) ─
const RunLinesTable = ({ run, lines, onNavigate }) => {
  const isDone = run.status === 'confirmed';
  const hash = txHashFor(run);
  return (
    <table className="data-table">
      <thead>
        <tr>
          <th>Recipient</th>
          <th>Invoice / contract</th>
          <th>Purpose</th>
          <th>AML</th>
          <th className="right">Amount</th>
          <th className="center">{isDone ? 'On-chain' : 'Status'}</th>
        </tr>
      </thead>
      <tbody>
        {lines.map((r) =>
          <tr key={r.id} style={{ cursor: 'default', ...(r.risk === 'high' ? { background: 'var(--col-error-bg)' } : {}) }}>
            <td>
              <div className="flex-row gap-8">
                <Avatar name={r.name} size="sm" />
                <div>
                  <div className="flex-row gap-6">
                    <span className="cell-primary" style={{ whiteSpace: 'nowrap' }}>{r.name}</span>
                    {!isDone && r.isNew && <span className="inline-flag flag-new">New</span>}
                  </div>
                  <div className="cell-address" style={{ fontSize: 11 }}>{truncAddr(r.address, 8, 6)}</div>
                </div>
              </div>
            </td>
            <td style={{ fontSize: 13, color: 'var(--col-text-2)', whiteSpace: 'nowrap' }}>{r.doc}</td>
            <td style={{ fontSize: 13, color: 'var(--col-text-2)' }}>{r.purpose}</td>
            <td title={r.riskNote || 'Screened by AMLBot before signing'}>
              <RiskPill risk={r.risk} score={r.riskScore} />
              {r.riskNote && <div style={{ fontSize: 11, color: 'var(--col-error)', marginTop: 3, maxWidth: 180, lineHeight: 1.35 }}>{r.riskNote}</div>}
            </td>
            <td className="right cell-mono fw-5" style={r.risk === 'high' ? { textDecoration: 'line-through', color: 'var(--col-text-3)' } : null}>{fmtFull(r.amount)}</td>
            <td className="center">
              {isDone ?
                <span style={{ fontFamily: "'SF Mono','Fira Code',monospace", fontSize: 11, color: 'var(--col-accent)' }} title={`Transfer #${r.transferIndex + 1} inside batch tx ${hash}`}>
                  {shortHash(hash, 5, 3)} #{r.transferIndex + 1}
                </span> :
                r.risk === 'high' ? <span style={{ fontSize: 12, color: 'var(--col-error)', fontWeight: 600 }}>Excluded</span> : <StatusBadge status="pending" />}
            </td>
          </tr>)}
      </tbody>
    </table>);
};

// ── Executed-run card (replaces approval card for confirmed runs) ─
const ExecutedCard = ({ run, addToast, onReport }) => {
  const meta = runMeta(run);
  const hash = txHashFor(run);
  const times = SIGNER_TIMES[run.id] || ['', ''];
  const { MOCK } = window;
  return (
    <div className="card card-pad">
      <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--col-success)', marginBottom: 12 }}>Executed · reconciled with chain</div>
      {MOCK.approvalSigners.slice(0, 2).map((s, i) =>
        <div key={s.name} className="flex-row gap-8" style={{ marginBottom: 8 }}>
          <div className="sig-dot signed"><IcoCheck size={10} /></div>
          <Avatar name={s.name} size="sm" />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--col-text)' }}>{s.name}</div>
            <div style={{ fontSize: 11, color: 'var(--col-text-3)' }}>{s.role} · signed {times[i]}</div>
          </div>
        </div>)}
      <div style={{ marginTop: 10 }}>
        <KV w={84} k="Tx hash" v={shortHash(hash, 10, 8)} mono />
        <KV w={84} k="Network fee" v={meta.fee} />
        <KV w={84} k="Via" v={meta.contract} />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 14 }}>
        <button className="btn btn-primary btn-md" style={{ justifyContent: 'center' }} onClick={onReport}>Payout report for auditor</button>
        <button className="btn btn-secondary btn-md" style={{ justifyContent: 'center' }} onClick={() => addToast(`Opening transaction on ${meta.explorer}…`, 'success')}>
          <IcoExternal size={13} /> View on {meta.explorer}
        </button>
      </div>
    </div>);
};

// ── Idle funds (yield) module for Treasury ──────────────────────
const IdleFundsCard = ({ addToast }) => {
  const [enabled, setEnabled] = React.useState(true);
  const [modal, setModal] = React.useState(null); // 'supply' | 'withdraw'
  const [amount, setAmount] = React.useState('50000');
  const supplied = 250000, accrued = 2114.36;
  const exportYield = () => {
    const rows = [['date', 'type', 'protocol', 'network', 'asset', 'amount', 'position_after', 'tx_hash'],
      ['2026-10-01', 'supply', 'Aave v3', 'Ethereum', 'USDT', '200000.00', '200000.00', '0x' + fakeHex('y1')],
      ['2026-10-15', 'supply', 'Aave v3', 'Ethereum', 'USDT', '50000.00', '250413.18', '0x' + fakeHex('y2')],
      ['2026-10-31', 'interest accrued (month)', 'Aave v3', 'Ethereum', 'USDT', '1037.55', '251037.55', ''],
      ['2026-11-25', 'interest accrued (to date)', 'Aave v3', 'Ethereum', 'USDT', '1076.81', '252114.36', '']];
    downloadFile('astrail-idle-funds-report.csv', toCsv(rows));
    addToast('Yield report CSV downloaded', 'success');
  };
  return (
    <div className="card card-pad">
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
        <div style={{ flex: 1 }}>
          <div className="card-title" style={{ marginBottom: 2 }}>Idle funds</div>
          <div style={{ fontSize: 13, color: 'var(--col-text-3)' }}>Optional module, off by default. Funds go from your Safe to the protocol; the position token stays on your Safe.</div>
        </div>
        <span style={{ fontSize: 12, color: 'var(--col-text-3)' }}>{enabled ? 'On' : 'Off'}</span>
        <SToggle value={enabled} onChange={(v) => { setEnabled(v); addToast(v ? 'Idle funds module enabled by Owner' : 'Idle funds module disabled', 'success'); }} />
      </div>
      {enabled ?
        <>
          <div style={{ border: '1px solid var(--col-border-s)', borderRadius: 12, padding: '14px 16px', display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr auto', gap: 16, alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--col-text)' }}>Aave v3 · USDT</div>
              <div style={{ fontSize: 12, color: 'var(--col-text-3)' }}>Ethereum · from Operations Safe · aEthUSDT held by your Safe</div>
            </div>
            <div><div className="stat-label">Supplied</div><div style={{ fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{fmtUSD(supplied)}</div></div>
            <div><div className="stat-label">Earned to date</div><div style={{ fontWeight: 600, color: 'var(--col-success)', fontVariantNumeric: 'tabular-nums' }}>+{fmtFull(accrued)}</div></div>
            <div><div className="stat-label">Rate</div><div style={{ fontWeight: 600 }}>variable, set by Aave</div></div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn btn-secondary btn-sm" onClick={() => setModal('supply')}>Supply</button>
              <button className="btn btn-secondary btn-sm" onClick={() => setModal('withdraw')}>Withdraw</button>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', marginTop: 12, fontSize: 12, color: 'var(--col-text-3)' }}>
            <span>No lock-up: withdraw in one Safe transaction</span>
            <span>·</span>
            <span>Every move needs the same 2 of 3 signatures as payouts</span>
            <span>·</span>
            <span>Protocol risk stays with the company</span>
            <button className="btn btn-link" style={{ fontSize: 12, marginLeft: 'auto' }} onClick={exportYield}><IcoDownload size={12} /> Yield report for accounting</button>
          </div>
          <div style={{ marginTop: 12, padding: '10px 12px', borderRadius: 10, background: 'var(--col-surface-2)', fontSize: 12, color: 'var(--col-text-2)' }}>
            Also available on request: tokenized US T-bill funds (Ondo, Spiko). The fund issuer runs its own KYB; redemption is same day to T+2.
          </div>
        </> :
        <div style={{ fontSize: 13, color: 'var(--col-text-3)' }}>Module is off. Nothing leaves your wallets for yield until an Owner enables it.</div>}

      {modal &&
        <div className="modal-overlay" onClick={() => setModal(null)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 480 }}>
            <div className="modal-header">
              <div className="modal-title">{modal === 'supply' ? 'Supply to Aave v3' : 'Withdraw from Aave v3'}</div>
              <div style={{ fontSize: 13, color: 'var(--col-text-3)', marginTop: 2 }}>Creates a Safe transaction. Nothing moves until 2 of 3 signers approve in their wallets.</div>
            </div>
            <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 7 }}>Amount, USDT</label>
            <input className="form-input" value={amount} onChange={e => setAmount(e.target.value.replace(/[^0-9.]/g, ''))}
              style={{ height: 40, width: '100%', padding: '0 12px', border: '1.5px solid var(--col-border)', borderRadius: 9, fontFamily: 'inherit', fontSize: 14, background: 'var(--col-surface)', color: 'var(--col-text)', marginBottom: 14 }} />
            <div style={{ fontSize: 13, color: 'var(--col-text-2)', lineHeight: 1.6, marginBottom: 20 }}>
              {modal === 'supply' ?
                <>From <strong>Operations Safe</strong> → Aave v3 pool. You receive aEthUSDT on the same Safe. Rate is variable.</> :
                <>aEthUSDT → USDT back to <strong>Operations Safe</strong>. No lock-up, no exit fee from Astrail.</>}
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary btn-md" onClick={() => setModal(null)}>Cancel</button>
              <button className="btn btn-primary btn-md" onClick={() => { setModal(null); addToast('Safe transaction proposed — waiting for 2 of 3 signatures', 'success'); }}>Propose to signers</button>
            </div>
          </div>
        </div>}
    </div>);
};

// ── Settings: Compliance & Accounting ───────────────────────────
const ComplianceSettings = ({ addToast }) => {
  const [provider, setProvider] = React.useState('amlbot');
  const [screenOut, setScreenOut] = React.useState(true);
  const [screenIn, setScreenIn] = React.useState(true);
  const [block, setBlock] = React.useState('70');
  return (
    <div>
      <SectionHead title="Compliance" desc="AML screening runs before anyone signs. Astrail never holds funds, so screening is advisory: the decision stays with your signers." />
      <FormRow label="AML provider" hint="Default is AMLBot. Bring your own contract and API key with another provider.">
        <SSelect value={provider} onChange={(v) => { setProvider(v); addToast('AML provider updated', 'success'); }} options={[
          { value: 'amlbot', label: 'AMLBot (default)' },
          { value: 'chainalysis', label: 'Chainalysis KYT (your API key)' },
          { value: 'elliptic', label: 'Elliptic (your API key)' },
          { value: 'crystal', label: 'Crystal (your API key)' }]} />
      </FormRow>
      <FormRow label="Screen payout recipients" hint="Every address in a run is checked against sanctions lists and scored before signing.">
        <SToggle value={screenOut} onChange={setScreenOut} />
      </FormRow>
      <FormRow label="Screen incoming funds" hint="Incoming transfers to connected wallets get a risk score and a flag in Treasury.">
        <SToggle value={screenIn} onChange={setScreenIn} />
      </FormRow>
      <FormRow label="Exclude from run above score" hint="Lines above this score are excluded automatically; an Owner can override with a note.">
        <SSelect value={block} onChange={setBlock} options={[{ value: '50', label: '50' }, { value: '70', label: '70 (recommended)' }, { value: '85', label: '85' }]} />
      </FormRow>
      <FormRow label="Sanctions lists" hint="Always on." noBorder>
        <div style={{ fontSize: 14, color: 'var(--col-text-2)', paddingTop: 9 }}>OFAC SDN, EU, UN, UK HMT</div>
      </FormRow>
    </div>);
};

const AccountingSettings = ({ addToast }) => {
  const [fmtSel, setFmtSel] = React.useState('xero');
  const [reqDoc, setReqDoc] = React.useState(true);
  const [reqPurpose, setReqPurpose] = React.useState(true);
  return (
    <div>
      <SectionHead title="Accounting" desc="Every payout line carries an invoice or contract number and a purpose. Exports are ready to import as bank statement lines." />
      <FormRow label="Export format" hint="Xero: wallet is set up as a bank account, payouts import as statement lines.">
        <SSelect value={fmtSel} onChange={(v) => { setFmtSel(v); addToast('Export format saved', 'success'); }} options={[
          { value: 'xero', label: 'Xero — bank statement CSV' },
          { value: 'qbo', label: 'QuickBooks Online — bank CSV' },
          { value: 'generic', label: 'Generic CSV (all fields)' }]} />
      </FormRow>
      <FormRow label="Require invoice / contract no.">
        <SToggle value={reqDoc} onChange={setReqDoc} />
      </FormRow>
      <FormRow label="Require payment purpose">
        <SToggle value={reqPurpose} onChange={setReqPurpose} />
      </FormRow>
      <FormRow label="Reporting currency" hint="Rates are stored for the execution date.">
        <SSelect value="usd" onChange={() => {}} options={[{ value: 'usd', label: 'USD' }, { value: 'sgd', label: 'SGD' }, { value: 'eur', label: 'EUR' }]} />
      </FormRow>
      <FormRow label="Audit access" hint="Read-only role for an external auditor: history, reports, audit log." noBorder>
        <button className="btn btn-secondary btn-sm" onClick={() => addToast('Invite sent to auditor (Viewer role)', 'success')}>Invite auditor</button>
      </FormRow>
    </div>);
};

// ── New run: CSV upload or address book ─────────────────────────
const NewRunScreen = ({ onNavigate, addToast }) => {
  const { MOCK } = window;
  const [name, setName] = React.useState('June 2026 Payroll');
  const [chain, setChain] = React.useState('Tron');
  const [source, setSource] = React.useState(null); // 'csv' | 'book'
  const [loading, setLoading] = React.useState(false);
  const run = { ...MOCK.payrollRuns[0], id: 'PR-025', name, date: '2026-06-01', chain, status: 'pending' };
  const lines = source ? buildRunLines(run) : [];
  const total = lines.filter(l => l.risk !== 'high').reduce((s, l) => s + l.amount, 0);
  const load = (src) => { setLoading(true); setTimeout(() => { setLoading(false); setSource(src); addToast(src === 'csv' ? 'payroll-june.csv parsed: 8 lines' : '8 recipients added from address book', 'success'); }, 900); };
  return (
    <>
      <div className="content-header">
        <div className="content-header-left">
          <div className="breadcrumb">
            <span className="breadcrumb-link" onClick={() => onNavigate('payroll')}>Payroll</span>
            <IcoChevronRight size={12} color="var(--col-text-3)" />
            <span className="breadcrumb-current">New run</span>
          </div>
        </div>
      </div>
      <div className="content-body">
        <div className="card card-pad" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 16 }}>
          <div>
            <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 7 }}>Run name</label>
            <input className="form-input" value={name} onChange={e => setName(e.target.value)} style={{ height: 40, width: '100%', padding: '0 12px', border: '1.5px solid var(--col-border)', borderRadius: 9, fontFamily: 'inherit', fontSize: 14, background: 'var(--col-surface)', color: 'var(--col-text)' }} />
          </div>
          <div>
            <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 7 }}>Pay from</label>
            <select value={chain} onChange={e => setChain(e.target.value)} style={{ height: 40, width: '100%', padding: '0 12px', border: '1.5px solid var(--col-border)', borderRadius: 9, fontFamily: 'inherit', fontSize: 14, background: 'var(--col-surface)', color: 'var(--col-text)' }}>
              <option value="Tron">Tron Treasury · USDT TRC-20</option>
              <option value="EVM">Operations Safe · USDT ERC-20</option>
            </select>
          </div>
          <div>
            <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 7 }}>Approval</label>
            <div style={{ height: 40, display: 'flex', alignItems: 'center', fontSize: 14, color: 'var(--col-text-2)' }}>2 of 3 signers</div>
          </div>
        </div>

        {!source &&
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div className="card card-pad" style={{ cursor: 'pointer', borderStyle: 'dashed', textAlign: 'center', padding: '36px 20px' }} onClick={() => !loading && load('csv')}>
              <IcoUpload size={26} color="var(--col-accent)" />
              <div style={{ fontSize: 15, fontWeight: 600, marginTop: 10 }}>Upload CSV</div>
              <div style={{ fontSize: 13, color: 'var(--col-text-3)', marginTop: 4 }}>name, address, amount, invoice/contract, purpose</div>
            </div>
            <div className="card card-pad" style={{ cursor: 'pointer', textAlign: 'center', padding: '36px 20px' }} onClick={() => !loading && load('book')}>
              <IcoAddressBook size={26} color="var(--col-accent)" />
              <div style={{ fontSize: 15, fontWeight: 600, marginTop: 10 }}>From address book</div>
              <div style={{ fontSize: 13, color: 'var(--col-text-3)', marginTop: 4 }}>Saved recipients with verified addresses</div>
            </div>
          </div>}
        {loading && <div className="card card-pad" style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, color: 'var(--col-text-2)' }}><LoaderArc size="sm" /> Validating addresses, balance and AML…</div>}

        {source && !loading &&
          <>
            <div className="card card-pad">
              <div className="card-title">Pre-flight checks</div>
              <div className="check-list">
                {[
                  { ok: true, label: 'All addresses valid', detail: '8 of 8' },
                  { ok: true, label: 'Balance sufficient', detail: chain === 'Tron' ? '$286,400 on Tron Treasury' : '$882,000 on Operations Safe' },
                  { ok: false, err: true, label: 'AML screening (AMLBot)', detail: '1 recipient high risk — excluded until an Owner reviews' },
                  { ok: false, warn: true, label: 'New recipients', detail: '2 addresses paid for the first time' },
                  { ok: true, label: 'Invoice / contract and purpose', detail: 'filled on every line' },
                  { ok: true, label: 'Network fee', detail: chain === 'Tron' ? '≈ $38, energy rented for the batch' : '≈ $22, one Safe transaction' }].map(c =>
                  <div key={c.label} className="check-item">
                    <div className={`check-icon ${c.ok ? 'check-ok' : c.warn ? 'check-warn' : 'check-err'}`}>
                      {c.ok ? <IcoCheck size={10} /> : c.warn ? <IcoAlert size={10} /> : <IcoX size={10} />}
                    </div>
                    <div style={{ flex: 1 }}><span style={{ fontWeight: 500 }}>{c.label}</span><span style={{ color: 'var(--col-text-3)', marginLeft: 4 }}>— {c.detail}</span></div>
                  </div>)}
              </div>
            </div>
            <div className="card" style={{ overflow: 'hidden' }}>
              <RunLinesTable run={run} lines={lines} />
              <div style={{ padding: '12px 16px', borderTop: '1px solid var(--col-border-s)', display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 13, color: 'var(--col-text-2)' }}>7 lines · <strong style={{ color: 'var(--col-text)' }}>{fmtFull(total)}</strong> USDT · 1 excluded</span>
                <button className="btn btn-secondary btn-sm ml-auto" onClick={() => setSource(null)}>Start over</button>
                <button className="btn btn-primary btn-sm" onClick={() => { addToast(`${name} sent to signers — Alice Johnson, Boris Kovalev`, 'success'); setTimeout(() => onNavigate('payroll-detail', MOCK.payrollRuns[0]), 500); }}>Submit for approval</button>
              </div>
            </div>
          </>}
      </div>
    </>);
};

// Print: only the report modal
(function injectPrintCss() {
  if (document.getElementById('astrail-print')) return;
  const s = document.createElement('style');
  s.id = 'astrail-print';
  s.textContent = `@media print {
    body * { visibility: hidden !important; }
    .astrail-print-area, .astrail-print-area * { visibility: visible !important; }
    .astrail-print-area { position: absolute !important; left: 0; top: 0; width: 100% !important; max-width: none !important; max-height: none !important; overflow: visible !important; box-shadow: none !important; }
    .no-print { display: none !important; }
  }`;
  document.head.appendChild(s);
})();

Object.assign(window, {
  buildRunLines, buildAuditLog, runMeta, txHashFor, exportXero, exportLinesCsv, exportRunsCsv, downloadFile, toCsv,
  PayoutReportModal, RunLinesTable, ExecutedCard, IdleFundsCard,
  ComplianceSettings, AccountingSettings, NewRunScreen,
});
