/* ============================================================================
   StonksScout — CHART PRIMITIVES (hand-rolled SVG, no chart deps)
   ============================================================================ */
const { useId } = React;

/* ---- Conviction bar (signature 0–100 readout) ----------------------------- */
function ConvictionBar({ value, color, height=10, showScale=false }){
  const pct = Math.max(0, Math.min(100, value));
  return (
    <div className="w-full">
      <div className="relative w-full rounded-full overflow-hidden"
           style={{ height, background:"var(--track)" }}>
        <div className="absolute inset-y-0 left-0 rounded-full"
             style={{ width: pct+"%", background:`linear-gradient(90deg, ${color}aa, ${color})`,
                      boxShadow:`0 0 14px ${color}66` }} />
        {[25,50,75].map(t=>(
          <div key={t} className="absolute inset-y-0" style={{ left:t+"%", width:1, background:"rgba(0,0,0,0.45)" }} />
        ))}
      </div>
      {showScale && (
        <div className="flex justify-between mt-1 font-mono text-[10px]" style={{ color:"var(--muted)" }}>
          <span>0</span><span>50</span><span>100</span>
        </div>
      )}
    </div>
  );
}

/* ---- Big conviction gauge (detail view) — 270° arc ------------------------ */
function ConvictionGauge({ value, color, size=190, label }){
  const pct = Math.max(0, Math.min(100, value));
  const r = size/2 - 16, cx = size/2, cy = size/2;
  const start = 135, sweep = 270;
  const polar = (deg) => {
    const a = (deg) * Math.PI/180;
    return [cx + r*Math.cos(a), cy + r*Math.sin(a)];
  };
  const arc = (fromPct, toPct) => {
    const a0 = start + (sweep*fromPct/100), a1 = start + (sweep*toPct/100);
    const [x0,y0] = polar(a0), [x1,y1] = polar(a1);
    const large = (a1-a0) > 180 ? 1 : 0;
    return `M ${x0} ${y0} A ${r} ${r} 0 ${large} 1 ${x1} ${y1}`;
  };
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="block">
      <path d={arc(0,100)} fill="none" stroke="var(--track)" strokeWidth="13" strokeLinecap="round" />
      <path d={arc(0,pct)} fill="none" stroke={color} strokeWidth="13" strokeLinecap="round"
            style={{ filter:`drop-shadow(0 0 10px ${color}88)` }} />
      <text x={cx} y={cy-4} textAnchor="middle" className="font-mono font-bold"
            style={{ fontSize:size*0.27, fill:"var(--text)" }}>{Math.round(pct)}</text>
      <text x={cx} y={cy+size*0.13} textAnchor="middle" className="font-mono"
            style={{ fontSize:11, fill:"var(--muted)", letterSpacing:"0.12em" }}>{label || "CONVICTION"}</text>
    </svg>
  );
}

/* ---- Radar / spider chart (8 factors) ------------------------------------- */
function RadarChart({ factors, color, size=300 }){
  const keys = Object.keys(factors);
  const n = keys.length, cx=size/2, cy=size/2, R=size/2-46;
  const pt = (i, rad) => {
    const a = (-90 + i*360/n) * Math.PI/180;
    return [cx + rad*Math.cos(a), cy + rad*Math.sin(a)];
  };
  const rings = [0.25,0.5,0.75,1];
  const poly = (vals) => vals.map((v,i)=>pt(i, R*v/100).join(",")).join(" ");
  const gridPoly = (f) => keys.map((_,i)=>pt(i, R*f).join(",")).join(" ");
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="block mx-auto">
      {rings.map((f,i)=>(
        <polygon key={i} points={gridPoly(f)} fill="none"
                 stroke="var(--track)" strokeWidth="1" />
      ))}
      {keys.map((k,i)=>{
        const [x,y]=pt(i,R);
        return <line key={k} x1={cx} y1={cy} x2={x} y2={y} stroke="var(--track)" strokeWidth="1" />;
      })}
      <polygon points={poly(keys.map(k=>factors[k]))}
               fill={color+"33"} stroke={color} strokeWidth="2"
               style={{ filter:`drop-shadow(0 0 8px ${color}55)` }} />
      {keys.map((k,i)=>{
        const [x,y]=pt(i, R*factors[k]/100);
        return <circle key={k} cx={x} cy={y} r="3" fill={color} />;
      })}
      {keys.map((k,i)=>{
        const [x,y]=pt(i, R+24);
        const lbl = FACTOR_LABELS[k] || k;
        return (
          <text key={k} x={x} y={y} textAnchor="middle" dominantBaseline="middle"
                style={{ fontSize:9.5, fill:"var(--muted)", letterSpacing:"0.02em" }}>
            <tspan x={x} dy="-4">{lbl.split(" ")[0]}</tspan>
            {lbl.split(" ")[1] && <tspan x={x} dy="11">{lbl.split(" ")[1]}</tspan>}
          </text>
        );
      })}
    </svg>
  );
}

/* ---- Labeled factor bars (compact, used in cards) ------------------------- */
function FactorBars({ factors, color, compact=false }){
  const keys = Object.keys(factors);
  return (
    <div className={"grid gap-x-5 gap-y-"+(compact?"1.5":"2.5")} style={{ gridTemplateColumns:"1fr 1fr" }}>
      {keys.map(k=>(
        <div key={k} className="flex items-center gap-2">
          <span className="font-mono shrink-0 text-[10px] uppercase tracking-wide"
                style={{ color:"var(--muted)", width:compact?72:88 }}>
            {(FACTOR_LABELS[k]||k).replace(" ","\u00A0")}
          </span>
          <div className="relative flex-1 rounded-full overflow-hidden" style={{ height:6, background:"var(--track)" }}>
            <div className="absolute inset-y-0 left-0 rounded-full"
                 style={{ width:factors[k]+"%", background:color, opacity:0.55+0.45*factors[k]/100 }} />
          </div>
          <span className="font-mono text-[10px] tabular-nums w-5 text-right" style={{ color:"var(--text)" }}>{factors[k]}</span>
        </div>
      ))}
    </div>
  );
}

