/* global React */
const { useState, useEffect, useRef } = React;

// ── Inject animation keyframes + responsive CSS ─────────────────────────────
const _heroCss = document.createElement('style');
_heroCss.textContent = `
  @keyframes hero-slide-in {
    from { opacity: 0; transform: translateY(20px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  @keyframes hero-img-fade {
    from { opacity: 0; transform: scale(1.04); }
    to   { opacity: 1; transform: scale(1); }
  }
  .hero-slide { animation: hero-slide-in 600ms cubic-bezier(.2,.8,.2,1) forwards; }

  /* ── Responsive grid ── */
  @media (max-width: 768px) {
    .hero-grid {
      grid-template-columns: 1fr !important;
      grid-template-rows: auto auto auto !important;
      gap: 0 !important;
      min-height: auto !important;
      padding-top: 88px !important;
      padding-bottom: 48px !important;
      align-items: start !important;
    }
    .hero-text-top  { order: 1; grid-column: unset !important; grid-row: unset !important; }
    .hero-img-col   {
      order: 2;
      grid-column: unset !important; grid-row: unset !important;
      width: 100% !important;
      aspect-ratio: unset !important;
      height: 300px !important;
      border-radius: 0 !important;
      box-shadow: none !important;
      margin-left: -32px !important;
      margin-right: -32px !important;
      width: calc(100% + 64px) !important;
    }
    .hero-text-bottom { order: 3; grid-column: unset !important; grid-row: unset !important; padding-top: 28px !important; }
    .hero-bottom-stats {
      grid-template-columns: repeat(2, 1fr) !important;
      margin-top: 32px !important;
    }
  }

  @media (max-width: 480px) {
    .hero-img-col   { height: 260px !important; }
    .hero-grid      { padding-top: 76px !important; }
  }
`;
document.head.appendChild(_heroCss);

// ── Impact slideshow data (mirrors Impact.jsx) ───────────────────────────────
const HERO_IMPACTS = [
  { id: 2, year: "2024", state: "Maharashtra",      politician: "Prashant Jagtap",      margin: null,             color: "var(--teal)", image: "./assets/impactsection/Ward 16 Victory/2.png", mobileImgRight: false },
  { id: 1, year: "2026", state: "Pune",             politician: "Maruti Aba Tupe",          margin: "6K Vote Margin", color: "var(--gold)", image: "./assets/impactsection/Ward 16 Victory/1.png", mobileImgRight: true  },
  { id: 3, year: "2024", state: "Pimpri-Chinchwad", politician: "Gautam Chabukswar",    margin: null,             color: "var(--navy)", image: "./assets/impactsection/Ward 16 Victory/3.png", mobileImgRight: false },
  { id: 4, year: "2024", state: "Maharashtra",      politician: "Dr. Hulgesh Chalwadi", margin: null,             color: "var(--gold)", image: "./assets/impactsection/Ward 16 Victory/4.png", mobileImgRight: true  },
  { id: 5, year: "2023", state: "Assam",            politician: "Phany Bhushan Chaudhuri", margin: null,           color: "var(--teal)", image: "./assets/impactsection/Ward 16 Victory/5.png", mobileImgRight: true  },
];

const HERO_IMPACT_STATS = [
  {
    position: { top: "38%", right: 14 }, mobileLeftMiddle: false, mobileRightMiddle: true,
    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 },
    ],
  },
  {
    position: { top: "38%", left: 14 }, mobileLeftMiddle: true,
    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  },
    ],
  },
  {
    position: { top: "38%", right: 14 }, mobileLeftMiddle: false, mobileRightMiddle: true,
    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 },
    ],
  },
  {
    position: { top: "35%", left: 14 }, mobileLeftMiddle: true,
    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 },
    ],
  },
  {
    position: { top: "35%", left: 14 }, mobileLeftMiddle: true,
    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 },
    ],
  },
];

