const { useState: useStateP, useMemo: useMemoP, useRef: useRefP } = React;

function PollingSection({ lang = "en" }) {
  const data = window.POLLING_DATA;
  const t = (en, fr) => (lang === "fr" ? fr : en);
  const [mode, setMode] = useStateP("parties"); // 'parties' | 'approval'
  const [hoverIdx, setHoverIdx] = useStateP(null);

  return (
    <section className="polling wrap">
      <div className="polling-head">
        <div>
          <div className="polling-eyebrow">{t("Public Support · Rolling aggregate", "Appui public · Moyenne mobile")}</div>
          <h2 className="polling-title">
            {mode === "parties"
              ? t(<>Federal vote intention since the <em>2025 election</em>.</>, <>Intentions de vote depuis les <em>élections de 2025</em>.</>)
              : t(<>Carney approval, <em>Angus Reid</em>.</>, <>Approbation de Carney, <em>Angus Reid</em>.</>)}
          </h2>
        </div>
        <div className="polling-toggle" role="tablist">
          <button className={`polling-toggle-btn ${mode === "parties" ? "active" : ""}`} onClick={() => setMode("parties")}>
            {t("Vote share", "Intentions de vote")}
          </button>
          <button className={`polling-toggle-btn ${mode === "approval" ? "active" : ""}`} onClick={() => setMode("approval")}>
            {t("Carney approval", "Approbation Carney")}
          </button>
        </div>
      </div>

      {mode === "parties"
        ? <PartiesChart data={data} hoverIdx={hoverIdx} setHoverIdx={setHoverIdx} />
        : <ApprovalChart data={data.approval} hoverIdx={hoverIdx} setHoverIdx={setHoverIdx} lang={lang} />}

      <div className="polling-foot">
        <span>{data.meta.note}</span>
      </div>
    </section>
  );
}

/* ──────────────────────────────────────────────────────────
   Shared chart geometry
   ────────────────────────────────────────────────────────── */
const W = 1180, H = 320, PL = 44, PR = 56, PT = 24, PB = 36;
const innerW = W - PL - PR;
const innerH = H - PT - PB;

function ticksY(min, max, step) {
  const ticks = [];
  for (let v = min; v <= max + 0.0001; v += step) ticks.push(v);
  return ticks;
}
function fmtMonth(d) {
  const [y, m] = d.split("-");
  return new Date(Number(y), Number(m) - 1, 1)
    .toLocaleDateString("en-CA", { month: "short" }) + (m === "01" ? ` ${y.slice(2)}` : "");
}

/* ──────────────────────────────────────────────────────────
   Parties chart — multi-line with hover crosshair
   ────────────────────────────────────────────────────────── */
