// User-facing screens: Sidebar, Dashboard, BotsList, BotDetail, History, Deposit, KYC.

const BOT_COLORS = ['#1f8a5b', '#4f46e5', '#dc2626', '#0891b2', '#f97316', '#a855f7', '#0ea5e9', '#84cc16'];
const colorFor = (id) => BOT_COLORS[id % BOT_COLORS.length];
const emojiFor = (cat) => ({ conservative: '〰', moderate: '⬢', aggressive: '⚡' })[cat] || '◆';

function Sidebar({ route, setRoute, isAdmin, adminView, setAdminView, user, signOut }) {
  const userNav = [
    { id: 'dashboard',  label: 'Dashboard',    icon: IconDash },
    { id: 'bots',       label: 'Bots',         icon: IconBot },
    { id: 'history',    label: 'Transactions', icon: IconClock },
    { id: 'deposit',    label: 'Deposit',      icon: IconPlus },
    { id: 'kyc',        label: 'Verification', icon: IconID },
  ];
  const adminNav = [
    { id: 'admin',      label: 'God View',     icon: IconDash },
    { id: 'stats',      label: 'Stats',        icon: IconChart },
    { id: 'funding',    label: 'Funding',      icon: IconChart },
    { id: 'backtest',   label: 'Backtest',     icon: IconChart },
    { id: 'approvals',  label: 'Approvals',    icon: IconQueue },
    { id: 'users',      label: 'Users',        icon: IconUser },
    { id: 'killswitch', label: 'Bot Control',  icon: IconPower },
    { id: 'exchange',   label: 'Exchange',     icon: IconExchange },
    { id: 'settings',   label: 'Settings',     icon: IconSettings },
  ];
  const filteredUserNav = (user && user.role !== 'admin' && user.approval_status !== 'approved')
    ? userNav.filter(it => it.id === 'kyc')
    : userNav;
  const nav = adminView ? adminNav : filteredUserNav;
  const initials = (user?.full_name || user?.username || 'A').split(' ').map(s => s[0]).join('').slice(0,2).toUpperCase();
  return (
    <>
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark">A</div>
        <div>
          <div className="brand-name">Aeizch</div>
          <div className="brand-sub">{adminView ? 'Admin console' : 'Pooled trading'}</div>
        </div>
      </div>
      <div className="nav-label">{adminView ? 'Operations' : 'Investing'}</div>
      {nav.map((it) => {
        const I = it.icon;
        const active = route === it.id || (it.id === 'bots' && route.startsWith('bot:')) || (it.id === 'admin' && route.startsWith('admin-bot:'));
        return (
          <button key={it.id} className={'nav-item' + (active ? ' active' : '')} onClick={() => setRoute(it.id)}>
            <I className="nav-icon"/>
            <span>{it.label}</span>
            {it.badge && <span className="nav-badge">{it.badge}</span>}
          </button>
        );
      })}
      {isAdmin && (
        <>
          <div className="nav-label">Mode</div>
          <button className="nav-item mobile-hide" onClick={() => setAdminView(!adminView)}>
            <IconShield className="nav-icon"/>
            <span>Switch to {adminView ? 'User' : 'Admin'}</span>
          </button>
        </>
      )}
      {!adminView && (
        <div className="mobile-hide" style={{ padding: '12px 12px 4px', borderTop: '1px solid var(--line)', marginTop: 8 }}>
          <div className="tiny muted">Available cash</div>
          <div style={{ marginTop: 2 }}>
            <MorphNumber value={user?.cash_balance ?? 0} decimals={2} prefix="$" size={18} weight={700} color="var(--ink)"/>
          </div>
        </div>
      )}
      <div className="sidebar-foot">
        <div className="avatar">{initials}</div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {user?.full_name || user?.username || 'User'}
          </div>
          <div style={{ fontSize: 11, color: 'var(--ink-4)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {user?.email}
          </div>
        </div>
        <button className="btn ghost sm mobile-hide" onClick={signOut} title="Sign out" style={{ padding: '6px 10px' }}>
          <IconX size={14}/>
        </button>
      </div>
    </aside>
    {/* Mobile-only floating logout — sidebar-foot is hidden on mobile,
        and the bottom-nav has no room. Rendered as a SIBLING of <aside>
        (not a child) because the sidebar's backdrop-filter would otherwise
        create a containing block that traps position:fixed children. */}
    <button className="mobile-logout" onClick={signOut} title="Sign out" aria-label="Sign out">
      <IconX size={16}/>
    </button>
    </>
  );
}

/* ---------- Dashboard ---------- */
function Dashboard({ go }) {
  const [dash] = useApi('/api/dashboard/user');
  const [bots] = useApi('/api/bots');
  const holdings = (dash?.holdings || []).map(h => {
    const bot = (bots || []).find(b => b.id === h.bot_id);
    const avgPrice = h.units ? h.cost_basis / h.units : 0;
    const currentPrice = h.units ? h.current_value / h.units : 0;
    return { ...h, bot, avgPrice, currentPrice };
  });
  return (
    <>
      <div className="topbar">
        <div>
          <div className="crumb">Portfolio</div>
          <h1 className="h1">Welcome back, {dash ? (USD(dash.total_current_value), '') : ''}</h1>
        </div>
        <div className="row gap-8">
          <button className="btn ghost" onClick={() => go('deposit')}><IconPlus size={16}/> Deposit</button>
          <button className="btn primary" onClick={() => go('bots')}><IconBot size={16}/> Invest</button>
        </div>
      </div>
      <div className="content">
        <div className="grid grid-4">
          <KPI label="Total balance" value={USD((dash?.total_current_value || 0) + (dash?.cash_balance || 0))} sub="Invested + available cash"/>
          <KPI label="Available cash" value={USD(dash?.cash_balance)} sub="Ready to invest or withdraw"/>
          <KPI label="Invested" value={USD(dash?.total_current_value)} delta={dash ? fmtPct(dash.total_unrealized_pnl_percentage) + ' P&L' : null} pos={dash?.total_unrealized_pnl >= 0} neg={dash?.total_unrealized_pnl < 0}/>
          <KPI label="Unrealized PnL" value={USD(dash?.total_unrealized_pnl, {sign: true})} delta={dash ? fmtPct(dash.total_unrealized_pnl_percentage) : null} pos={dash?.total_unrealized_pnl >= 0} neg={dash?.total_unrealized_pnl < 0}/>
        </div>

        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="row" style={{ justifyContent: 'space-between', padding: '20px 22px 8px' }}>
            <div>
              <h2 className="h2">Your holdings</h2>
              <div className="tiny muted">Click any row to view the bot</div>
            </div>
            <button className="btn ghost sm" onClick={() => go('bots')}>Explore bots <IconArrowRt size={14}/></button>
          </div>
          {holdings.length === 0 ? (
            <div style={{ padding: '40px 22px', textAlign: 'center', color: 'var(--ink-4)' }}>
              No holdings yet — start by buying units in any bot.
            </div>
          ) : (
            <table className="tbl">
              <thead>
                <tr><th>Bot</th><th>Units</th><th>Avg price</th><th>Current</th><th>Value</th><th>P&L</th><th></th></tr>
              </thead>
              <tbody>
                {holdings.map(h => (
                  <tr key={h.bot_id} style={{ cursor: 'pointer' }} onClick={() => go('bot:' + h.bot_id)}>
                    <td>
                      <div className="row gap-12">
                        <div className="bot-emblem" style={{ width: 32, height: 32, borderRadius: 9, background: colorFor(h.bot_id), fontSize: 13 }}>{emojiFor(h.risk_category)}</div>
                        <div>
                          <div style={{ fontWeight: 600 }}>{h.bot_name}</div>
                          <div className="tiny muted" style={{ textTransform: 'capitalize' }}>{h.risk_category}</div>
                        </div>
                      </div>
                    </td>
                    <td className="num">{fmtNum(h.units, 4)}</td>
                    <td className="num">{fmtNum(h.avgPrice, 4)}</td>
                    <td className="num">{fmtNum(h.currentPrice, 4)}</td>
                    <td className="num" style={{ fontWeight: 600 }}>{USD(h.current_value)}</td>
                    <td>
                      <span className="num" style={{ color: h.unrealized_pnl >= 0 ? 'var(--pos)' : 'var(--neg)', fontWeight: 600 }}>
                        {USD(h.unrealized_pnl, { sign: true })} <span style={{ opacity: 0.7, fontWeight: 500 }}>({fmtPct(h.unrealized_pnl_percentage)})</span>
                      </span>
                    </td>
                    <td><IconArrowRt size={16} style={{ color: 'var(--ink-4)' }}/></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </>
  );
}

/* ---------- Bots list ---------- */
function BotsList({ go }) {
  const [bots] = useApi('/api/bots');
  const [filter, setFilter] = React.useState('All');
  const filtered = (bots || []).filter(b => filter === 'All' || b.risk_category === filter.toLowerCase());
  return (
    <>
      <div className="topbar">
        <div>
          <div className="crumb">Explore</div>
          <h1 className="h1">Trading bots</h1>
        </div>
        <div className="row gap-6">
          {['All','Conservative','Moderate','Aggressive'].map(t => (
            <button key={t} className={'btn ' + (filter === t ? 'primary' : 'ghost') + ' sm'} onClick={() => setFilter(t)}>{t}</button>
          ))}
        </div>
      </div>
      <div className="content">
        <div className="grid grid-3">
          {filtered.map(b => <BotCard key={b.id} bot={b} onClick={() => go('bot:' + b.id)}/>)}
          {filtered.length === 0 && bots && <div className="muted">No bots match this filter.</div>}
        </div>
      </div>
    </>
  );
}

function BotCard({ bot, onClick }) {
  const color = colorFor(bot.id);
  return (
    <div className="bot-card" onClick={onClick}>
      <div className="row" style={{ justifyContent: 'space-between' }}>
        <div className="row gap-12">
          <div className="bot-emblem" style={{ background: color }}>{emojiFor(bot.risk_category)}</div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 16 }}>{bot.name}</div>
            <span className="pill" style={{ marginTop: 4, background: color + '22', color, textTransform: 'capitalize' }}><span className="dot"/>{bot.risk_category}</span>
          </div>
        </div>
        <IconArrowRt size={18} style={{ color: 'var(--ink-4)' }}/>
      </div>
      <p className="muted" style={{ margin: 0, fontSize: 13, lineHeight: 1.5 }}>
        {bot.description || 'AI-driven trading strategy.'}
      </p>
      <div className="row" style={{ justifyContent: 'space-between', borderTop: '1px solid var(--line-2)', paddingTop: 14 }}>
        <div>
          <div className="tiny muted">Unit price</div>
          <div className="num" style={{ fontWeight: 700, fontSize: 15 }}>${fmtNum(bot.unit_price, 4)}</div>
        </div>
        <div>
          <div className="tiny muted">Risk</div>
          <div style={{ fontWeight: 700, fontSize: 13, textTransform: 'capitalize' }}>{bot.risk_category}</div>
        </div>
        <div>
          <div className="tiny muted">Status</div>
          <div style={{ fontWeight: 700, fontSize: 13, color: bot.is_active && !bot.is_kill_switched ? 'var(--pos)' : 'var(--ink-4)' }}>
            {bot.is_kill_switched ? 'KILLED' : bot.is_active ? 'Live' : 'Off'}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Bot detail (user view) ---------- */
function BotDetail({ botId, go, onInvest, onWithdraw }) {
  const [bot] = useApi('/api/bots/' + botId);
  const [dash] = useApi('/api/dashboard/user');
  const [bucket, setBucket] = React.useState('hour');
  const [history] = useApi(bot ? `/api/admin/bots/${botId}/unit-price-history?bucket=${bucket}` : null, [bucket, bot?.id]);
  if (!bot) return <div style={{ padding: 32 }} className="muted">Loading…</div>;
  const color = colorFor(bot.id);
  const holding = (dash?.holdings || []).find(h => h.bot_id === bot.id);
  const prices = (history || []).map(p => p.unit_price);
  const change = prices.length > 1 ? prices[prices.length - 1] - prices[0] : 0;
  const changePct = prices[0] ? (change / prices[0]) * 100 : 0;

  return (
    <>
      <div className="topbar">
        <div>
          <button className="btn ghost sm" onClick={() => go('bots')} style={{ marginBottom: 8 }}>← All bots</button>
          <div className="row gap-12">
            <div className="bot-emblem" style={{ background: color, width: 52, height: 52, fontSize: 20 }}>{emojiFor(bot.risk_category)}</div>
            <div>
              <div className="row gap-8" style={{ marginBottom: 4 }}>
                <span className="pill" style={{ background: color + '22', color, textTransform: 'capitalize' }}><span className="dot"/>{bot.risk_category}</span>
                <span className={'pill ' + (bot.is_active && !bot.is_kill_switched ? 'pos' : 'warn')}><span className="dot"/>{bot.is_kill_switched ? 'Killed' : bot.is_active ? 'Live' : 'Off'}</span>
              </div>
              <h1 className="h1" style={{ marginTop: 0 }}>{bot.name}</h1>
            </div>
          </div>
        </div>
        <div className="row gap-8">
          {holding && <button className="btn ghost" onClick={() => onWithdraw(bot)}><IconMinus size={16}/> Sell units</button>}
          <button className="btn primary" onClick={() => onInvest(bot)}><IconPlus size={16}/> Buy units</button>
        </div>
      </div>
      <div className="content">
        <div className="grid" style={{ gridTemplateColumns: '2fr 1fr', gap: 22 }}>
          <div className="card">
            <div style={{ marginBottom: 20 }}>
              <div className="tiny muted" style={{ marginBottom: 8, letterSpacing: '0.16em', textTransform: 'uppercase', fontSize: 10 }}>Unit price · live</div>
              <div className="row gap-12" style={{ alignItems: 'baseline', flexWrap: 'wrap' }}>
                <MorphNumber value={bot.unit_price} decimals={4} prefix="$" size={44} weight={600} color="var(--ink)"/>
                {prices.length > 1 && (
                  <span className={'pill ' + (change >= 0 ? 'pos' : 'neg')} style={{ alignSelf: 'center' }}>
                    {change >= 0 ? <IconArrowUp size={11}/> : <IconArrowDn size={11}/>} {fmtPct(changePct)}
                  </span>
                )}
              </div>
            </div>
            {prices.length > 0
              ? <LineChart data={prices} color={color} height={260}/>
              : <div className="muted" style={{ padding: '80px 0', textAlign: 'center' }}>No price history yet at this resolution.</div>
            }
            {/* Period selector — minimal text, justified, active is underlined */}
            <div style={{
              display: 'flex', justifyContent: 'space-between', marginTop: 14,
              fontFamily: 'var(--font-num)', fontSize: 11, letterSpacing: '0.14em',
            }}>
              {[['hour','1H'],['day','1D'],['week','1W'],['month','1M']].map(([b,lab]) => (
                <button key={b} onClick={() => setBucket(b)} style={{
                  background: 'transparent', border: 'none', padding: '6px 18px', cursor: 'pointer',
                  color: bucket === b ? 'var(--ink)' : 'var(--ink-4)',
                  fontFamily: 'inherit', fontSize: 'inherit', letterSpacing: 'inherit',
                  borderBottom: '1.5px solid ' + (bucket === b ? 'var(--ink)' : 'transparent'),
                  transition: 'color 180ms ease, border-color 180ms ease',
                }}>{lab}</button>
              ))}
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div className="card">
              <h3 className="h3" style={{ marginBottom: 12 }}>Strategy</h3>
              <p className="muted" style={{ margin: 0, fontSize: 13.5, lineHeight: 1.6 }}>
                {bot.description || bot.strategy || 'Multi-factor confluence scanner — trend alignment + momentum + pullback + breakout + S/R + vol regime, scored across a universe of USDT-perp symbols.'}
              </p>
            </div>
            {holding ? (
              <div className="card lift">
                <div className="tiny muted">Your position</div>
                <div style={{ marginTop: 4 }}>
                  <MorphNumber value={holding.current_value} decimals={2} prefix="$" size={24} weight={700} color="var(--ink)"/>
                </div>
                <div className={'kpi-delta ' + (holding.unrealized_pnl >= 0 ? 'pos' : 'neg')} style={{ marginTop: 4 }}>
                  {holding.unrealized_pnl >= 0 ? <IconArrowUp size={12}/> : <IconArrowDn size={12}/>}
                  {USD(holding.unrealized_pnl, { sign: true })} ({fmtPct(holding.unrealized_pnl_percentage)})
                </div>
                <div style={{ borderTop: '1px solid var(--line-2)', marginTop: 14, paddingTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 13 }}>
                  <div><div className="tiny muted">Units</div><div className="num" style={{ fontWeight: 600 }}>{fmtNum(holding.units, 4)}</div></div>
                  <div><div className="tiny muted">Cost basis</div><div className="num" style={{ fontWeight: 600 }}>{USD(holding.cost_basis)}</div></div>
                </div>
              </div>
            ) : (
              <div className="card flat">
                <h3 className="h3">No position yet</h3>
                <p className="muted" style={{ margin: '6px 0 12px', fontSize: 13 }}>Buy units at the current NAV.</p>
                <button className="btn primary block" onClick={() => onInvest(bot)}>Buy units</button>
              </div>
            )}
          </div>
        </div>

        {bot.performance && (
          <div className="grid grid-3">
            <KPI label="Total PnL" value={fmtPct(bot.performance.total_pnl_percentage)} pos={bot.performance.total_pnl_percentage >= 0} neg={bot.performance.total_pnl_percentage < 0}/>
            <KPI label="Win rate" value={(bot.performance.win_rate || 0).toFixed(1) + '%'}/>
            <KPI label="Trades" value={String(bot.performance.total_closed_trades || 0)} sub={(bot.performance.total_trades || 0) + ' total'}/>
          </div>
        )}
      </div>
    </>
  );
}

/* ---------- Transactions ---------- */
function History() {
  const [txs] = useApi('/api/transactions');
  return (
    <>
      <div className="topbar">
        <div>
          <div className="crumb">Activity</div>
          <h1 className="h1">Transactions</h1>
        </div>
      </div>
      <div className="content">
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          {txs && txs.length === 0 ? (
            <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-4)' }}>No transactions yet.</div>
          ) : (
            <table className="tbl">
              <thead><tr><th>Type</th><th>Detail</th><th>Date</th><th style={{ textAlign: 'right' }}>Amount</th><th>Status</th></tr></thead>
              <tbody>
                {(txs || []).map(t => {
                  const icon = t.transaction_type === 'buy' ? <IconPlus size={14}/>
                    : t.transaction_type === 'sell' ? <IconMinus size={14}/>
                    : t.transaction_type === 'deposit' ? <IconWallet size={14}/>
                    : <IconArrowRt size={14}/>;
                  return (
                    <tr key={t.id}>
                      <td>
                        <div className="row gap-10">
                          <div style={{ width: 32, height: 32, borderRadius: 9, background: 'var(--bg-soft)', display: 'grid', placeItems: 'center', color: 'var(--ink-2)' }}>{icon}</div>
                          <span style={{ fontWeight: 600, textTransform: 'capitalize' }}>{t.transaction_type}</span>
                        </div>
                      </td>
                      <td className="muted" style={{ fontSize: 13 }}>
                        {t.units ? (fmtNum(t.units, 4) + ' units @ ' + fmtNum(t.unit_price, 4)) : (t.description || '—')}
                      </td>
                      <td className="muted tiny">{fmtDate(t.created_at)}</td>
                      <td className="num" style={{ textAlign: 'right', fontWeight: 600 }}>{USD(t.amount)}</td>
                      <td>
                        <span className={'pill ' + (t.status === 'completed' || t.status === 'approved' ? 'pos' : t.status === 'pending' ? 'warn' : 'neg')}>
                          <span className="dot"/>{t.status}
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </>
  );
}

/* ---------- Deposit ---------- */
function Deposit() {
  const [amount, setAmount] = React.useState(100);
  const [step, setStep] = React.useState(0);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [copied, setCopied] = React.useState(false);
  const presets = [50, 100, 500, 1000];
  // Pulls the platform's USDT deposit address + chain. Admin sets these in
  // Settings under DEPOSIT_ADDRESS / DEPOSIT_NETWORK. Without them the user
  // sees an explicit "not yet configured" state instead of a fake address.
  const [info] = useApi('/api/transactions/deposit/info');
  const [reference] = React.useState(() =>
    'AZ-' + Math.floor(Math.random() * 99999).toString().padStart(5, '0')
  );
  const submit = async () => {
    setSubmitting(true); setError(null);
    try {
      await api.post('/api/transactions/deposit', { amount, description: `Deposit · ref ${reference}` });
      setStep(2);
    } catch (e) { setError(e.detail || e.message); }
    setSubmitting(false);
  };
  const copyAddress = async () => {
    if (!info?.address) return;
    try {
      await navigator.clipboard.writeText(info.address);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {}
  };
  return (
    <>
      <div className="topbar">
        <div>
          <div className="crumb">Deposit funds</div>
          <h1 className="h1">Top up your account</h1>
        </div>
        <span className="pill warn"><span className="dot"/>Manual verification</span>
      </div>
      <div className="content">
        <div className="steps" style={{ maxWidth: 600 }}>
          <div className={'step ' + (step >= 0 ? 'done' : '')}/>
          <div className={'step ' + (step >= 1 ? 'done' : '')}/>
          <div className={'step ' + (step >= 2 ? 'done' : '')}/>
        </div>
        <div className="grid" style={{ gridTemplateColumns: '1.2fr 1fr', gap: 22 }}>
          <div className="card">
            {step === 0 && (
              <>
                <h2 className="h2" style={{ marginBottom: 16 }}>How much would you like to deposit?</h2>
                <div className="field">
                  <input className="input" style={{ fontSize: 24, fontWeight: 700, fontFamily: 'var(--font-num)', padding: '20px 18px' }}
                    value={'$ ' + amount.toLocaleString('en-US')}
                    onChange={(e) => setAmount(Number(e.target.value.replace(/[^0-9.]/g, '')) || 0)}/>
                </div>
                <div className="row gap-8" style={{ marginTop: 10, flexWrap: 'wrap' }}>
                  {presets.map(p => (
                    <button key={p} className={'btn ' + (amount === p ? 'soft' : 'ghost') + ' sm'} onClick={() => setAmount(p)}>{USD(p, {decimals:0})}</button>
                  ))}
                </div>
                <button className="btn primary block lg" style={{ marginTop: 20 }} onClick={() => setStep(1)} disabled={amount < 10}>Continue</button>
              </>
            )}
            {step === 1 && (
              <>
                <h2 className="h2" style={{ marginBottom: 6 }}>Send USDT to this address</h2>
                <p className="muted" style={{ marginTop: 0, fontSize: 13.5 }}>Send exactly the amount shown. Admin will check the Bybit wallet and approve once your transfer settles.</p>
                <div className="card flat" style={{ padding: 18, marginTop: 12 }}>
                  <div className="row" style={{ justifyContent: 'space-between' }}>
                    <span className="muted tiny">Network</span>
                    <strong>USDT · {info?.network || '—'}</strong>
                  </div>
                  <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
                    <div className="muted tiny" style={{ marginBottom: 6 }}>Deposit address</div>
                    {info?.address ? (
                      <div className="row gap-8" style={{ alignItems: 'center' }}>
                        <code className="num" style={{ fontSize: 12, wordBreak: 'break-all', flex: 1, lineHeight: 1.4 }}>{info.address}</code>
                        <button className="btn ghost sm" onClick={copyAddress}>{copied ? 'Copied' : 'Copy'}</button>
                      </div>
                    ) : (
                      <div className="muted tiny">Not configured. Contact admin to set <code>DEPOSIT_ADDRESS</code> in Settings.</div>
                    )}
                  </div>
                  <div className="row" style={{ justifyContent: 'space-between', marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
                    <span className="muted tiny">Amount</span><strong className="num" style={{ fontSize: 18 }}>{USD(amount)}</strong>
                  </div>
                  <div className="row" style={{ justifyContent: 'space-between', marginTop: 8 }}><span className="muted tiny">Reference</span><strong className="num">{reference}</strong></div>
                </div>
                {error && <div style={{ fontSize: 13, color: 'var(--neg)', background: 'var(--neg-soft)', padding: 10, borderRadius: 8, marginTop: 12 }}>{error}</div>}
                <button className="btn primary block lg" style={{ marginTop: 20 }} onClick={submit} disabled={submitting || !info?.address}>{submitting ? 'Submitting…' : "I've sent the transfer"}</button>
              </>
            )}
            {step === 2 && (
              <div style={{ textAlign: 'center', padding: '24px 0' }}>
                <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'var(--pos-soft)', color: 'var(--pos)', display: 'grid', placeItems: 'center', margin: '0 auto 18px' }}>
                  <IconCheck size={34}/>
                </div>
                <h2 className="h2">Submitted for review</h2>
                <p className="muted" style={{ fontSize: 14, marginTop: 8 }}>We'll confirm your deposit of <strong className="num">{USD(amount)}</strong> after the on-chain transfer settles.</p>
                <button className="btn primary lg" style={{ marginTop: 14 }} onClick={() => { setStep(0); setAmount(100); }}>Done</button>
              </div>
            )}
          </div>
          <div className="card flat">
            <h3 className="h3">Before you transfer</h3>
            <ul style={{ margin: '12px 0 0', paddingLeft: 18, fontSize: 13.5, lineHeight: 1.7, color: 'var(--ink-2)' }}>
              <li>Use USDT on the <strong>TRC20</strong> network (fastest, lowest fee).</li>
              <li>Include the <strong>reference code</strong> in the transfer note.</li>
              <li>Funds are credited at the next NAV calculation after confirmation.</li>
            </ul>
          </div>
        </div>
      </div>
    </>
  );
}

/* ---------- KYC ---------- */
function KYC({ onStatusChange }) {
  const [statusData, { reload }] = useApi('/api/auth/kyc/status');
  const [step, setStep] = React.useState(0);
  const [name, setName] = React.useState('');
  const [ktp, setKtp] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  const submit = async () => {
    setSubmitting(true); setError(null);
    try {
      console.log("Submitting KYC with:", { name, ktp });
      console.log("reload function type:", typeof reload);
      await api.post('/api/auth/kyc', { full_name: name, ktp_number: ktp });
      console.log("KYC post success. Calling reload...");
      if (typeof reload === 'function') {
        reload();
      } else {
        console.warn("reload is not a function!");
      }
      console.log("Calling onStatusChange...");
      try {
        if (typeof onStatusChange === 'function') onStatusChange();
      } catch (cbErr) {
        console.warn("onStatusChange callback threw, ignoring:", cbErr);
      }
      setStep(2);
    } catch (e) {
      console.error("Caught error in KYC submit:", e);
      // Coerce any shape (TypeError, FastAPI error, array of validation errors)
      // to a string. Previously e.stack could be a long stack trace dumped
      // into the red box; here we prefer the readable detail/message.
      const msg = (e && (e.detail || e.message)) || (typeof e === 'string' ? e : null) || 'Submit failed';
      setError(String(msg));
    }
    setSubmitting(false);
  };

  const status = statusData?.status;
  const isDone = status === 'approved' || status === 'pending';

  return (
    <>
      <div className="topbar">
        <div>
          <div className="crumb">Identity verification</div>
          <h1 className="h1">Complete your KYC</h1>
        </div>
        {status && <span className={'pill ' + (status === 'approved' ? 'pos' : status === 'rejected' ? 'neg' : 'warn')}><span className="dot"/>{status}</span>}
      </div>
      <div className="content">
        {isDone && status === 'approved' && (
          <div className="card" style={{ textAlign: 'center', padding: 40 }}>
            <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--pos-soft)', color: 'var(--pos)', display: 'grid', placeItems: 'center', margin: '0 auto 14px' }}>
              <IconCheck size={32}/>
            </div>
            <h2 className="h2">KYC verified</h2>
            <p className="muted">You're fully verified — invest without limits.</p>
          </div>
        )}
        {status === 'pending' && (
          <div className="card" style={{ textAlign: 'center', padding: 40 }}>
            <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--warn-soft)', color: 'var(--warn)', display: 'grid', placeItems: 'center', margin: '0 auto 14px' }}>
              <IconClock size={32}/>
            </div>
            <h2 className="h2">Under review</h2>
            <p className="muted">Submitted — typically reviewed within 24 hours.</p>
          </div>
        )}
        {!isDone && (
          <div className="grid" style={{ gridTemplateColumns: '1.3fr 1fr', gap: 22 }}>
            <div className="card">
              <h2 className="h2">Personal details</h2>
              <div className="grid grid-2" style={{ marginTop: 16 }}>
                <div className="field"><label className="field-label">Full name (as on KTP)</label><input className="input" value={name} onChange={(e) => setName(e.target.value)}/></div>
                <div className="field"><label className="field-label">NIK (KTP number)</label><input className="input num" value={ktp} onChange={(e) => setKtp(e.target.value)}/></div>
              </div>
              {status === 'rejected' && statusData?.rejection_reason && (
                <div style={{ marginTop: 14, fontSize: 13, color: 'var(--neg)', background: 'var(--neg-soft)', padding: 10, borderRadius: 8 }}>
                  Previous submission rejected: {statusData.rejection_reason}
                </div>
              )}
              {error && <div style={{ marginTop: 14, fontSize: 13, color: 'var(--neg)', background: 'var(--neg-soft)', padding: 10, borderRadius: 8 }}>{error}</div>}
              <button className="btn primary block lg" style={{ marginTop: 20 }} onClick={submit} disabled={!name || !ktp || submitting}>
                {submitting ? 'Submitting…' : 'Submit for review'}
              </button>
            </div>
            <div className="card flat">
              <h3 className="h3">Why we need this</h3>
              <p className="muted" style={{ fontSize: 13.5, marginTop: 8, lineHeight: 1.6 }}>
                Aeizch is a Closed User Group. KYC ensures every member is an invited individual and helps us comply with Indonesian financial regulations.
              </p>
              <div style={{ marginTop: 16, padding: 14, borderRadius: 12, background: 'var(--bg-soft)', border: '1px solid var(--line)' }}>
                <div className="row gap-10">
                  <IconShield size={18} style={{ color: 'var(--accent)' }}/>
                  <strong style={{ fontSize: 13.5 }}>Your data, encrypted</strong>
                </div>
                <p className="tiny muted" style={{ marginTop: 6, lineHeight: 1.5 }}>Stored encrypted; only accessed during review.</p>
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { Sidebar, Dashboard, BotsList, BotDetail, History, Deposit, KYC, colorFor, emojiFor });
