// ============ Dashboard page ============
const DashboardPage = ({ setRoute }) => {
  const { t, fmtCur, fmtCurShort } = useI18n();
  const { active, accounts, accountsById, statsFor, todayPnlFor } = useAccounts();
  const pool = active==='all' ? TRADES : TRADES.filter(t => t.accountId===active);
  const recent = pool.filter(x=>x.status==='closed').slice(0,10);
  const curve = active==='all' ? EQUITY : equityCurveFor(active);
  const activeAcc = active==='all' ? null : accountsById[active];
  const startCap = activeAcc ? activeAcc.startingCapital : 25000;
  const stats = statsFor(active);
  const startEq = startCap;
  const curEq = curve.length ? curve[curve.length-1].equity : startCap;

  // Prop challenge progress
  let propProgress = null;
  if (activeAcc && activeAcc.type==='prop_challenge' && activeAcc.rules) {
    const r = activeAcc.rules;
    const todayLoss = Math.max(0, -todayPnlFor(active));
    const totalLoss = Math.max(0, -stats.netPnl);
    const profit = Math.max(0, stats.netPnl);
    const dailyPct = (todayLoss / (startCap * r.maxDailyLoss / 100)) * 100;
    const totalPct = (totalLoss / (startCap * r.maxTotalLoss / 100)) * 100;
    const profitPct = r.profitTarget > 0 ? (profit / (startCap * r.profitTarget / 100)) * 100 : 0;
    const daysLeft = r.deadline ? Math.ceil((new Date(r.deadline) - new Date(2026,3,21)) / 86400000) : null;
    propProgress = { dailyPct, totalPct, profitPct, rules:r, daysLeft, todayLoss, totalLoss, profit, startCap };
  }

  const colorForLoss = (pct) => pct >= 80 ? '#ef4444' : pct >= 50 ? '#f59e0b' : '#10b981';
  const colorForGain = (pct) => pct >= 100 ? '#10b981' : pct >= 50 ? '#3b82f6' : '#a3a3a3';
  return (
    <div className="page">
      <PageHead
        title={<span style={{display:'inline-flex',alignItems:'center',gap:10,flexWrap:'wrap'}}>
          {t('nav_dashboard')}
          {activeAcc && (
            <span className="acct-type-badge" style={{background:`color-mix(in srgb, ${accountTypeColor(activeAcc.type)} 18%, transparent)`, color: accountTypeColor(activeAcc.type), fontSize:11}}>
              {accountTypeLabel(activeAcc.type)}
            </span>
          )}
        </span>}
        sub={activeAcc ? `${activeAcc.name} · ${activeAcc.broker} · ${activeAcc.assetClass}` : t('dash_sub')}
        actions={
          <>
            <div className="seg">
              <button className="on">30D</button>
              <button>90D</button>
              <button>YTD</button>
              <button>All</button>
            </div>
            <button className="btn"><Icon name="download" size={13}/> {t('export')}</button>
          </>
        }
      />

      {propProgress && (
        <div className="card card-pad mb-16" style={{padding:'18px 20px'}}>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:16,flexWrap:'wrap',gap:8}}>
            <div>
              <div style={{fontWeight:600,fontSize:14,display:'flex',alignItems:'center',gap:8}}>
                <div style={{width:6,height:6,borderRadius:999,background:'#f59e0b'}}/>
                {t('challenge_rules')}
              </div>
              <div className="tiny muted" style={{marginTop:2}}>
                {propProgress.rules.deadline && (propProgress.daysLeft > 0 ? t('days_left',{n:propProgress.daysLeft}) : t('expired'))}
              </div>
            </div>
          </div>
          <div className="g-3">
            <div>
              <div style={{display:'flex',justifyContent:'space-between',marginBottom:6}}>
                <span className="tiny muted">{t('daily_loss_used')}</span>
                <span className="mono tiny" style={{fontWeight:600, color:colorForLoss(propProgress.dailyPct)}}>{Math.min(100,propProgress.dailyPct).toFixed(0)}%</span>
              </div>
              <div className="prop-bar"><span style={{width:Math.min(100,propProgress.dailyPct)+'%', background:colorForLoss(propProgress.dailyPct)}}/></div>
              <div className="tiny muted mono" style={{marginTop:6}}>{fmtCurShort(-propProgress.todayLoss)} / {fmtCurShort(-(propProgress.startCap*propProgress.rules.maxDailyLoss/100))}</div>
            </div>
            <div>
              <div style={{display:'flex',justifyContent:'space-between',marginBottom:6}}>
                <span className="tiny muted">{t('total_loss_used')}</span>
                <span className="mono tiny" style={{fontWeight:600, color:colorForLoss(propProgress.totalPct)}}>{Math.min(100,propProgress.totalPct).toFixed(0)}%</span>
              </div>
              <div className="prop-bar"><span style={{width:Math.min(100,propProgress.totalPct)+'%', background:colorForLoss(propProgress.totalPct)}}/></div>
              <div className="tiny muted mono" style={{marginTop:6}}>{fmtCurShort(-propProgress.totalLoss)} / {fmtCurShort(-(propProgress.startCap*propProgress.rules.maxTotalLoss/100))}</div>
            </div>
            <div>
              <div style={{display:'flex',justifyContent:'space-between',marginBottom:6}}>
                <span className="tiny muted">{t('profit_target_progress')}</span>
                <span className="mono tiny" style={{fontWeight:600, color:colorForGain(propProgress.profitPct)}}>{Math.min(100,propProgress.profitPct).toFixed(0)}%</span>
              </div>
              <div className="prop-bar"><span style={{width:Math.min(100,propProgress.profitPct)+'%', background:colorForGain(propProgress.profitPct)}}/></div>
              <div className="tiny muted mono" style={{marginTop:6}}>{fmtCurShort(propProgress.profit)} / {fmtCurShort(propProgress.startCap*propProgress.rules.profitTarget/100)}</div>
            </div>
          </div>
        </div>
      )}

      <KPIRow />

      {active==='all' && (
        <div className="card mb-16">
          <div className="card-head">
            <div>
              <div className="card-title">{t('accounts_snapshot')}</div>
              <div className="card-sub">{t('accounts_snapshot_sub')}</div>
            </div>
          </div>
          <div className="card-pad" style={{padding:'16px 18px'}}>
            <div className="g-3">
              {accounts.map(a => {
                const as = statsFor(a.id);
                const today = todayPnlFor(a.id);
                const bal = a.startingCapital + as.netPnl;
                let propPct = null, propColor = null;
                if (a.type==='prop_challenge' && a.rules) {
                  const loss = Math.max(0, -as.netPnl);
                  propPct = (loss / (a.startingCapital * a.rules.maxTotalLoss / 100)) * 100;
                  propColor = colorForLoss(propPct);
                }
                return (
                  <div key={a.id} className="card" style={{padding:14, cursor:'pointer', background:'#0f0f0f'}}>
                    <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:10}}>
                      <div className="acct-avatar" style={{width:24,height:24,fontSize:11,background:a.color}}>{a.name.slice(0,1)}</div>
                      <div style={{flex:1,minWidth:0}}>
                        <div style={{fontWeight:500,fontSize:13,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{a.name}</div>
                        <div className="tiny muted">{a.broker}</div>
                      </div>
                      {a.type==='prop_challenge' && <span className="acct-type-badge" style={{background:'rgba(245,158,11,.15)',color:'#f59e0b'}}>C</span>}
                      {a.type==='prop_funded' && <span className="acct-type-badge" style={{background:'rgba(59,130,246,.15)',color:'#3b82f6'}}>F</span>}
                    </div>
                    <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline'}}>
                      <span className="tiny muted">{t('balance')}</span>
                      <span className="mono" style={{fontSize:14,fontWeight:600}}>{fmtCurShort(bal)}</span>
                    </div>
                    <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginTop:4}}>
                      <span className="tiny muted">{t('today_pnl')}</span>
                      <span className={'mono tiny ' + (today>=0?'up':'dn')} style={{fontWeight:600}}>{fmtCurShort(today)}</span>
                    </div>
                    {propPct != null && (
                      <>
                        <div className="prop-bar" style={{marginTop:10,height:5}}><span style={{width:Math.min(100,propPct)+'%', background:propColor}}/></div>
                        <div className="tiny muted" style={{marginTop:4}}>{Math.min(100,propPct).toFixed(0)}% {t('total_loss_used').toLowerCase()}</div>
                      </>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}

      <div className="card mb-16">
        <div className="card-head">
          <div>
            <div className="card-title">{t('equity_curve')}</div>
            <div className="card-sub">{t('equity_sub')}</div>
          </div>
          <div className="row">
            <span className="tiny muted">{t('starting')}</span>
            <span className="mono tiny">${startEq.toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2})}</span>
            <span className="tiny muted" style={{marginLeft:8}}>{t('current')}</span>
            <span className="mono tiny" style={{fontWeight:600}}>${curEq.toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2})}</span>
          </div>
        </div>
        <div style={{padding:'10px 12px 16px'}}>
          <EquityCurve height={300} />
        </div>
      </div>

      <div className="card">
        <div className="card-head">
          <div>
            <div className="card-title">{t('recent_trades')}</div>
            <div className="card-sub">{t('recent_trades_sub')}</div>
          </div>
          <button className="btn btn-ghost" onClick={()=>setRoute('trades')}>{t('view_all')} <Icon name="chevron-right" size={12}/></button>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>{t('th_ticker')}</th><th>{t('th_dir')}</th><th>{t('th_entry')}</th><th>{t('th_exit')}</th><th>{t('th_pnl')}</th><th>{t('th_r')}</th><th>{t('th_date')}</th>
            </tr>
          </thead>
          <tbody>
            {recent.map(tr => <TradeRow key={tr.id} t={tr} />)}
          </tbody>
        </table>
        <div>{recent.map(tr => <TradeCard key={tr.id} t={tr}/>)}</div>
      </div>
    </div>
  );
};

window.DashboardPage = DashboardPage;
