// Weekly performance chart — animated SVG area + bars.
const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

function PerfChart({ data, mode="earnings" }){
  const [hover, setHover] = useStateC(null);
  const ref = useRefC(null);
  const W = 720, H = 260, PAD = { l: 48, r: 20, t: 20, b: 34 };
  const innerW = W - PAD.l - PAD.r;
  const innerH = H - PAD.t - PAD.b;

  const values = data.map(d => mode === "earnings" ? d.earnings : d.sales);
  const max = Math.max(...values) * 1.15;
  const min = 0;
  const stepX = innerW / (data.length - 1);

  const points = values.map((v,i) => [PAD.l + i*stepX, PAD.t + innerH - (v/(max-min)) * innerH]);
  const line = points.map((p,i) => (i===0?"M":"L") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  const area = line + ` L ${PAD.l + innerW} ${PAD.t + innerH} L ${PAD.l} ${PAD.t + innerH} Z`;

  // y grid lines
  const yTicks = 4;
  const gridY = Array.from({length: yTicks+1}, (_,i) => PAD.t + (innerH/yTicks)*i);
  const yLabels = Array.from({length: yTicks+1}, (_,i) => {
    const val = max - (max/yTicks)*i;
    return mode === "earnings" ? "€"+Math.round(val) : Math.round(val);
  });

  // animated draw
  const pathRef = useRefC(null);
  useEffectC(() => {
    const p = pathRef.current; if(!p) return;
    const len = p.getTotalLength();
    p.style.strokeDasharray = len;
    p.style.strokeDashoffset = len;
    p.getBoundingClientRect();
    p.style.transition = "stroke-dashoffset 1.4s cubic-bezier(.2,.8,.2,1)";
    p.style.strokeDashoffset = 0;
  }, [mode]);

  const handleMove = (e) => {
    const svg = ref.current; if(!svg) return;
    const pt = svg.createSVGPoint();
    pt.x = e.clientX; pt.y = e.clientY;
    const cursor = pt.matrixTransform(svg.getScreenCTM().inverse());
    const idx = Math.max(0, Math.min(data.length - 1, Math.round((cursor.x - PAD.l) / stepX)));
    setHover(idx);
  };

  return (
    <svg ref={ref} viewBox={`0 0 ${W} ${H}`} style={{width:"100%",height:"100%",display:"block"}}
         onMouseMove={handleMove} onMouseLeave={() => setHover(null)}>
      <defs>
        <linearGradient id="chartArea" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#5B8CFF" stopOpacity="0.35"/>
          <stop offset="60%" stopColor="#5B8CFF" stopOpacity="0.05"/>
          <stop offset="100%" stopColor="#5B8CFF" stopOpacity="0"/>
        </linearGradient>
        <linearGradient id="chartLine" x1="0" x2="1">
          <stop offset="0%" stopColor="#5B8CFF"/>
          <stop offset="100%" stopColor="#8A5BFF"/>
        </linearGradient>
        <filter id="chartGlow" x="-20%" y="-20%" width="140%" height="140%">
          <feGaussianBlur stdDeviation="4" result="b"/>
          <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
      </defs>

      {/* grid */}
      {gridY.map((y,i) => (
        <g key={i}>
          <line x1={PAD.l} x2={W-PAD.r} y1={y} y2={y} stroke="rgba(255,255,255,0.04)" strokeDasharray="2 4"/>
          <text x={PAD.l - 10} y={y+3} textAnchor="end" fontSize="10" fontFamily="JetBrains Mono" fill="var(--dim)">{yLabels[i]}</text>
        </g>
      ))}

      {/* area */}
      <path d={area} fill="url(#chartArea)"/>

      {/* line */}
      <path ref={pathRef} d={line} fill="none" stroke="url(#chartLine)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" filter="url(#chartGlow)"/>

      {/* points */}
      {points.map((p,i) => (
        <g key={i}>
          <circle cx={p[0]} cy={p[1]} r={hover===i?5:3} fill="#0B0F1A" stroke="#5B8CFF" strokeWidth="1.6"
                  style={{transition:"r .15s"}}/>
          {hover===i && <circle cx={p[0]} cy={p[1]} r="10" fill="#5B8CFF" opacity="0.15"/>}
        </g>
      ))}

      {/* x labels */}
      {data.map((d,i) => (
        <text key={i} x={PAD.l + i*stepX} y={H-12} textAnchor="middle" fontSize="10" fontFamily="JetBrains Mono" fill="var(--dim)">{d.w}</text>
      ))}

      {/* hover line + tooltip */}
      {hover !== null && (
        <g>
          <line x1={points[hover][0]} x2={points[hover][0]} y1={PAD.t} y2={H-PAD.b} stroke="rgba(91,140,255,0.3)" strokeDasharray="3 3"/>
          <g transform={`translate(${Math.min(points[hover][0] + 12, W - PAD.r - 110)} ${Math.max(points[hover][1] - 40, PAD.t)})`}>
            <rect width="110" height="44" rx="8" fill="rgba(15,20,35,0.95)" stroke="rgba(91,140,255,0.4)"/>
            <text x="10" y="16" fontSize="10" fontFamily="JetBrains Mono" fill="var(--sub)" letterSpacing="0.08em">{data[hover].w}</text>
            <text x="10" y="34" fontSize="14" fontFamily="Sora" fontWeight="700" fill="#E6EAF2">
              {mode==="earnings" ? `€${data[hover].earnings}` : `${data[hover].sales} sales`}
            </text>
          </g>
        </g>
      )}
    </svg>
  );
}

window.PerfChart = PerfChart;
