/* Hero: Parliament hemicycle — 151 seats */
function ParliamentChart() {
  const P = window.DASH.parliament;
  const [ref, seen] = window.useInView({ threshold: 0.2 });
  const [hover, setHover] = useState(null);

  const W = 780, H = 430, cx = W / 2, cy = 392;
  const innerR = 132, outerR = 366, rows = 6;

  const seats = useMemo(() => {
    const radii = [];
    for (let i = 0; i < rows; i++) radii.push(innerR + (outerR - innerR) * (i / (rows - 1)));
    const sum = radii.reduce((a, b) => a + b, 0);
    let counts = radii.map(r => Math.round(P.total * r / sum));
    let diff = P.total - counts.reduce((a, b) => a + b, 0);
    let k = counts.length - 1;
    while (diff !== 0) { counts[k] += diff > 0 ? 1 : -1; diff += diff > 0 ? -1 : 1; k = (k - 1 + counts.length) % counts.length; }

    const pts = [];
    radii.forEach((R, ri) => {
      const n = counts[ri];
      for (let j = 0; j < n; j++) {
        const theta = Math.PI * (1 - (j + 0.5) / n);
        pts.push({ x: cx + R * Math.cos(theta), y: cy - R * Math.sin(theta), theta, ri });
      }
    });
    pts.sort((a, b) => b.theta - a.theta || a.ri - b.ri);

    // assign parties by cumulative blocks
    let idx = 0;
    P.groups.forEach(g => {
      for (let s = 0; s < g.seats; s++) { if (pts[idx]) { pts[idx].g = g; } idx++; }
    });
    return pts;
  }, []);

  const dot = 9.2;

  return (
    <div ref={ref}>
      <div className="parl-top">
        <div className="parl-side">
          <div className="parl-side-lab" style={{ color: "var(--c-labor)" }}>Governing</div>
          <div className="parl-side-name">Australian Labor Party</div>
          <div className="parl-side-seats" style={{ color: "var(--c-labor)" }}>77 <span>seats</span></div>
        </div>
        <div className="parl-side right">
          <div className="parl-side-lab" style={{ color: "var(--c-coalition)" }}>Opposition Coalition</div>
          <div className="parl-side-name">Liberal&nbsp;·&nbsp;Nationals</div>
          <div className="parl-side-seats" style={{ color: "var(--c-coalition)" }}>54 <span>seats</span></div>
        </div>
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", display: "block" }}
           onMouseLeave={() => { setHover(null); window.Tip.hide(); }}>
        {/* majority arc marker */}
        {seats.map((s, i) => (
          <circle key={i} cx={s.x} cy={s.y} r={dot}
            fill={s.g ? s.g.color : "var(--c-vacant)"}
            className="seat"
            style={{
              transition: "opacity .45s ease, transform .45s cubic-bezier(.34,1.56,.64,1)",
              transitionDelay: (i * 3) + "ms",
              transformBox: "fill-box", transformOrigin: "center",
              opacity: seen ? (hover && hover !== s.g?.id ? .28 : 1) : 0,
              transform: seen ? "scale(1)" : "scale(.2)",
              cursor: "default",
            }}
            onMouseEnter={(e) => {
              if (!s.g) return;
              setHover(s.g.id);
              window.Tip.show(e.clientX, e.clientY,
                `<div class="tip-t">${s.g.label}</div>${window.tipRows([{ k: "Seats", v: s.g.seats, sw: s.g.color }, { k: "Share", v: (s.g.seats / P.total * 100).toFixed(1) + "%" }])}`);
            }}
            onMouseMove={(e) => window.Tip.move(e.clientX, e.clientY)}
          />
        ))}
        {/* center total */}
        <text x={cx} y={cy - 38} textAnchor="middle" style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 52, fill: "var(--ink)" }}>{P.total}</text>
        <text x={cx} y={cy - 14} textAnchor="middle" className="axis-label" style={{ letterSpacing: ".18em", textTransform: "uppercase" }}>seats · 76 for majority</text>
      </svg>

      <div className="legend" style={{ marginTop: 4, justifyContent: "center", gap: "8px 16px" }}>
        {P.groups.map(g => (
          <span className="legend-item" key={g.id}
            style={{ opacity: hover && hover !== g.id ? .4 : 1, transition: "opacity .2s" }}
            onMouseEnter={() => setHover(g.id)} onMouseLeave={() => setHover(null)}>
            <i className="legend-swatch" style={{ background: g.color }} />
            {g.label} <b>{g.seats}</b>
          </span>
        ))}
      </div>
    </div>
  );
}
window.ParliamentChart = ParliamentChart;
