/* ============================================================================
   VIEW 4 — PERFORMANCE LEDGER  (does the engine actually work?)
   ============================================================================ */
const { useMemo:useMemoLedger } = React;

function KpiCard({ label, value, accent, sub, big }){
  return (
    <div className="ss-card relative overflow-hidden px-5 py-4 flex flex-col gap-1.5">
      {accent && <div className="absolute left-0 top-0 bottom-0 w-[3px]" style={{background:accent}} />}
      <span className="text-[10.5px] uppercase tracking-[0.13em]" style={{color:"var(--muted)"}}>{label}</span>
      <span className={"font-mono font-bold tabular-nums leading-none "+(big?"text-4xl":"text-2xl")} style={{color:accent||"var(--text)"}}>{value}</span>
      {sub && <span className="text-[11.5px]" style={{color:"var(--muted)"}}>{sub}</span>}
    </div>
  );
}

/* tiny win/loss distribution bar for 1w returns */
function HitBar({ rows }){
  const sorted = [...rows].sort((a,b)=>a.ret_1w-b.ret_1w);
  const max = Math.max(...rows.map(r=>Math.abs(r.ret_1w)))||1;
  return (
    <div className="flex items-end gap-[3px] h-12">
      {sorted.map(r=>{
        const pos = r.ret_1w>=0;
        return (
          <div key={r.ticker} className="relative group/hb flex-1 flex flex-col justify-center" style={{minWidth:6}}>
            <div className="w-full rounded-sm" style={{ height:Math.max(3,Math.abs(r.ret_1w)/max*46)+"px", background:pos?"#17a86a":"#ee3f5f", opacity:0.85, alignSelf: pos?"flex-end":"flex-start", marginTop:pos?"auto":0, marginBottom:pos?0:"auto" }} />
            <div className="pointer-events-none absolute bottom-full mb-1 left-1/2 -translate-x-1/2 z-20 hidden group-hover/hb:block whitespace-nowrap rounded px-1.5 py-0.5 text-[9px] font-mono"
                 style={{background:"#000",color:"var(--text)",border:"1px solid var(--line)"}}>
              {r.ticker} {fmtPct(r.ret_1w)}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function PerformanceLedger({ rows }){
  const k = useMemoLedger(()=>ledgerKpis(rows),[rows]);
  const [sortKey, setSortKey] = React.useState("recommended_at");
  const [dir, setDir] = React.useState(-1);
  const sorted = useMemoLedger(()=>{
    return [...rows].sort((a,b)=>{
      const av=a[sortKey], bv=b[sortKey];
      if(typeof av==="string") return av<bv?-dir:av>bv?dir:0;
      return (av-bv)*dir;
    });
  },[rows,sortKey,dir]);
  const setSort = (key)=>{ if(sortKey===key) setDir(d=>-d); else { setSortKey(key); setDir(-1); } };

  const cols = [
    {k:"ticker", label:"Ticker", align:"left"},
    {k:"recommended_at", label:"Recommended", align:"left"},
    {k:"tier", label:"Tier", align:"left"},
    {k:"entry", label:"Entry", align:"right"},
    {k:"ret_1d", label:"1D", align:"right"},
    {k:"ret_1w", label:"1W", align:"right"},
    {k:"ret_1m", label:"1M", align:"right"},
    {k:"status", label:"Status", align:"left"},
  ];

  return (
    <div className="flex flex-col gap-5">
      <div>
        <h2 className="text-xl font-bold" style={{color:"var(--text)"}}>Performance Ledger</h2>
        <p className="text-[12.5px]" style={{color:"var(--muted)"}}>Forward returns on past verdicts · {k.n} records</p>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <KpiCard label="Hit Rate (1W)" value={k.hit+"%"} accent={k.hit>=60?"#15bd80":k.hit>=50?"#b9870c":"#ee3f5f"} sub="% positive after 1 week" big />
        <KpiCard label="Avg 1W Return" value={fmtPct(k.avg1w)} accent={k.avg1w>=0?"#17a86a":"#ee3f5f"} sub="mean across records" big />
        <KpiCard label="Best (1M)" value={fmtPct(k.best.ret_1m)} accent="#17a86a" sub={k.best.ticker+" · "+k.best.recommended_at} big />
        <KpiCard label="Worst (1M)" value={fmtPct(k.worst.ret_1m)} accent="#ee3f5f" sub={k.worst.ticker+" · "+k.worst.recommended_at} big />
      </div>

      {/* distribution */}
      <div className="ss-card px-5 py-4">
        <div className="flex items-center justify-between mb-3">
          <span className="text-[11px] uppercase tracking-[0.12em]" style={{color:"var(--muted)"}}>1-Week return distribution</span>
          <div className="flex items-center gap-3 text-[10.5px]" style={{color:"var(--muted)"}}>
            <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-sm" style={{background:"#17a86a"}}/>win</span>
            <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-sm" style={{background:"#ee3f5f"}}/>loss</span>
          </div>
        </div>
        <HitBar rows={rows} />
      </div>

      {/* table */}
      <div className="ss-card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[760px] border-collapse">
            <thead>
              <tr style={{borderBottom:"1px solid var(--line)"}}>
                {cols.map(c=>(
                  <th key={c.k} onClick={()=>setSort(c.k)}
                      className={"select-none cursor-pointer text-[10.5px] uppercase tracking-[0.1em] font-medium py-3 px-4 hover:text-white transition-colors "+(c.align==="right"?"text-right":"text-left")}
                      style={{color: sortKey===c.k?"var(--accent)":"var(--muted)"}}>
                    <span className="inline-flex items-center gap-1">
                      {c.label}
                      {sortKey===c.k && <span className="font-mono text-[9px]">{dir<0?"▼":"▲"}</span>}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {sorted.map(r=>(
                <tr key={r.ticker+r.recommended_at} className="ss-trow" style={{borderBottom:"1px solid var(--line)"}}>
                  <td className="py-3 px-4"><span className="font-mono text-[14px] font-bold" style={{color:"var(--text)"}}>{r.ticker}</span></td>
                  <td className="py-3 px-4"><span className="font-mono text-[12.5px]" style={{color:"var(--muted)"}}>{r.recommended_at}</span></td>
                  <td className="py-3 px-4"><TierBadge tier={r.tier} size="sm" /></td>
                  <td className="py-3 px-4 text-right"><span className="font-mono text-[13px] tabular-nums" style={{color:"var(--text-2)"}}>{fmtPrice(r.entry)}</span></td>
                  <td className="py-3 px-4 text-right"><Ret value={r.ret_1d} /></td>
                  <td className="py-3 px-4 text-right">
                    <span className="inline-block rounded px-2 py-0.5" style={{background: r.ret_1w>0?"rgba(70,211,154,0.1)":"rgba(245,85,109,0.1)"}}><Ret value={r.ret_1w} /></span>
                  </td>
                  <td className="py-3 px-4 text-right"><Ret value={r.ret_1m} /></td>
                  <td className="py-3 px-4">
                    <span className="text-[11.5px] px-2 py-0.5 rounded" style={{ color: r.status==="Open"?"#7aa7ff":"var(--muted)", border:"1px solid var(--line)", background:r.status==="Open"?"rgba(122,167,255,0.08)":"transparent" }}>{r.status}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      <p className="text-[11px] px-1" style={{color:"var(--muted)"}}>Illustrative track record for demonstration — past performance does not guarantee future results.</p>
    </div>
  );
}

Object.assign(window, { PerformanceLedger });
