// LineChart — income vs expenses over time.
// series: [{ name, color, data: [{ x, y }] }]
function LineChart({ series, labels, height = 260 }) {
  const ref = React.useRef(null);
  const { w } = useSize(ref);
  const padL = 48, padR = 16, padT = 16, padB = 30;
  const innerW = Math.max(100, w - padL - padR);
  const innerH = height - padT - padB;
  const [hover, setHover] = React.useState(null);

  const allVals = series.flatMap(s => s.data.map(d => d.y));
  const max = Math.max(...allVals, 1);
  const niceMax = Math.ceil(max / 1000) * 1000;
  const n = labels.length;

  const xOf = i => padL + (innerW / (n - 1)) * i;
  const yOf = v => padT + innerH - (v / niceMax) * innerH;

  const ticks = 4;
  const tickVals = Array.from({ length: ticks + 1 }, (_, i) => (niceMax / ticks) * i);

  return (
    <div ref={ref} style={{ width: '100%', height, position: 'relative' }}
         onMouseLeave={() => setHover(null)}>
      <svg width="100%" height={height} style={{ display: 'block' }}
           onMouseMove={e => {
             const rect = e.currentTarget.getBoundingClientRect();
             const x = e.clientX - rect.left;
             const i = Math.round(((x - padL) / innerW) * (n - 1));
             if (i >= 0 && i < n) setHover(i);
           }}>
        {/* gridlines */}
        {tickVals.map((v, i) => {
          const y = yOf(v);
          return (
            <g key={i}>
              <line x1={padL} x2={w - padR} y1={y} y2={y} stroke="var(--border)" strokeWidth="1"/>
              <text x={padL - 8} y={y + 3} fontSize="10" fill="var(--text-tertiary)" textAnchor="end">
                {fmt$(v, { compact: true })}
              </text>
            </g>
          );
        })}
        {/* x labels */}
        {labels.map((l, i) => (
          <text key={i} x={xOf(i)} y={padT + innerH + 16} fontSize="10.5" fill="var(--text-tertiary)" textAnchor="middle">{l}</text>
        ))}

        {/* area fills */}
        {series.map((s, si) => {
          const d = s.data.map((p, i) => `${i === 0 ? 'M' : 'L'} ${xOf(i)} ${yOf(p.y)}`).join(' ');
          const areaD = d + ` L ${xOf(n - 1)} ${yOf(0)} L ${xOf(0)} ${yOf(0)} Z`;
          return (
            <g key={si}>
              <path d={areaD} fill={s.color} opacity="0.08"/>
              <path d={d} fill="none" stroke={s.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              {s.data.map((p, i) => (
                <circle key={i} cx={xOf(i)} cy={yOf(p.y)} r={hover === i ? 4 : 2.5}
                        fill={hover === i ? s.color : 'var(--bg-elev)'}
                        stroke={s.color} strokeWidth="1.5"/>
              ))}
            </g>
          );
        })}

        {/* hover line */}
        {hover != null && (
          <line x1={xOf(hover)} x2={xOf(hover)} y1={padT} y2={padT + innerH} stroke="var(--border-strong)" strokeWidth="1" strokeDasharray="2 2"/>
        )}
      </svg>

      {hover != null && (
        <div style={{
          position: 'absolute',
          left: Math.min(xOf(hover) + 8, w - 160),
          top: 8,
          background: 'var(--bg-elev)',
          border: '1px solid var(--border)',
          borderRadius: 8,
          padding: '8px 12px',
          boxShadow: 'var(--shadow)',
          fontSize: 12,
          pointerEvents: 'none',
          minWidth: 130,
        }}>
          <div style={{ fontWeight: 600, marginBottom: 6 }}>{labels[hover]}</div>
          {series.map((s, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: s.color }}/>
              <span style={{ flex: 1, color: 'var(--text-secondary)' }}>{s.name}</span>
              <span style={{ fontVariantNumeric: 'tabular-nums' }}>{fmt$(s.data[hover].y, { compact: true })}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { LineChart });
