// charts.jsx — lightweight SVG charts for LBC Platform
const { useState: useStateC } = React;

/* ---- Area / line chart (commissions over time) ---- */
function AreaChart({ data, height = 150, color = 'var(--brand)', fmt }) {
  const [hover, setHover] = useStateC(null);
  const fm = fmt || euro;
  const W = 520, H = height, padX = 14, padTop = 16, padBot = 26;
  const max = Math.max(...data.map(d => d.v)) * 1.18 || 1;
  const innerW = W - padX * 2, innerH = H - padTop - padBot;
  const x = i => padX + (data.length === 1 ? innerW / 2 : (i / (data.length - 1)) * innerW);
  const y = v => padTop + innerH - (v / max) * innerH;
  const pts = data.map((d, i) => [x(i), y(d.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).toFixed(1)} ${(padTop + innerH).toFixed(1)} L${x(0).toFixed(1)} ${(padTop + innerH).toFixed(1)} Z`;

  return (
    <div style={{ position:'relative', width:'100%' }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} style={{ display:'block', overflow:'visible' }}
        onMouseLeave={()=>setHover(null)}>
        <defs>
          <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.22" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>
        {[0.5, 1].map((g,i)=>(
          <line key={i} x1={padX} x2={W-padX} y1={padTop + innerH*(1-g)} y2={padTop + innerH*(1-g)}
            stroke="var(--border)" strokeWidth="1" strokeDasharray="3 4" />
        ))}
        <path d={area} fill="url(#areaGrad)" />
        <path d={line} fill="none" stroke={color} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
        {data.map((d,i)=>(
          <g key={i}>
            <rect x={x(i)-innerW/(data.length*2)} y={padTop} width={innerW/data.length} height={innerH}
              fill="transparent" onMouseEnter={()=>setHover(i)} />
            <circle cx={x(i)} cy={y(d.v)} r={hover===i?5:3} fill="#fff" stroke={color} strokeWidth="2.2" className="chart-dot" />
            <text x={x(i)} y={H-7} textAnchor="middle" fontSize="11" fontWeight="500" fill="var(--muted)" fontFamily="Geist, sans-serif">{d.m}</text>
          </g>
        ))}
        {hover!==null && (
          <g>
            <line x1={x(hover)} x2={x(hover)} y1={padTop} y2={padTop+innerH} stroke={color} strokeWidth="1" strokeOpacity=".3" />
          </g>
        )}
      </svg>
      {hover!==null && (
        <div style={{ position:'absolute', left:`${(x(hover)/W)*100}%`, top:-4,
          transform:'translateX(-50%)', background:'var(--navy-deep)', color:'var(--cream)', fontSize:11.5, fontWeight:600,
          padding:'5px 9px', borderRadius:7, pointerEvents:'none', whiteSpace:'nowrap', boxShadow:'var(--shadow-pop)' }}>
          {data[hover].m} · {fm(data[hover].v)}
        </div>
      )}
    </div>
  );
}

/* ---- Donut (lead status distribution) ---- */
function Donut({ segments, size = 132, unit = 'leads' }) {
  const [hover, setHover] = useStateC(null);
  const total = segments.reduce((s,d)=>s+d.value,0) || 1;
  const r = size/2 - 12, cx = size/2, cy = size/2, C = 2*Math.PI*r, sw = 16;
  let acc = 0;
  return (
    <div style={{ display:'flex', alignItems:'center', gap:20, flexWrap:'wrap' }}>
      <div style={{ position:'relative', width:size, height:size, flexShrink:0 }}>
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform:'rotate(-90deg)' }}>
          <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--bg)" strokeWidth={sw} />
          {segments.map((s,i)=>{
            const frac = s.value/total;
            const dash = frac*C;
            const seg = (
              <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={s.color} strokeWidth={hover===i?sw+3:sw}
                strokeDasharray={`${dash} ${C-dash}`} strokeDashoffset={-acc} strokeLinecap="butt"
                className="donut-seg" onMouseEnter={()=>setHover(i)} onMouseLeave={()=>setHover(null)} />
            );
            acc += dash;
            return seg;
          })}
        </svg>
        <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center' }}>
          <span className="tnum" style={{ fontSize:24, fontWeight:700, color:'var(--ink)' }}>{hover!==null?segments[hover].value:total}</span>
          <span style={{ fontSize:10.5, color:'var(--muted)', fontWeight:500 }}>{hover!==null?segments[hover].label:unit}</span>
        </div>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:8, flex:1, minWidth:130 }}>
        {segments.map((s,i)=>(
          <div key={i} onMouseEnter={()=>setHover(i)} onMouseLeave={()=>setHover(null)}
            style={{ display:'flex', alignItems:'center', gap:9, fontSize:13, cursor:'default', opacity: hover===null||hover===i?1:.5, transition:'.12s' }}>
            <span style={{ width:9, height:9, borderRadius:3, background:s.color, flexShrink:0 }} />
            <span style={{ color:'var(--ink-2)', flex:1 }}>{s.label}</span>
            <span className="tnum" style={{ color:'var(--ink)', fontWeight:600 }}>{s.value}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { AreaChart, Donut });
