/* ===== Charts — hand-built SVG ===== */
const { useState: useStateC, useRef: useRefC, useEffect: useEffectC } = React;

function smoothPath(pts) {
  if (pts.length < 2) return "";
  let d = `M ${pts[0][0]} ${pts[0][1]}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const [x0, y0] = pts[i], [x1, y1] = pts[i + 1];
    const cx = (x0 + x1) / 2;
    d += ` C ${cx} ${y0} ${cx} ${y1} ${x1} ${y1}`;
  }
  return d;
}

// Cash flow: stacked area + lines for income & expense
function CashFlowChart({ data, eur0 }) {
  const [hover, setHover] = useStateC(null);
  const W = 720, H = 260, padL = 8, padR = 8, padT = 16, padB = 28;
  const iw = W - padL - padR, ih = H - padT - padB;
  const max = Math.max(...data.map(d => Math.max(d.income, d.expense))) * 1.12;
  const x = (i) => padL + (i / (data.length - 1)) * iw;
  const y = (v) => padT + ih - (v / max) * ih;
  const incPts = data.map((d, i) => [x(i), y(d.income)]);
  const expPts = data.map((d, i) => [x(i), y(d.expense)]);
  const incLine = smoothPath(incPts);
  const expLine = smoothPath(expPts);
  const incArea = incLine + ` L ${x(data.length-1)} ${padT+ih} L ${x(0)} ${padT+ih} Z`;

  return (
    <div style={{ position:"relative" }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display:"block", overflow:"visible" }}
        onMouseLeave={() => setHover(null)}>
        <defs>
          <linearGradient id="incGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.22"/>
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
          </linearGradient>
        </defs>
        {[0.25,0.5,0.75,1].map((g,i) => (
          <line key={i} x1={padL} x2={W-padR} y1={padT+ih*(1-g)} y2={padT+ih*(1-g)}
            stroke="var(--line-2)" strokeWidth="1" strokeDasharray="2 5"/>
        ))}
        <path d={incArea} fill="url(#incGrad)"/>
        <path d={expLine} fill="none" stroke="var(--text-3)" strokeWidth="2" strokeDasharray="4 4" opacity="0.6"/>
        <path d={incLine} fill="none" stroke="var(--accent)" strokeWidth="2.6"/>
        {data.map((d,i) => (
          <g key={i}>
            {hover===i && <line x1={x(i)} x2={x(i)} y1={padT} y2={padT+ih} stroke="var(--line)" strokeWidth="1.5"/>}
            {hover===i && <circle cx={x(i)} cy={y(d.income)} r="4.5" fill="var(--accent)" stroke="var(--surface)" strokeWidth="2.5"/>}
            <rect x={x(i)-(iw/data.length/2)} y={padT} width={iw/data.length} height={ih} fill="transparent"
              onMouseEnter={() => setHover(i)}/>
            <text x={x(i)} y={H-8} textAnchor="middle" fontSize="11" fill="var(--text-3)" fontFamily="var(--font-ui)">{d.m}</text>
          </g>
        ))}
      </svg>
      {hover!==null && (
        <div style={{ position:"absolute", top:6, left:`clamp(8px, ${(x(hover)/W)*100}% - 70px, calc(100% - 150px))`,
          background:"var(--navy)", color:"#fff", borderRadius:10, padding:"9px 12px", fontSize:12, pointerEvents:"none",
          boxShadow:"var(--shadow)", minWidth:130 }}>
          <div style={{ fontWeight:600, marginBottom:5, color:"var(--on-navy)" }}>{data[hover].m} 2026</div>
          <div style={{ display:"flex", justifyContent:"space-between", gap:14 }}>
            <span style={{ color:"var(--on-navy-2)" }}>Income</span><span className="mono">{eur0(data[hover].income)}</span></div>
          <div style={{ display:"flex", justifyContent:"space-between", gap:14 }}>
            <span style={{ color:"var(--on-navy-2)" }}>Expense</span><span className="mono">{eur0(data[hover].expense)}</span></div>
          <div style={{ display:"flex", justifyContent:"space-between", gap:14, marginTop:3, paddingTop:5, borderTop:"1px solid rgba(255,255,255,.15)" }}>
            <span style={{ color:"var(--on-navy-2)" }}>Net</span><span className="mono" style={{ color:"var(--pos)" }}>{eur0(data[hover].net)}</span></div>
        </div>
      )}
    </div>
  );
}

// Donut for expense breakdown
function DonutChart({ data, eur0, size }) {
  const [hover, setHover] = useStateC(null);
  const S = size || 168, r = S/2 - 14, cx = S/2, cy = S/2, sw = 22;
  const total = data.reduce((s,d) => s+d.value, 0);
  const C = 2*Math.PI*r;
  let acc = 0;
  const segs = data.map(d => {
    const frac = d.value/total;
    const seg = { ...d, frac, off: acc, len: frac*C };
    acc += frac;
    return seg;
  });
  const active = hover!=null ? segs[hover] : null;
  return (
    <div style={{ display:"flex", alignItems:"center", gap:22, flexWrap:"wrap" }}>
      <svg width={S} height={S} viewBox={`0 0 ${S} ${S}`} style={{ flex:"0 0 auto" }}>
        <g transform={`rotate(-90 ${cx} ${cy})`}>
          {segs.map((s,i) => (
            <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={s.color}
              strokeWidth={hover===i ? sw+4 : sw} strokeDasharray={`${s.len} ${C-s.len}`}
              strokeDashoffset={-s.off*C} strokeLinecap="butt"
              style={{ transition:"stroke-width .18s ease", cursor:"pointer", opacity: hover==null||hover===i?1:0.45 }}
              onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}/>
          ))}
        </g>
        <text x={cx} y={cy-4} textAnchor="middle" fontSize="11" fill="var(--text-3)" fontFamily="var(--font-ui)">
          {active ? active.name : "Total"}</text>
        <text x={cx} y={cy+15} textAnchor="middle" fontSize="18" fontWeight="600" fill="var(--text)" fontFamily="var(--font-ui)" className="mono">
          {eur0(active ? active.value : total)}</text>
      </svg>
      <div style={{ flex:1, minWidth:160, display:"flex", flexDirection:"column", gap:9 }}>
        {segs.map((s,i) => (
          <div key={i} style={{ display:"flex", alignItems:"center", gap:9, cursor:"pointer", opacity: hover==null||hover===i?1:0.5 }}
            onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
            <span style={{ width:9, height:9, borderRadius:3, background:s.color, flex:"0 0 auto" }}></span>
            <span style={{ fontSize:13, flex:1, color:"var(--text-2)" }}>{s.name}</span>
            <span className="mono" style={{ fontSize:12.5, fontWeight:600 }}>{Math.round(s.frac*100)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// Sparkline
function Spark({ data, color, w, h }) {
  const W = w||72, H = h||28, max = Math.max(...data), min = Math.min(...data);
  const rng = max-min || 1;
  const pts = data.map((v,i) => [ (i/(data.length-1))*W, H - ((v-min)/rng)*(H-4) - 2 ]);
  const d = smoothPath(pts);
  const area = d + ` L ${W} ${H} L 0 ${H} Z`;
  const gid = "sg"+Math.round((color||"").length*data.length*data[0]);
  return (
    <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} style={{ overflow:"visible" }}>
      <defs><linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor={color||"var(--accent)"} stopOpacity="0.18"/>
        <stop offset="100%" stopColor={color||"var(--accent)"} stopOpacity="0"/>
      </linearGradient></defs>
      <path d={area} fill={`url(#${gid})`}/>
      <path d={d} fill="none" stroke={color||"var(--accent)"} strokeWidth="2" strokeLinecap="round"/>
    </svg>
  );
}

window.CashFlowChart = CashFlowChart;
window.DonutChart = DonutChart;
window.Spark = Spark;
