/* ============================================================================
   VIEW 1 — TODAY'S VERDICTS  (hero pick + rich ranked rows)
   ============================================================================ */

/* compact vertical mini-bars for the 8 signal sub-scores */
function SignalStrip({ factors, color, label=true }){
  const keys = Object.keys(factors);
  return (
    <div>
      {label && <div className="text-[9.5px] uppercase tracking-[0.12em] mb-1.5" style={{color:"var(--muted)"}}>Signals</div>}
      <div className="flex items-end gap-[3px]" style={{height:34}}>
        {keys.map(k=>{
          const v = factors[k];
          return (
            <div key={k} className="relative group/sig flex-1 flex items-end" style={{minWidth:7}}>
              <div className="w-full rounded-sm" style={{ height:Math.max(8,v)+"%", background:color, opacity:0.4+0.6*v/100 }} />
              <div className="pointer-events-none absolute bottom-full mb-1 left-1/2 -translate-x-1/2 z-20 hidden group-hover/sig: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)" }}>
                {(FACTOR_LABELS[k]||k)} {v}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function HeroPick({ v, onOpen }){
  const t = tierOf(v.tier);
  return (
    <div className="ss-card ss-hero relative overflow-hidden p-6 lg:p-7" style={{ borderColor:t.line }}>
      <div className="pointer-events-none absolute -top-24 -right-24 w-80 h-80 rounded-full blur-3xl"
           style={{ background:t.color, opacity:0.10 }} />
      <div className="flex items-center gap-2 mb-5">
        <span className="font-mono text-[11px] px-2 py-0.5 rounded" style={{background:"var(--accent)",color:"#1a1606",fontWeight:700}}>#1 TODAY</span>
        <span className="text-[11px] uppercase tracking-[0.14em]" style={{color:"var(--muted)"}}>Top conviction</span>
        {v.manipulation_flag && <span className="ml-auto"><PumpRisk/></span>}
      </div>

      <div className="grid lg:grid-cols-[1fr_auto] gap-6 lg:gap-8 items-start">
        {/* left */}
        <div className="min-w-0">
          <div className="flex flex-wrap items-center gap-x-4 gap-y-2 mb-3">
            <h2 className="font-mono text-4xl font-bold tracking-tight" style={{color:"var(--text)"}}>{v.ticker}</h2>
            <TierBadge tier={v.tier} size="lg" />
            <span className="text-[13px]" style={{color:"var(--muted)"}}>{v.company}</span>
            <span className="ml-auto"><PriceChange price={v.price} change={v.change_pct} /></span>
          </div>

          <p className="text-[15px] leading-relaxed mb-5 max-w-2xl" style={{color:"var(--text-2)"}}>{v.thesis}</p>

          <div className="grid sm:grid-cols-2 gap-x-8 gap-y-3 mb-5">
            <div>
              <div className="text-[10px] uppercase tracking-[0.12em] mb-2" style={{color:"var(--muted)"}}>Catalysts</div>
              <div className="flex flex-wrap gap-1.5">
                {v.catalysts.length ? v.catalysts.map((c,i)=><Chip key={i} tone="pos">{c}</Chip>)
                  : <span className="text-[12px]" style={{color:"var(--muted)"}}>None identified</span>}
              </div>
            </div>
            <div>
              <div className="text-[10px] uppercase tracking-[0.12em] mb-2" style={{color:"var(--muted)"}}>Risks</div>
              <div className="flex flex-wrap gap-1.5">
                {v.risks.map((c,i)=><Chip key={i} tone="neg">{c}</Chip>)}
              </div>
            </div>
          </div>

          <TradeFrame frame={v.trade_frame} tierColor={t.color} />
        </div>

        {/* right rail */}
        <div className="lg:w-[260px] flex flex-col gap-5">
          <div className="ss-inset rounded-xl p-4 flex flex-col items-center">
            <ConvictionGauge value={v.conviction} color={t.color} size={184} />
          </div>
          <SignalStrip factors={v.factors} color={t.color} />
          <button onClick={onOpen}
                  className="ss-btn-primary mt-1 w-full rounded-lg py-2.5 text-[13px] font-semibold flex items-center justify-center gap-2">
            Open full breakdown
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

function VerdictRow({ v, rank, onOpen }){
  const t = tierOf(v.tier);
  return (
    <button onClick={onOpen}
            className="ss-row group w-full text-left grid items-stretch"
            style={{ gridTemplateColumns:"40px minmax(190px,1.1fr) minmax(0,2fr) 188px 150px" }}>
      <div className="relative flex items-center justify-center" style={{borderRight:"1px solid var(--line)"}}>
        <span className="absolute left-0 top-0 bottom-0 w-[3px]" style={{background:t.color}} />
        <span className="font-mono text-sm" style={{color:"var(--muted)"}}>{String(rank).padStart(2,"0")}</span>
      </div>

      {/* identity */}
      <div className="px-4 py-3.5 flex flex-col justify-center gap-1" style={{borderRight:"1px solid var(--line)"}}>
        <div className="flex items-center gap-2">
          <span className="font-mono text-lg font-bold tracking-tight" style={{color:"var(--text)"}}>{v.ticker}</span>
          {v.manipulation_flag && <PumpRisk size="sm" />}
        </div>
        <span className="text-[12px] truncate" style={{color:"var(--muted)"}}>{v.company}</span>
        <PriceChange price={v.price} change={v.change_pct} />
      </div>

      {/* thesis + chips */}
      <div className="px-4 py-3.5 flex flex-col justify-center gap-2 min-w-0" style={{borderRight:"1px solid var(--line)"}}>
        <p className="text-[13px] leading-snug line-clamp-2" style={{color:"var(--text-2)"}}>{v.thesis}</p>
        <div className="flex flex-wrap gap-1.5">
          {v.catalysts.slice(0,2).map((c,i)=><Chip key={"c"+i} tone="pos">{c}</Chip>)}
          {v.risks.slice(0,1).map((c,i)=><Chip key={"r"+i} tone="neg">{c}</Chip>)}
          {(v.catalysts.length>2 || v.risks.length>1) &&
            <span className="text-[11px] self-center" style={{color:"var(--muted)"}}>
              +{(v.catalysts.length>2?v.catalysts.length-2:0)+(v.risks.length>1?v.risks.length-1:0)} more
            </span>}
        </div>
      </div>

      {/* conviction */}
      <div className="px-4 py-3.5 flex flex-col justify-center gap-2" style={{borderRight:"1px solid var(--line)"}}>
        <div className="flex items-center justify-between">
          <TierBadge tier={v.tier} size="sm" />
          <span className="font-mono text-xl font-bold tabular-nums" style={{color:t.color}}>{v.conviction}</span>
        </div>
        <ConvictionBar value={v.conviction} color={t.color} height={8} />
      </div>

      {/* signals */}
      <div className="px-4 py-3.5 flex items-center">
        <div className="flex-1"><SignalStrip factors={v.factors} color={t.color} label={false} /></div>
        <svg className="ml-2 shrink-0 opacity-40 group-hover:opacity-90 transition-opacity" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--text)" strokeWidth="2"><path d="M9 6l6 6-6 6"/></svg>
      </div>
    </button>
  );
}

function TodaysVerdicts({ verdicts, onOpen }){
  const sorted = [...verdicts].sort((a,b)=> b.conviction - a.conviction);
  const sum = verdictSummary(sorted);
  const [hero, ...rest] = sorted;
  return (
    <div className="flex flex-col gap-6">
      {/* summary stats */}
      <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-3">
        <StatCard label="Picks Today" value={sum.count} sub="ranked by conviction" />
        <StatCard label="Strong Buys" value={sum.strongBuys} accent="#15bd80" sub="highest tier" />
        <StatCard label="Avg Conviction" value={sum.avgConv} sub="across all picks" />
        <StatCard label="Pump Flags" value={sum.flags} accent={sum.flags?"#ee3f5f":"var(--text)"} sub="manipulation risk" />
        <div className="ss-card px-4 py-3.5 flex flex-col gap-1 justify-center col-span-2 md:col-span-1">
          <div className="flex items-center gap-2">
            <span className="relative flex h-2 w-2">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full opacity-60" style={{background:"#17a86a"}}></span>
              <span className="relative inline-flex rounded-full h-2 w-2" style={{background:"#17a86a"}}></span>
            </span>
            <span className="text-[12px] font-semibold" style={{color:"#17a86a"}}>Market Open</span>
          </div>
          <span className="font-mono text-[12px]" style={{color:"var(--text)"}}>Last run 06:40 ET</span>
          <span className="text-[11px]" style={{color:"var(--muted)"}}>Fri · May 30, 2026</span>
        </div>
      </div>

      <HeroPick v={hero} onOpen={()=>onOpen(hero.ticker)} />

      {/* rich rows */}
      <div>
        <div className="flex items-center justify-between mb-3 px-1">
          <h3 className="text-[13px] uppercase tracking-[0.14em]" style={{color:"var(--muted)"}}>Remaining ranked picks</h3>
          <span className="text-[11px] font-mono" style={{color:"var(--muted)"}}>{rest.length} more</span>
        </div>
        <div className="ss-card overflow-hidden divide-y" style={{ "--tw-divide-opacity":1 }}>
          {rest.map((v,i)=>(
            <VerdictRow key={v.ticker} v={v} rank={i+2} onOpen={()=>onOpen(v.ticker)} />
          ))}
        </div>
        <p className="text-[11px] mt-3 px-1" style={{color:"var(--muted)"}}>
          Illustrative tickers for demonstration — not investment advice.
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { TodaysVerdicts, SignalStrip });
