// charts.jsx — interactive SVG charts (bar / line / donut). Exported to window.
const { useState } = React;

// ── Bar chart ────────────────────────────────────────────────
function BarChart({ data, unit = '', height = 230 }) {
  const [hover, setHover] = useState(null);
  const W = 520, H = height, padL = 36, padB = 40, padT = 14;
  if (!data || !data.length) return <div style={{height, display:'flex', alignItems:'center', justifyContent:'center', color:'var(--text-3)', fontSize:13}}>Zatím bez dat</div>;
  const max = Math.max(0, ...data.map(d => d.value));
  const niceMax = Math.ceil(max / 4) * 4 || 4;
  const innerW = W - padL - 12, innerH = H - padB - padT;
  const bw = innerW / data.length;
  const barW = Math.min(64, bw * 0.56);
  const ticks = [0, niceMax/4, niceMax/2, niceMax*3/4, niceMax];
  return (
    <div style={{ position:'relative' }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display:'block', overflow:'visible' }}>
        {ticks.map((t,i) => {
          const y = padT + innerH - (t/niceMax)*innerH;
          return <g key={i}>
            <line x1={padL} y1={y} x2={W-12} y2={y} stroke="var(--border)" strokeWidth="1"/>
            <text x={padL-8} y={y+4} textAnchor="end" fontSize="11" fill="var(--text-3)">{t}</text>
          </g>;
        })}
        {data.map((d,i) => {
          const x = padL + bw*i + (bw-barW)/2;
          const h = (d.value/niceMax)*innerH;
          const y = padT + innerH - h;
          const on = hover === i;
          return <g key={i} onMouseEnter={()=>setHover(i)} onMouseLeave={()=>setHover(null)} style={{cursor:'default'}}>
            <rect x={padL+bw*i} y={padT} width={bw} height={innerH} fill="transparent"/>
            <rect x={x} y={y} width={barW} height={h} rx="5" fill={d.color} opacity={hover===null||on?1:.45} style={{transition:'opacity .15s'}}/>
            <text x={x+barW/2} y={H-padB+18} textAnchor="middle" fontSize="12" fontWeight="600" fill="var(--text-2)">{d.label}</text>
          </g>;
        })}
      </svg>
      {hover!==null && (() => {
        const x = padL + bw*hover + bw/2;
        const h = (data[hover].value/niceMax)*innerH;
        const y = padT + innerH - h;
        return <div className="tooltip show" style={{ left:`${x/W*100}%`, top:`${y/H*100}%` }}>
          {data[hover].label}: {data[hover].value}{unit}
        </div>;
      })()}
    </div>
  );
}

// ── Line chart ───────────────────────────────────────────────
function LineChart({ data, unit='%', height=230 }) {
  const [hover, setHover] = useState(null);
  const W = 520, H = height, padL = 38, padB = 32, padT = 16, padR = 14;
  const innerW = W-padL-padR, innerH = H-padB-padT;
  const max = 100, min = 0;
  const px = i => padL + (innerW/(data.length-1))*i;
  const py = v => padT + innerH - ((v-min)/(max-min))*innerH;
  const pts = data.map((d,i)=>[px(i),py(d.v)]);
  const line = pts.map((p,i)=>(i?'L':'M')+p[0]+' '+p[1]).join(' ');
  const area = line + ` L ${px(data.length-1)} ${padT+innerH} L ${padL} ${padT+innerH} Z`;
  const ticks=[0,25,50,75,100];
  return (
    <div style={{position:'relative'}}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{display:'block', overflow:'visible'}}
        onMouseLeave={()=>setHover(null)}>
        <defs>
          <linearGradient id="lg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--brand)" stopOpacity=".22"/>
            <stop offset="100%" stopColor="var(--brand)" stopOpacity="0"/>
          </linearGradient>
        </defs>
        {ticks.map((t,i)=>{const y=py(t);return <g key={i}>
          <line x1={padL} y1={y} x2={W-padR} y2={y} stroke="var(--border)" strokeWidth="1"/>
          <text x={padL-8} y={y+4} textAnchor="end" fontSize="11" fill="var(--text-3)">{t}</text>
        </g>;})}
        <path d={area} fill="url(#lg)"/>
        <path d={line} fill="none" stroke="var(--brand)" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/>
        {data.map((d,i)=>(
          <g key={i} onMouseEnter={()=>setHover(i)} style={{cursor:'default'}}>
            <rect x={px(i)-innerW/(data.length-1)/2} y={padT} width={innerW/(data.length-1)} height={innerH} fill="transparent"/>
            <circle cx={px(i)} cy={py(d.v)} r={hover===i?6:4.5} fill="var(--surface)" stroke="var(--brand)" strokeWidth="2.6" style={{transition:'r .12s'}}/>
            <text x={px(i)} y={H-padB+18} textAnchor="middle" fontSize="12" fontWeight="600" fill="var(--text-2)">{d.m}</text>
          </g>
        ))}
      </svg>
      {hover!==null && <div className="tooltip show" style={{left:`${px(hover)/W*100}%`, top:`${py(data[hover].v)/H*100}%`}}>{data[hover].m}: {data[hover].v}{unit}</div>}
    </div>
  );
}