/* ---- Sparkline (price history) -------------------------------------------- */
function Sparkline({ data, color, width=120, height=34, strokeWidth=1.6, fill=true }){
  const gid = useId().replace(/:/g,"");
  if(!data || data.length<2) return <svg width={width} height={height} />;
  const min = Math.min(...data), max = Math.max(...data), span = (max-min)||1;
  const x = (i) => (i/(data.length-1))*(width-2)+1;
  const y = (v) => height-2 - ((v-min)/span)*(height-4);
  const pts = data.map((v,i)=>[x(i),y(v)]);
  const line = pts.map((p,i)=>(i?"L":"M")+p[0].toFixed(1)+" "+p[1].toFixed(1)).join(" ");
  const area = line + ` L ${width-1} ${height} L 1 ${height} Z`;
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} className="block overflow-visible">
      <defs>
        <linearGradient id={"sg"+gid} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.30" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {fill && <path d={area} fill={`url(#sg${gid})`} />}
      <path d={line} fill="none" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.2" fill={color} />
    </svg>
  );
}

/* ---- Trend chip (tiny conviction trend with delta) ------------------------ */
function TrendSpark({ data, width=58, height=20 }){
  const delta = data[data.length-1]-data[0];
  const c = delta>=0 ? "#17a86a" : "#ee3f5f";
  return (
    <div className="flex items-center gap-1.5">
      <Sparkline data={data} color={c} width={width} height={height} strokeWidth={1.4} fill={false} />
      <span className="font-mono text-[10px] tabular-nums" style={{ color:c }}>
        {delta>=0?"+":""}{delta}
      </span>
    </div>
  );
}

/* ---- Price chart with entry / stop / target lines (detail view) ----------- */
function PriceChart({ data, frame, color, width=560, height=220 }){
  const gid = useId().replace(/:/g,"");
  const padL=8, padR=64, padT=14, padB=18;
  const levels = [];
  if(frame){
    if(frame.stop!=null) levels.push({v:frame.stop, c:"#ee3f5f", t:"STOP"});
    (frame.targets||[]).forEach((t,i)=>levels.push({v:t, c:"#17a86a", t:"T"+(i+1)}));
  }
  const allVals = [...data, ...levels.map(l=>l.v)];
  const min = Math.min(...allVals)*0.985, max = Math.max(...allVals)*1.015, span=(max-min)||1;
  const x = (i)=> padL + (i/(data.length-1))*(width-padL-padR);
  const y = (v)=> padT + (1-(v-min)/span)*(height-padT-padB);
  const pts = data.map((v,i)=>[x(i),y(v)]);
  const line = pts.map((p,i)=>(i?"L":"M")+p[0].toFixed(1)+" "+p[1].toFixed(1)).join(" ");
  const area = line + ` L ${x(data.length-1)} ${height-padB} L ${padL} ${height-padB} Z`;
  return (
    <svg width="100%" viewBox={`0 0 ${width} ${height}`} className="block">
      <defs>
        <linearGradient id={"pc"+gid} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.28" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {levels.map((l,i)=>(
        <g key={i}>
          <line x1={padL} x2={width-padR} y1={y(l.v)} y2={y(l.v)} stroke={l.c} strokeWidth="1" strokeDasharray="4 4" opacity="0.7" />
          <rect x={width-padR+4} y={y(l.v)-8} width={padR-6} height={16} rx="3" fill={l.c+"22"} />
          <text x={width-padR+8} y={y(l.v)+3} style={{fontSize:9, fill:l.c}} className="font-mono">
            {l.t} {Number(l.v).toFixed(2)}
          </text>
        </g>
      ))}
      <path d={area} fill={`url(#pc${gid})`} />
      <path d={line} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="3" fill={color}
              style={{filter:`drop-shadow(0 0 6px ${color})`}} />
    </svg>
  );
}

/* ---- Analyst rating split (stacked bar) ----------------------------------- */
function AnalystSplit({ a }){
  const segs = [
    { k:"Strong Buy", v:a.strong_buy, c:"#15bd80" },
    { k:"Buy",        v:a.buy,        c:"#17a86a" },
    { k:"Hold",       v:a.hold,       c:"#b9870c" },
    { k:"Sell",       v:a.sell,       c:"#ee3f5f" },
  ];
  const total = segs.reduce((s,x)=>s+x.v,0)||1;
  return (
    <div>
      <div className="flex w-full h-3 rounded-full overflow-hidden" style={{background:"var(--track)"}}>
        {segs.map(s=> s.v>0 && (
          <div key={s.k} style={{ width:(s.v/total*100)+"%", background:s.c }} title={`${s.k}: ${s.v}`} />
        ))}
      </div>
      <div className="flex flex-wrap gap-x-4 gap-y-1 mt-2.5">
        {segs.map(s=>(
          <div key={s.k} className="flex items-center gap-1.5">
            <span className="w-2 h-2 rounded-sm" style={{background:s.c}} />
            <span className="text-[11px]" style={{color:"var(--muted)"}}>{s.k}</span>
            <span className="font-mono text-[11px] tabular-nums" style={{color:"var(--text)"}}>{s.v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ConvictionBar, ConvictionGauge, RadarChart, FactorBars, Sparkline, TrendSpark, PriceChart, AnalystSplit });