function PartiesChart({ data, hoverIdx, setHoverIdx }) {
  const svgRef = useRefP(null);
  const yMin = 0, yMax = 50;
  const yTicks = ticksY(yMin, yMax, 10);
  const N = data.series.length;
  const x = (i) => PL + (i / (N - 1)) * innerW;
  const y = (v) => PT + innerH - ((v - yMin) / (yMax - yMin)) * innerH;

  const handleMove = (e) => {
    const rect = svgRef.current.getBoundingClientRect();
    const px = ((e.clientX - rect.left) / rect.width) * W;
    const i = Math.round(((px - PL) / innerW) * (N - 1));
    setHoverIdx(Math.max(0, Math.min(N - 1, i)));
  };

  const lastRow = data.series[N - 1];

  return (
    <div className="chart-wrap">
      <svg
        ref={svgRef}
        viewBox={`0 0 ${W} ${H}`}
        preserveAspectRatio="none"
        className="chart"
        onMouseMove={handleMove}
        onMouseLeave={() => setHoverIdx(null)}
      >
        {/* Y gridlines + labels */}
        {yTicks.map(v => (
          <g key={v}>
            <line x1={PL} x2={W - PR} y1={y(v)} y2={y(v)} className="chart-grid" />
            <text x={PL - 8} y={y(v)} className="chart-axis" textAnchor="end" dominantBaseline="middle">{v}%</text>
          </g>
        ))}

        {/* X labels */}
        {data.series.map((row, i) => {
          if (i % 2 !== 0 && i !== N - 1) return null;
          return (
            <text key={row.date} x={x(i)} y={H - 12} className="chart-axis" textAnchor="middle">
              {fmtMonth(row.date)}
            </text>
          );
        })}

        {/* Hover crosshair */}
        {hoverIdx != null && (
          <line x1={x(hoverIdx)} x2={x(hoverIdx)} y1={PT} y2={H - PB} className="chart-cross" />
        )}

        {/* Party lines */}
        {data.parties.map(p => {
          const pts = data.series.map((row, i) => `${x(i)},${y(row[p.id])}`).join(" ");
          return (
            <g key={p.id}>
              <polyline points={pts} fill="none" stroke={p.color} strokeWidth="2.5"
                strokeLinejoin="round" strokeLinecap="round" />
              {/* End-of-line label */}
              <circle cx={x(N - 1)} cy={y(lastRow[p.id])} r="3.5" fill={p.color} />
              <text x={W - PR + 8} y={y(lastRow[p.id])} className="chart-end-label"
                    dominantBaseline="middle" fill={p.color}>
                {p.name}
              </text>
              <text x={W - PR + 8} y={y(lastRow[p.id]) + 14} className="chart-end-value"
                    dominantBaseline="middle">
                {lastRow[p.id].toFixed(1)}%
              </text>
            </g>
          );
        })}

        {/* Hover dots */}
        {hoverIdx != null && data.parties.map(p => (
          <circle key={p.id} cx={x(hoverIdx)} cy={y(data.series[hoverIdx][p.id])}
                  r="4.5" fill="var(--bg)" stroke={p.color} strokeWidth="2.5" />
        ))}
      </svg>

      {/* Hover readout */}
      {hoverIdx != null && (
        <div className="chart-readout" style={{ left: `${(x(hoverIdx) / W) * 100}%` }}>
          <div className="chart-readout-date">{fmtMonth(data.series[hoverIdx].date)}</div>
          {data.parties.map(p => (
            <div key={p.id} className="chart-readout-row">
              <span className="chart-readout-dot" style={{ background: p.color }} />
              <span className="chart-readout-name">{p.name}</span>
              <span className="chart-readout-val">{data.series[hoverIdx][p.id].toFixed(1)}%</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ──────────────────────────────────────────────────────────
   Approval chart — single area + line
   ────────────────────────────────────────────────────────── */
function ApprovalChart({ data, hoverIdx, setHoverIdx, lang = "en" }) {
  const t = (en, fr) => (lang === "fr" ? fr : en);
  const loc = lang === "fr" ? "fr-CA" : "en-CA";
  const svgRef = useRefP(null);
  const yMin = 30, yMax = 70;
  const yTicks = ticksY(yMin, yMax, 10);
  const N = data.length;
  const x = (i) => PL + (i / (N - 1)) * innerW;
  const y = (v) => PT + innerH - ((v - yMin) / (yMax - yMin)) * innerH;

  const handleMove = (e) => {
    const rect = svgRef.current.getBoundingClientRect();
    const px = ((e.clientX - rect.left) / rect.width) * W;
    const i = Math.round(((px - PL) / innerW) * (N - 1));
    setHoverIdx(Math.max(0, Math.min(N - 1, i)));
  };

  const pts = data.map((row, i) => `${x(i)},${y(row.value)}`).join(" ");
  const areaPath = `M ${PL},${y(yMin)} L ${data.map((r, i) => `${x(i)},${y(r.value)}`).join(" L ")} L ${x(N-1)},${y(yMin)} Z`;
  const last = data[N - 1];
  const first = data[0];
  const delta = last.value - first.value;
  const peak = data.reduce((a, b) => (b.value > a.value ? b : a));
  const monthYear = (d) => { const [y, m] = d.split("-"); return new Date(+y, +m - 1, 1).toLocaleDateString(loc, { month: "short", year: "numeric" }); };
  const monthApos = (d) => { const [y, m] = d.split("-"); return new Date(+y, +m - 1, 1).toLocaleDateString(loc, { month: "short" }) + " '" + y.slice(2); };

  return (
    <div className="chart-wrap">
      <svg
        ref={svgRef}
        viewBox={`0 0 ${W} ${H}`}
        preserveAspectRatio="none"
        className="chart"
        onMouseMove={handleMove}
        onMouseLeave={() => setHoverIdx(null)}
      >
        <defs>
          <linearGradient id="approvalGrad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.22" />
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0.02" />
          </linearGradient>
        </defs>
        {yTicks.map(v => (
          <g key={v}>
            <line x1={PL} x2={W - PR} y1={y(v)} y2={y(v)} className="chart-grid" />
            <text x={PL - 8} y={y(v)} className="chart-axis" textAnchor="end" dominantBaseline="middle">{v}%</text>
          </g>
        ))}
        {data.map((row, i) => {
          if (i % 2 !== 0 && i !== N - 1) return null;
          return <text key={row.date} x={x(i)} y={H - 12} className="chart-axis" textAnchor="middle">{fmtMonth(row.date)}</text>;
        })}

        {/* 50% reference line */}
        <line x1={PL} x2={W - PR} y1={y(50)} y2={y(50)} className="chart-ref" />
        <text x={W - PR + 6} y={y(50)} className="chart-axis" dominantBaseline="middle" fill="var(--ink-3)">50%</text>

        <path d={areaPath} fill="url(#approvalGrad)" />
        <polyline points={pts} fill="none" stroke="var(--accent)" strokeWidth="2.5"
                  strokeLinejoin="round" strokeLinecap="round" />

        {hoverIdx != null && (
          <>
            <line x1={x(hoverIdx)} x2={x(hoverIdx)} y1={PT} y2={H - PB} className="chart-cross" />
            <circle cx={x(hoverIdx)} cy={y(data[hoverIdx].value)} r="5" fill="var(--bg)" stroke="var(--accent)" strokeWidth="2.5" />
          </>
        )}

        {/* End label */}
        <circle cx={x(N - 1)} cy={y(last.value)} r="3.5" fill="var(--accent)" />
        <text x={W - PR + 8} y={y(last.value) - 6} className="chart-end-label" fill="var(--accent)" dominantBaseline="middle">{t("Now", "Auj.")}</text>
        <text x={W - PR + 8} y={y(last.value) + 10} className="chart-end-value" dominantBaseline="middle">{last.value}%</text>
      </svg>

      <div className="approval-summary">
        <div className="approval-stat">
          <div className="approval-stat-label">{t("Approval", "Approbation")}, {monthYear(last.date)}</div>
          <div className="approval-stat-value">{last.value}%</div>
        </div>
        <div className="approval-stat">
          <div className="approval-stat-label">{t("Since taking office", "Depuis l'entrée en fonction")}</div>
          <div className={`approval-stat-value ${delta < 0 ? "neg" : "pos"}`}>
            {delta > 0 ? "+" : ""}{delta} pts
          </div>
        </div>
        <div className="approval-stat">
          <div className="approval-stat-label">{t("Peak", "Sommet")}</div>
          <div className="approval-stat-value">{peak.value}% <span className="approval-stat-sub">{monthApos(peak.date)}</span></div>
        </div>
      </div>

      {hoverIdx != null && (
        <div className="chart-readout" style={{ left: `${(x(hoverIdx) / W) * 100}%` }}>
          <div className="chart-readout-date">{fmtMonth(data[hoverIdx].date)}</div>
          <div className="chart-readout-row">
            <span className="chart-readout-dot" style={{ background: "var(--accent)" }} />
            <span className="chart-readout-name">Approval</span>
            <span className="chart-readout-val">{data[hoverIdx].value}%</span>
          </div>
        </div>
      )}
    </div>
  );
}

window.PollingSection = PollingSection;