// ── Donut chart ──────────────────────────────────────────────
function DonutChart({ data, size=190, thickness=30 }) {
  const [hover, setHover] = useState(null);
  const total = data.reduce((a,d)=>a+d.value,0);
  const r = size/2, ir = r-thickness, cx=r, cy=r;
  let acc = -Math.PI/2;
  const arc = (start,end,radius)=>{
    const x1=cx+radius*Math.cos(start), y1=cy+radius*Math.sin(start);
    const x2=cx+radius*Math.cos(end), y2=cy+radius*Math.sin(end);
    const large = end-start>Math.PI?1:0;
    return {x1,y1,x2,y2,large};
  };
  const segs = data.map((d,i)=>{
    const ang = (d.value/total)*Math.PI*2;
    const start=acc, end=acc+ang; acc=end;
    const o=arc(start,end,r), inr=arc(end,start,ir);
    const path=`M ${o.x1} ${o.y1} A ${r} ${r} 0 ${o.large} 1 ${o.x2} ${o.y2} L ${inr.x1} ${inr.y1} A ${ir} ${ir} 0 ${o.large} 0 ${inr.x2} ${inr.y2} Z`;
    return { ...d, path, i };
  });
  return (
    <div style={{display:'flex', alignItems:'center', gap:24, flexWrap:'wrap'}}>
      <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size} style={{flexShrink:0}}>
        {segs.map(s=>(
          <path key={s.i} d={s.path} fill={s.color} opacity={hover===null||hover===s.i?1:.4}
            style={{transition:'opacity .15s', cursor:'default'}}
            onMouseEnter={()=>setHover(s.i)} onMouseLeave={()=>setHover(null)}/>
        ))}
        <text x={cx} y={cy-4} textAnchor="middle" fontSize="26" fontWeight="800" fill="var(--text)">
          {hover===null? data[0].value : data[hover].value}%
        </text>
        <text x={cx} y={cy+15} textAnchor="middle" fontSize="10.5" fill="var(--text-3)">
          {hover===null? 'nejčastější' : 'vybráno'}
        </text>
      </svg>
      <div className="legend" style={{flex:1, minWidth:180}}>
        {data.map((d,i)=>(
          <div className="lrow" key={i} onMouseEnter={()=>setHover(i)} onMouseLeave={()=>setHover(null)}
            style={{opacity:hover===null||hover===i?1:.5, transition:'opacity .15s'}}>
            <span className="ldot" style={{background:d.color}}/>
            <span style={{color:'var(--text-2)'}}>{d.label}</span>
            <span className="lval">{d.value}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { BarChart, LineChart, DonutChart });
