/* ============================================================
   charts.jsx — LineChart (positions over time) + StackedBar
   Exposes: LineChart, StackedBar, BigSpark
   ============================================================ */

// Positions line chart. Lower position = better, so Y is inverted.
function LineChart({ series = [], updates = [], height = 220, yLabel = "Позиция", invert = true, maxY }) {
  const ref = React.useRef(null);
  const [w, setW] = React.useState(720);
  const [hover, setHover] = React.useState(null);
  React.useEffect(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver(e => setW(e[0].contentRect.width));
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);

  const padL = 38, padR = 16, padT = 16, padB = 26;
  const allVals = series.flatMap(s => s.data);
  const dataMax = maxY || Math.max(...allVals);
  const lo = 1, hi = Math.ceil(dataMax / 5) * 5;
  const n = series[0]?.data.length || 1;
  const innerW = w - padL - padR, innerH = height - padT - padB;
  const x = i => padL + (i / (n - 1)) * innerW;
  const y = v => {
    const t = (v - lo) / (hi - lo);
    return padT + (invert ? t : (1 - t)) * innerH;
  };
  const ticks = [lo, Math.round(hi*0.25), Math.round(hi*0.5), Math.round(hi*0.75), hi];

  return (
    <div ref={ref} style={{ width: "100%", position: "relative" }}
      onMouseLeave={() => setHover(null)}
      onMouseMove={e => {
        const rect = ref.current.getBoundingClientRect();
        const mx = e.clientX - rect.left;
        const i = Math.round(((mx - padL) / innerW) * (n - 1));
        if (i >= 0 && i < n) setHover(i); else setHover(null);
      }}>
      <svg width={w} height={height} style={{ display: "block" }}>
        {ticks.map((t, i) => (
          <g key={i}>
            <line x1={padL} x2={w - padR} y1={y(t)} y2={y(t)} stroke="var(--border)" strokeWidth="1" />
            <text x={padL - 8} y={y(t) + 4} textAnchor="end" fontSize="10.5" fontWeight="600" fill="var(--ink-4)">{t}</text>
          </g>
        ))}
        {updates.map((u, i) => (
          <g key={"u" + i}>
            <line x1={x(u.day)} x2={x(u.day)} y1={padT} y2={height - padB} stroke="var(--ink-4)" strokeWidth="1" strokeDasharray="3 3" opacity="0.6" />
            <text x={x(u.day)} y={padT + 2} fontSize="9.5" fontWeight="700" fill="var(--ink-4)" textAnchor="middle" transform={`rotate(0)`}>⌁</text>
          </g>
        ))}
        {series.map((s, si) => {
          const line = s.data.map((v, i) => `${i ? "L" : "M"}${x(i).toFixed(1)} ${y(v).toFixed(1)}`).join(" ");
          return <path key={si} d={line} fill="none" stroke={s.color} strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" />;
        })}
        {hover != null && (
          <line x1={x(hover)} x2={x(hover)} y1={padT} y2={height - padB} stroke="var(--ink-3)" strokeWidth="1" />
        )}
        {hover != null && series.map((s, si) => (
          <circle key={si} cx={x(hover)} cy={y(s.data[hover])} r="4" fill="var(--surface)" stroke={s.color} strokeWidth="2.5" />
        ))}
      </svg>
      {hover != null && (
        <div style={{ position: "absolute", left: Math.min(Math.max(x(hover) - 60, 4), w - 130), top: 6, background: "var(--ink)", color: "#fff", borderRadius: 9, padding: "8px 11px", fontSize: 12, boxShadow: "var(--sh-3)", pointerEvents: "none", minWidth: 110 }}>
          <div style={{ fontSize: 10.5, opacity: .7, marginBottom: 4, fontWeight: 700 }}>День {hover + 1}</div>
          {series.map((s, si) => (
            <div key={si} style={{ display: "flex", alignItems: "center", gap: 6, fontWeight: 700 }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: s.color }} />
              {s.name}: <span className="tnum">{s.data[hover]}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// Stacked horizontal bar — distribution of keys by top buckets
function StackedBar({ segments, height = 14 }) {
  const total = segments.reduce((a, s) => a + s.value, 0) || 1;
  return (
    <div style={{ display: "flex", width: "100%", height, borderRadius: 999, overflow: "hidden", gap: 2 }}>
      {segments.map((s, i) => (
        <div key={i} title={`${s.label}: ${s.value}`} style={{ width: `${(s.value / total) * 100}%`, background: s.color, borderRadius: 3 }} />
      ))}
    </div>
  );
}

Object.assign(window, { LineChart, StackedBar });