// ── Animated stat chips ───────────────────────────────────────────────────────
const HeroCampaignStats = ({ runKey, position, chips, isMobile, mobileLeftMiddle, mobileRightMiddle }) => {
  const [vals, setVals]   = useState(chips.map(c => c.kind === "count" ? 0 : false));
  const [shown, setShown] = useState(chips.map(() => false));

  useEffect(() => {
    setVals(chips.map(c => c.kind === "count" ? 0 : false));
    setShown(chips.map(() => false));
    const timers = [];
    chips.forEach((chip, idx) => {
      const entryDelay = 300 + idx * 260;
      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]);

  // Mobile wrapper variants
  const mobileLeftMiddleWrapStyle = {
    position: "absolute",
    top: "38%", left: 28,
    transform: "translateY(-50%)",
    display: "flex", flexDirection: "column", gap: 8,
    zIndex: 3, pointerEvents: "none",
  };
  const mobileRightMiddleWrapStyle = {
    position: "absolute",
    top: "50%", right: 28,
    transform: "translateY(-50%)",
    display: "flex", flexDirection: "column", gap: 8,
    zIndex: 3, pointerEvents: "none",
  };
  const mobileTopRowWrapStyle = {
    position: "absolute",
    top: 10, left: 10, right: 10,
    display: "flex", flexDirection: "row",
    flexWrap: "wrap", gap: 6,
    zIndex: 3, pointerEvents: "none",
  };
  const desktopWrapStyle = {
    position: "absolute",
    display: "flex", flexDirection: "column", gap: 20,
    zIndex: 3, pointerEvents: "none",
    ...position
  };

  const activeMobileStyle = mobileLeftMiddle
    ? mobileLeftMiddleWrapStyle
    : mobileRightMiddle
      ? mobileRightMiddleWrapStyle
      : mobileTopRowWrapStyle;

  return (
    <div style={isMobile ? activeMobileStyle : desktopWrapStyle}>
      {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 : "—");

        const mobileChipStyle = {
          opacity:   shown[idx] ? 1 : 0,
          transform: shown[idx] ? "translateY(0)" : "translateY(10px)",
          transition: "opacity 0.4s ease, transform 0.4s cubic-bezier(0.22,1,0.36,1)",
          background: "rgba(10,14,20,0.85)",
          backdropFilter: "blur(6px)",
          borderLeft: `3px solid ${chip.accent}`,
          padding: "6px 10px",
          width: "auto",
          minWidth: 0,
        };
        const desktopChipStyle = {
          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,
        };

        return (
          <div key={idx} style={isMobile ? mobileChipStyle : desktopChipStyle}>
            <div style={{
              fontFamily: "var(--font-condensed)", fontWeight: 800,
              fontSize: isMobile ? 16 : 26,
              lineHeight: 1, letterSpacing: "-0.01em",
              color: chip.accent,
              whiteSpace: "nowrap"
            }}>{display}</div>
            <div style={{
              fontFamily: "var(--font-mono)",
              fontSize: isMobile ? 7 : 8,
              fontWeight: 600,
              letterSpacing: "0.16em", textTransform: "uppercase",
              color: "rgba(240,233,216,0.55)",
              marginTop: isMobile ? 2 : 3,
              whiteSpace: "nowrap"
            }}>{chip.label}</div>
          </div>
        );
      })}
    </div>
  );
};

