/* ============================================================================
   VIEW 3 — WATCHLIST  (filterable tracked tickers)
   ============================================================================ */
const { useState:useStateWL } = React;

const STATUS_STYLE = {
  "New":       { c:"#7aa7ff", bg:"rgba(122,167,255,0.12)", b:"rgba(122,167,255,0.35)" },
  "Tracking":  { c:"var(--text-2)", bg:"var(--fill-strong)",  b:"var(--line)" },
  "Triggered": { c:"#15bd80", bg:"rgba(31,224,160,0.12)",   b:"rgba(31,224,160,0.4)" },
  "Dropped":   { c:"#8a929e", bg:"var(--fill-soft)",  b:"var(--line)" },
};
function StatusTag({ status }){
  const s = STATUS_STYLE[status] || STATUS_STYLE["Tracking"];
  const dropped = status==="Dropped";
  return (
    <span className="inline-flex items-center gap-1.5 rounded-md px-2 py-0.5 text-[10.5px] font-medium uppercase tracking-wide"
          style={{ color:s.c, background:s.bg, border:`1px solid ${s.b}`, opacity:dropped?0.7:1 }}>
      {status==="Triggered" && <span className="rounded-full" style={{width:5,height:5,background:s.c,boxShadow:`0 0 5px ${s.c}`}}/>}
      {status}
    </span>
  );
}

function FilterPills({ label, options, value, onChange }){
  return (
    <div className="flex items-center gap-1.5 flex-wrap">
      <span className="text-[10px] uppercase tracking-[0.12em] mr-1" style={{color:"var(--muted)"}}>{label}</span>
      {["All",...options].map(o=>(
        <button key={o} onClick={()=>onChange(o)}
                className="rounded-md px-2.5 py-1 text-[11.5px] font-medium transition-colors"
                style={ value===o
                  ? { background:"var(--accent)", color:"#1a1606" }
                  : { background:"var(--fill)", color:"var(--muted)", border:"1px solid var(--line)" } }>
          {o}
        </button>
      ))}
    </div>
  );
}

function Watchlist({ rows, onOpen }){
  const [tier, setTier] = useStateWL("All");
  const [sector, setSector] = useStateWL("All");
  const sectors = [...new Set(rows.map(r=>r.sector))];
  const filtered = rows.filter(r=> (tier==="All"||r.tier===tier) && (sector==="All"||r.sector===sector))
                       .sort((a,b)=> TIER_ORDER[a.tier]-TIER_ORDER[b.tier] || b.conviction-a.conviction);
  const cols = ["Ticker","Tier","Conviction","Trend","Price","Sector","Days","Status"];
  return (
    <div className="flex flex-col gap-5">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h2 className="text-xl font-bold" style={{color:"var(--text)"}}>Watchlist</h2>
          <p className="text-[12.5px]" style={{color:"var(--muted)"}}>{filtered.length} of {rows.length} tracked tickers</p>
        </div>
      </div>

      <div className="ss-card p-4 flex flex-wrap items-center gap-x-6 gap-y-3">
        <FilterPills label="Tier"   options={["Strong Buy","Buy","Watch","Avoid"]} value={tier} onChange={setTier} />
        <div className="hidden md:block w-px h-5" style={{background:"var(--line)"}} />
        <FilterPills label="Sector" options={sectors} value={sector} onChange={setSector} />
      </div>

      <div className="ss-card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[840px] border-collapse">
            <thead>
              <tr style={{borderBottom:"1px solid var(--line)"}}>
                {cols.map((c,i)=>(
                  <th key={c} className={"text-[10.5px] uppercase tracking-[0.1em] font-medium py-3 px-4 "+(i===0?"text-left":i>=4&&i<=6?"text-right":"text-left")}
                      style={{color:"var(--muted)"}}>{c}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map(r=>{
                const t = tierOf(r.tier);
                const dropped = r.status==="Dropped";
                return (
                  <tr key={r.ticker} onClick={()=>onOpen(r.ticker)}
                      className="ss-trow cursor-pointer" style={{borderBottom:"1px solid var(--line)", opacity:dropped?0.6:1}}>
                    <td className="py-3 px-4">
                      <div className="flex items-center gap-2.5">
                        <span className="w-[3px] h-7 rounded-full" style={{background:t.color}} />
                        <span className="font-mono text-[15px] font-bold" style={{color:"var(--text)"}}>{r.ticker}</span>
                      </div>
                    </td>
                    <td className="py-3 px-4"><TierBadge tier={r.tier} size="sm" /></td>
                    <td className="py-3 px-4">
                      <div className="flex items-center gap-2.5 w-[150px]">
                        <span className="font-mono text-[14px] font-bold tabular-nums w-6" style={{color:t.color}}>{r.conviction}</span>
                        <div className="flex-1"><ConvictionBar value={r.conviction} color={t.color} height={6} /></div>
                      </div>
                    </td>
                    <td className="py-3 px-4"><TrendSpark data={r.conviction_trend} /></td>
                    <td className="py-3 px-4 text-right">
                      <div className="font-mono text-[13px] tabular-nums" style={{color:"var(--text)"}}>{fmtPrice(r.price)}</div>
                      <ChangePill value={r.change_pct} className="text-[11px]" />
                    </td>
                    <td className="py-3 px-4 text-right"><span className="text-[12.5px]" style={{color:"var(--muted)"}}>{r.sector}</span></td>
                    <td className="py-3 px-4 text-right"><span className="font-mono text-[13px] tabular-nums" style={{color:"var(--text-2)"}}>{r.days_tracked}</span></td>
                    <td className="py-3 px-4"><StatusTag status={r.status} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {!filtered.length && <div className="py-12 text-center text-[13px]" style={{color:"var(--muted)"}}>No tickers match these filters.</div>}
      </div>
    </div>
  );
}

Object.assign(window, { Watchlist });
