/* global React */

const CampaignStats = ({ runKey, position, chips }) => {
  const [vals, setVals]   = React.useState(chips.map(c => c.kind === "count" ? 0 : false));
  const [shown, setShown] = React.useState(chips.map(() => false));

  React.useEffect(() => {
    setVals(chips.map(c => c.kind === "count" ? 0 : false));
    setShown(chips.map(() => false));

    const timers = [];

    chips.forEach((chip, idx) => {
      const entryDelay = 300 + idx * 320;

      timers.push(setTimeout(() =>
        setShown(s => { const n = [...s]; n[idx] = true; return n; }),
        entryDelay
      ));

      if (chip.kind === "count") {
        timers.push(setTimeout(() => {
          let cur = 0;
          const stepSize = chip.to / (chip.steps || 20);
          const t = setInterval(() => {
            cur = parseFloat(Math.min(cur + stepSize, chip.to).toFixed(chip.decimals || 0));
            setVals(v => { const n = [...v]; n[idx] = cur; return n; });
            if (cur >= chip.to) clearInterval(t);
          }, chip.speed || 30);
          timers.push(t);
        }, entryDelay));
      } else {
        timers.push(setTimeout(() =>
          setVals(v => { const n = [...v]; n[idx] = true; return n; }),
          entryDelay + 200
        ));
      }
    });

    return () => timers.forEach(t => { clearInterval(t); clearTimeout(t); });
  }, [runKey]);

  return (
    <div style={{
      position: "absolute",
      display: "flex", flexDirection: "column", gap: 20,
      zIndex: 3, pointerEvents: "none",
      ...position
    }}>
      {chips.map((chip, idx) => {
        const raw = vals[idx];
        const display = chip.kind === "count"
          ? (chip.decimals ? Number(raw).toFixed(chip.decimals) : String(Math.round(raw))) + (chip.suffix || "")
          : (raw ? chip.text : "—");

        return (
          <div key={idx} style={{
            opacity: shown[idx] ? 1 : 0,
            transform: shown[idx] ? "translateY(0)" : "translateY(20px)",
            transition: "opacity 0.5s ease, transform 0.5s cubic-bezier(0.22,1,0.36,1)",
            background: "rgba(10,14,20,0.82)",
            backdropFilter: "blur(4px)",
            borderLeft: `4px solid ${chip.accent}`,
            padding: "12px 22px",
            minWidth: chip.width || 120,
            width: chip.width || 120
          }}>
            <div style={{
              fontFamily: "var(--font-condensed)", fontWeight: 800,
              fontSize: 26, lineHeight: 1, letterSpacing: "-0.01em",
              color: chip.accent
            }}>{display}</div>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 8, fontWeight: 600,
              letterSpacing: "0.16em", textTransform: "uppercase",
              color: "rgba(240,233,216,0.55)", marginTop: 3
            }}>{chip.label}</div>
          </div>
        );
      })}
    </div>
  );
};

const IMPACT_STATS = [
  // 2: Hadapsar Assembly Stand — stats MIDDLE-RIGHT
  {
    position: { top: "50%", right: 14 },
    chips: [
      { kind: "count", to: 40,  suffix: "%", label: "Vote Share", accent: "#4AA8A0", width: 148, speed: 30 },
      { kind: "count", to: 128, suffix: "K", label: "Votes",      accent: "#C9A84C", width: 148, speed: 15 },
      { kind: "text",  text: "1st",          label: "Runner-Up",  accent: "#E86A2A", width: 118 },
    ],
  },
  // 1: Ward 16 Victory — stats MIDDLE-LEFT
  {
    position: { top: "50%", left: 14 },
    chips: [
      { kind: "count", to: 85,  suffix: "K", label: "Voters",    accent: "#C9A84C", width: 148, speed: 25 },
      { kind: "count", to: 6,   suffix: "K", label: "Margin",    accent: "#4AA8A0", width: 118, speed: 80, steps: 6 },
      { kind: "text",  text: "BJP",          label: "Win",        accent: "#E86A2A", width: 92  },
    ],
  },
  // 3: Pimpri Groundwork — stats MIDDLE-RIGHT
  {
    position: { top: "50%", right: 14 },
    chips: [
      { kind: "text",  text: "MLA",          label: "Chabukswar", accent: "#C9A84C", width: 148 },
      { kind: "text",  text: "Survey",       label: "Groundwork", accent: "#4AA8A0", width: 140 },
      { kind: "text",  text: "Strong",       label: "Foundation", accent: "#E86A2A", width: 140 },
    ],
  },
  // 4: BSP Statewide Branding — stats UPPER-LEFT
  {
    position: { top: "35%", left: 14 },
    chips: [
      { kind: "count", to: 36,  suffix: "",  label: "Districts",  accent: "#C9A84C", width: 148, speed: 40 },
      { kind: "text",  text: "100K+",        label: "Reach",      accent: "#4AA8A0", width: 128 },
      { kind: "text",  text: "State",        label: "Wide Brand", accent: "#E86A2A", width: 128 },
    ],
  },
  // 5: Ghore Ghore Hathi — stats UPPER-LEFT
  {
    position: { top: "35%", left: 14 },
    chips: [
      { kind: "text",  text: "AGP",          label: "Party",      accent: "#4AA8A0", width: 118 },
      { kind: "text",  text: "Bongaigaon",   label: "Assembly",   accent: "#C9A84C", width: 148 },
      { kind: "text",  text: "Win",          label: "Campaign",   accent: "#E86A2A", width: 118 },
    ],
  },
];