// ── Hero ─────────────────────────────────────────────────────────────────────
const Hero = ({ onCta }) => {
  const [current, setCurrent] = useState(0);
  const [animKey, setAnimKey] = useState(0);
  const [imgKey,  setImgKey]  = useState(0);
  const [isMobile, setIsMobile] = useState(window.innerWidth <= 768);
  const timerRef    = useRef(null);
  const touchStartX = useRef(null);

  useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  const startTimer = () => {
    clearInterval(timerRef.current);
    timerRef.current = setInterval(() => {
      setCurrent(prev => (prev + 1) % HERO_IMPACTS.length);
      setAnimKey(k => k + 1);
      setImgKey(k => k + 1);
    }, 4500);
  };

  useEffect(() => {
    startTimer();
    return () => clearInterval(timerRef.current);
  }, []);

  const goTo = (idx) => {
    if (idx === current) return;
    setCurrent(idx);
    setAnimKey(k => k + 1);
    setImgKey(k => k + 1);
    startTimer();
  };

  const onSlideStart = (e) => { touchStartX.current = e.changedTouches[0].clientX; };
  const onSlideEnd   = (e) => {
    if (touchStartX.current === null) return;
    const diff = touchStartX.current - e.changedTouches[0].clientX;
    if (Math.abs(diff) > 50) {
      goTo(diff > 0
        ? (current + 1) % HERO_IMPACTS.length
        : (current - 1 + HERO_IMPACTS.length) % HERO_IMPACTS.length);
    }
    touchStartX.current = null;
  };

  const c     = HERO_IMPACTS[current];
  const stats = HERO_IMPACT_STATS[current];

  return (
    <section id="top" style={{
      background: "var(--ink)",
      position: "relative", overflow: "hidden",
      minHeight: "100vh"
    }}>

      {/* Dot grid */}
      <div aria-hidden style={{
        position: "absolute", inset: 0, opacity: 0.04, pointerEvents: "none",
        backgroundImage: "radial-gradient(circle, var(--parchment) 1px, transparent 1px)",
        backgroundSize: "18px 18px"
      }}/>

      {/* Two-column layout */}
      <div className="hero-grid" style={{
        maxWidth: 1280, margin: "0 auto",
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gridTemplateRows: "1fr auto",
        gap: "0 48px",
        minHeight: "100vh", padding: "clamp(80px, 10vh, 120px) 32px"
      }}>

        {/* ── Text top: eyebrow → description (desktop col 1 row 1) ── */}
        <div className="hero-text-top" style={{
          position: "relative", zIndex: 2,
          gridColumn: 1, gridRow: 1
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 36 }}>
            <div style={{ width: 48, height: 2, background: "var(--peacock)", flexShrink: 0 }}/>
            <span style={{
              fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 500,
              letterSpacing: "0.18em", textTransform: "uppercase",
              color: "var(--peacock-bright)"
            }}>Political & Election Consultancy · Pune, Maharashtra</span>
          </div>

          <h1 className="h1-hero hero-slide" key={animKey} style={{
            fontFamily: "var(--font-condensed)",
            fontWeight: 800,
            fontSize: "clamp(48px, 6.5vw, 96px)",
            lineHeight: 0.95,
            letterSpacing: "-0.01em",
            textTransform: "uppercase",
            color: "var(--parchment)",
            margin: "0 0 32px"
          }}>
            Strategic<br/>
            Campaigns.<br/>
            <span style={{ color: "var(--gold)" }}>Voter Connection.</span>
          </h1>

          <div style={{ display: "flex", alignItems: "flex-start", gap: 16, margin: "0 0 20px" }}>
            <div style={{ width: 3, height: 36, background: "var(--gold)", flexShrink: 0, marginTop: 4 }}/>
            <p style={{
              fontFamily: "var(--font-display)", fontSize: "clamp(16px, 2vw, 22px)",
              fontWeight: 400, fontStyle: "italic",
              color: "rgba(240,233,216,0.9)", lineHeight: 1.35, margin: 0
            }}>
              Data-driven campaigns. Ground-up voter engagement. Results.
            </p>
          </div>

        </div>

        {/* ── Text bottom: buttons + stats (desktop col 1 row 2) ── */}
        <div className="hero-text-bottom" style={{
          position: "relative", zIndex: 2,
          gridColumn: 1, gridRow: 2,
          alignSelf: "end"
        }}>
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
            <Button variant="primary" onClick={onCta}>Work with us</Button>
            <Button variant="ghost-light" arrow={false}
              onClick={() => {
                document.getElementById("work").scrollIntoView({ behavior: "smooth" });
                setTimeout(() => window.dispatchEvent(new CustomEvent("pravah:openWork")), 700);
              }}>
              See our work
            </Button>
          </div>

          <div className="hero-bottom-stats" style={{
            marginTop: "clamp(48px, 7vh, 80px)",
            paddingTop: 20,
            borderTop: "2px solid var(--peacock)",
            display: "grid",
            gridTemplateColumns: "repeat(4, 1fr)",
            gap: 16
          }}>
            {[
              { y: "7+ Years", l: "Election campaign management experience" },
              { y: "Digital",  l: "Social media & voter outreach" },
              { y: "Leaders",  l: "Cabinet ministers, MPs, MLAs & more" },
              { y: "Trust",    l: "Voter engagement & connection" },
            ].map((s, i) => (
              <div key={i}>
                <div style={{
                  fontFamily: "var(--font-mono)", fontSize: 10,
                  color: "var(--gold)", fontWeight: 600,
                  letterSpacing: "0.18em", marginBottom: 6
                }}>{s.y}</div>
                <div style={{
                  fontFamily: "var(--font-body)", fontSize: 13,
                  color: "rgba(240,233,216,0.6)", lineHeight: 1.45
                }}>{s.l}</div>
              </div>
            ))}
          </div>
        </div>

        {/* ── Right: Impact-style image card slideshow (desktop col 2 rows 1–2) ── */}
        <div
          className="hero-img-col"
          onTouchStart={onSlideStart}
          onTouchEnd={onSlideEnd}
          style={{
            position: "relative",
            aspectRatio: "4/5",
            borderRadius: 2,
            overflow: "hidden",
            boxShadow: "0 20px 60px rgba(0,0,0,0.45)",
            background: c.color,
            transition: "background 500ms ease",
            display: "flex", alignItems: "flex-end",
            gridColumn: 2, gridRow: "1 / 3"
          }}
        >
          {/* Slide images — cross-fade */}
          {HERO_IMPACTS.map((item, idx) => {
            const anchorRight = isMobile && item.mobileImgRight;
            return (
              <img
                key={item.id}
                src={item.image}
                alt={item.title}
                style={{
                  position: "absolute",
                  bottom: 0,
                  left:  anchorRight ? "auto" : 0,
                  right: anchorRight ? 0      : "auto",
                  height: "100%", width: "auto",
                  objectFit: "contain",
                  objectPosition: anchorRight ? "bottom right" : "bottom left",
                  opacity: idx === current ? 1 : 0,
                  transition: "opacity 700ms ease",
                  animation: idx === current ? "hero-img-fade 700ms ease forwards" : "none"
                }}
              />
            );
          })}

          {/* Animated stat chips */}
          <HeroCampaignStats
            key={imgKey}
            runKey={imgKey}
            position={stats.position}
            chips={stats.chips}
            isMobile={isMobile}
            mobileLeftMiddle={stats.mobileLeftMiddle}
            mobileRightMiddle={stats.mobileRightMiddle}
          />

          {/* Bottom scrim */}
          <div style={{
            position: "absolute", inset: 0,
            background: "linear-gradient(to top, rgba(10,14,20,0.65) 0%, transparent 50%)",
            zIndex: 2, pointerEvents: "none"
          }}/>

          {/* Campaign label */}
          <div style={{
            position: "absolute",
            bottom: isMobile ? 36 : 48,
            left: 18, zIndex: 4,
            pointerEvents: "none"
          }}>
            <div style={{
              fontFamily: "var(--font-mono)",
              fontSize: isMobile ? 9 : 10,
              fontWeight: 600,
              letterSpacing: "0.14em", textTransform: "uppercase",
              color: "rgba(240,233,216,0.55)", marginBottom: 3
            }}>{c.state.toUpperCase()} · {c.year}</div>
            <div style={{
              fontFamily: "var(--font-condensed)",
              fontSize: isMobile ? 13 : 15,
              fontWeight: 700,
              letterSpacing: "0.05em", textTransform: "uppercase",
              color: "rgba(240,233,216,0.92)"
            }}>{c.politician}</div>
            {c.margin && (
              <div style={{
                fontFamily: "var(--font-mono)",
                fontSize: isMobile ? 9 : 10,
                fontWeight: 600,
                letterSpacing: "0.12em", textTransform: "uppercase",
                color: "var(--gold)", marginTop: 4
              }}>{c.margin}</div>
            )}
          </div>

          {/* Dot indicators */}
          <div style={{
            position: "absolute", bottom: 12, left: "50%",
            transform: "translateX(-50%)",
            display: "flex", gap: isMobile ? 6 : 8, zIndex: 4
          }}>
            {HERO_IMPACTS.map((_, idx) => (
              <button
                key={idx}
                onClick={() => goTo(idx)}
                style={{
                  width: idx === current ? (isMobile ? 20 : 24) : (isMobile ? 6 : 8),
                  height: isMobile ? 6 : 8,
                  borderRadius: 4, border: "none",
                  background: idx === current ? "var(--gold)" : "rgba(240,233,216,0.35)",
                  cursor: "pointer", padding: 0,
                  transition: "width 220ms, background 220ms"
                }}
              />
            ))}
          </div>
        </div>
      </div>

      {/* Diagonal accent line — desktop only */}
      {!isMobile && (
        <div aria-hidden style={{
          position: "absolute",
          left: "48%", top: 0, bottom: 0, width: 1,
          background: "linear-gradient(180deg, transparent 0%, rgba(11,110,104,0.3) 20%, rgba(11,110,104,0.3) 80%, transparent 100%)",
          transform: "skewX(-8deg)",
          pointerEvents: "none"
        }}/>
      )}
    </section>
  );
};

window.Hero = Hero;