const IMPACTS = [
  { id: 2, year: "2024", state: "Maharashtra",      title: "Hadapsar Assembly Stand", lede: "40.22% vote share for NCP's candidate — first runner-up with 1,27,688 votes. The campaign built unmatched voter visibility across the constituency.",                                                                                        color: "var(--teal)", image: "./assets/impactsection/Ward 16 Victory/2.png" },
  { id: 1, year: "2026", state: "Pune",             title: "Ward 16 Victory",        lede: "A decisive win in Hadapsar-Satavadi — 6,000 vote margin, defeating both NCP and the incumbent MLA's supported candidate. BJP retained the ward with 85,488 voters.",                                                                                                color: "var(--gold)", image: "./assets/impactsection/Ward 16 Victory/1.png" },
  { id: 3, year: "2024", state: "Pimpri-Chinchwad", title: "Pimpri Groundwork",        lede: "Extensive constituency surveys and strategic outreach for former MLA Gautam Chabukswar. Ground research laid strong foundation despite last-minute seat reallocation.",                                                                        color: "var(--navy)", image: "./assets/impactsection/Ward 16 Victory/3.png" },
  { id: 4, year: "2024", state: "Maharashtra",      title: "BSP Statewide Branding",  lede: "Personal branding for Dr. Hulgesh Chalwadi — social media reach, high-profile events, and podcast production on major political issues across Maharashtra.",                                                                                color: "var(--gold)", image: "./assets/impactsection/Ward 16 Victory/4.png" },
  { id: 5, year: "2022", state: "Assam",            title: "Ghore Ghore Hathi",       lede: "The Bongaigaon Assembly Constituency campaign for Phany Bhushan Chaudhuri — widely appreciated by party leadership for its strategic planning, strong ground execution, and impactful voter outreach.",                                                                              color: "var(--teal)", image: "./assets/impactsection/Ward 16 Victory/5.png" },
];

const Impact = () => {
  const [i, setI] = React.useState(0);
  const c = IMPACTS[i];
  const stats = IMPACT_STATS[i];

  return (
    <section id="impact" className="section-pad" style={{
      background: "var(--ink)", color: "var(--cream)",
      padding: "128px 32px", borderTop: "1px solid var(--hairline)"
    }}>
      <div style={{ maxWidth: 1280, margin: "0 auto" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 32 }}>
          <Eyebrow accent>Our Impact</Eyebrow>
          <div style={{ display: "flex", gap: 8 }}>
            <button
              onClick={() => setI((i - 1 + IMPACTS.length) % IMPACTS.length)}
              aria-label="Previous"
              style={{
                width: 40, height: 40, border: "1px solid rgba(244,239,224,0.3)",
                background: "transparent", color: "var(--cream)", borderRadius: 2, cursor: "pointer",
                fontSize: 18, display: "flex", alignItems: "center", justifyContent: "center"
              }}
            >←</button>
            <button
              onClick={() => setI((i + 1) % IMPACTS.length)}
              aria-label="Next"
              style={{
                width: 40, height: 40, border: "1px solid rgba(244,239,224,0.3)",
                background: "transparent", color: "var(--cream)", borderRadius: 2, cursor: "pointer",
                fontSize: 18, display: "flex", alignItems: "center", justifyContent: "center"
              }}
            >→</button>
          </div>
        </div>

        <h2 style={{
          fontFamily: "var(--font-display)", fontWeight: 600,
          fontSize: "clamp(36px, 4vw, 56px)", lineHeight: 1.02,
          letterSpacing: "-0.03em", margin: "0 0 64px", color: "var(--cream)"
        }}>
          Campaigns that shaped outcomes.
        </h2>

        <div className="grid-impact" style={{
          display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: 56, alignItems: "center"
        }}>
          {/* Image card with animated stats overlay */}
          <div style={{
            aspectRatio: "4/5", background: c.color,
            position: "relative", overflow: "hidden",
            display: "flex", alignItems: "flex-end",
            transition: "background 400ms var(--ease-out)", borderRadius: 2
          }}>
            <img
              src={c.image}
              alt={c.title}
              style={{
                position: "absolute",
                bottom: 0, left: 0,
                height: "100%",
                width: "auto",
                objectFit: "contain",
                objectPosition: "bottom left"
              }}
            />
            <CampaignStats runKey={i} position={stats.position} chips={stats.chips} />
          </div>

          {/* Text + dot nav */}
          <div>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--gold)",
              letterSpacing: "0.15em", marginBottom: 16
            }}>
              {c.state.toUpperCase()} · {c.year}
            </div>
            <p style={{ fontSize: 22, lineHeight: 1.45, color: "var(--cream)", margin: "0 0 32px" }}>
              {c.lede}
            </p>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {IMPACTS.map((it, idx) => (
                <button key={it.id} onClick={() => setI(idx)} style={{
                  fontFamily: "var(--font-mono)", fontSize: 11,
                  padding: "6px 10px", borderRadius: 999,
                  background: idx === i ? "var(--gold)" : "transparent",
                  color: idx === i ? "var(--ink)" : "rgba(244,239,224,0.7)",
                  border: `1px solid ${idx === i ? "var(--gold)" : "rgba(244,239,224,0.25)"}`,
                  cursor: "pointer", letterSpacing: "0.04em", fontWeight: 600
                }}>{it.title}</button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

window.Impact = Impact;
