/* global React, VideoBackground, Icon, StarDivider, Eyebrow, SparkleHeading, Lightbox, Portrait */
const { useState: useStateAct, useEffect: useEffectAct, useMemo: useMemoAct } = React;

const REGISTER_LINKS = [
  {
    title: "California Voter Registration",
    sub: "Register or update your address with the Secretary of State.",
    href: "https://registertovote.ca.gov/",
    cta: "Register",
  },
  {
    title: "Check Registration Status",
    sub: "Confirm you're enrolled at the right address before deadline.",
    href: "https://voterstatus.sos.ca.gov",
    cta: "Check status",
  },
  {
    title: "Santa Barbara County Elections",
    sub: "Local ballots, drop boxes, polling places, and dates.",
    href: "https://www.countyofsb.org/164/Elections",
    cta: "County elections",
  },
];

const VOTING_TIPS = [
  ["Mail ballots, automatic", "Every California voter receives a vote‑by‑mail ballot."],
  ["Sign and date in ink", "On the return envelope — never on the ballot itself."],
  ["Postage is on us", "Return envelopes are postage‑paid."],
  ["24/7 drop boxes", "Drop boxes are available across the county, day or night."],
  ["Same‑day registration", "Available at the elections office or at any polling place."],
  ["Pre‑register at 16", "Sixteen and seventeen year‑olds can pre‑register today."],
];

const DISTRICT_LINKS = [
  { title: "Santa Maria City Districts", href: "https://santamariacity.maps.arcgis.com/apps/webappviewer/index.html?id=a12d2f43a91e4d869de09458e15cf34a" },
  { title: "SB County Full Lookup",      href: "http://www.sbcassessor.com/ElectionDataLookup/Default.aspx" },
  { title: "SB Supervisor District Map", href: "https://sbc-gis.maps.arcgis.com/apps/webappviewer/index.html?id=eec8b558246949d4912b99cf641a91e7" },
];

const ENDORSEMENTS = {
  "Santa Barbara County": [
    {
      name: "Kyle Slattery",
      office: "Auditor-Controller",
      web: "https://slattery4auditor.com/",
      instagram: "https://www.instagram.com/slattery4auditor/",
      photo: "uploads/Kyle_Slattery_v2.jpg",
    },
  ],
};

function CTA_Rotator({ messages }) {
  const [reduced, setReduced] = useStateAct(false);
  const [i, setI] = useStateAct(0);
  useEffectAct(() => {
    const m = window.matchMedia("(prefers-reduced-motion: reduce)");
    setReduced(m.matches);
    const change = () => setReduced(m.matches);
    m.addEventListener?.("change", change);
    return () => m.removeEventListener?.("change", change);
  }, []);
  useEffectAct(() => {
    if (reduced) return;
    const id = setInterval(() => setI(v => (v + 1) % messages.length), 5500);
    return () => clearInterval(id);
  }, [reduced, messages.length]);

  return (
    <div className="cta-rotator" aria-live="polite">
      {messages.map((m, idx) => (
        <span key={idx} className={`cta-msg ${idx === i ? "active" : ""}`}>{m}</span>
      ))}
    </div>
  );
}

function TakeAction({ lang }) {
  const t = (en, es) => (lang === "es" ? es : en);

  // Mosaic tiles + their lightbox index. Order matches DOM order so
  // ArrowLeft/Right in the lightbox steps through the visible mosaic.
  const mosaicTiles = useMemoAct(() => [
    { src: window.__resources.noKings01, alt: "Marchers gathered on a Santa Maria street with American flags.", cls: "big" },
    { src: window.__resources.noKings04, alt: "Demonstrators marching with handmade signs.", cls: "tall" },
    { src: window.__resources.noKings07, alt: "Crowd of protesters holding signs in front of palm trees.", cls: "" },
    { src: window.__resources.noKings08, alt: "Group portrait of protesters with 'No Dictators' signs.", cls: "" },
    { src: window.__resources.noKings02, alt: "Large rally crowd in a park, with a 'Dump White House Garbage' banner.", cls: "wide" },
    { src: window.__resources.noKings03, alt: "Police motorcycles escorting a march down the street.", cls: "wide" },
    { src: window.__resources.noKings05, alt: "March in Progress", cls: "" },
    { src: window.__resources.noKings10, alt: "A protester holding a 'Quiet Piggy' sign at the rally.", cls: "tall" },
    { src: window.__resources.noKings06, alt: "Marchers walking down the avenue, photographed from behind.", cls: "" },
    { src: window.__resources.noKings09, alt: "Dense crowd of rally-goers with hand-painted signs.", cls: "" },
    { src: window.__resources.noKings11, alt: "Diverse group of attendees raising signs along a parade route.", cls: "wide" } ],
  []);

  const [lightboxIndex, setLightboxIndex] = useStateAct(null);

  return (
    <>
      <section className="page-hero action-hero" aria-labelledby="action-title">
        <VideoBackground
          kind="fireworks"
          video={window.__resources.fireworksMp4}
          poster={window.__resources.fireworksPoster}
          overlay={false}
        />
        <div className="container page-hero-inner on-dark">
          <Eyebrow>{t("Take Action", "Participa")}</Eyebrow>
          <SparkleHeading id="action-title">
            {t("Your vote is", "Tu voto es")} <em>{t("your voice.", "tu voz.")}</em>
          </SparkleHeading>
          <p className="lede" style={{ color: "rgba(255,255,255,0.85)" }}>
            {t("Register, check your status, find your districts, and meet our endorsed candidates — all in one place.",
               "Regístrate, verifica tu estado, encuentra tus distritos y conoce a nuestros candidatos.")}
          </p>
          <div className="hero-ctas">
            <a className="btn btn-primary btn-lg" href="https://registertovote.ca.gov/" target="_blank" rel="noopener noreferrer">
              {t("Register to Vote", "Regístrate")} <Icon.Arrow className="arrow" />
            </a>
            <a className="btn btn-navy btn-lg" href="#endorsements">
              {t("See Endorsements", "Ver Apoyos")}
            </a>
          </div>
        </div>
      </section>

      {/* REGISTER */}
      <section className="ta-register" id="register">
        <div className="container">
          <div className="section-head">
            <Eyebrow>{t("Register", "Regístrate")}</Eyebrow>
            <h2>{t("Get on the rolls.", "Inscríbete.")}</h2>
          </div>
          <div className="register-grid">
            {REGISTER_LINKS.map((r, i) => (
              <a key={i} className="big-link-card" href={r.href} target="_blank" rel="noopener noreferrer">
                <div className="blc-num">{String(i+1).padStart(2,"0")}</div>
                <h3>{r.title}</h3>
                <p>{r.sub}</p>
                <div className="blc-cta">{r.cta} <Icon.External /></div>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* NO KINGS DAY MOSAIC */}
      <section className="nokings-mosaic-section" aria-labelledby="nokings-mosaic-title">
        <div className="container">
          <div className="section-head text-center">
            <Eyebrow>{t("No Kings Day", "Día Sin Reyes")}</Eyebrow>
            <h2 id="nokings-mosaic-title">
              {t("Our Community in Action", "Nuestra Comunidad en Acción")}
            </h2>
          </div>
          <div className="mosaic">
            {mosaicTiles.map((tile, i) => (
              <button
                key={i}
                type="button"
                className={`mosaic-item ${tile.cls}`}
                onClick={() => setLightboxIndex(i)}
                aria-label={t("Open photo: ", "Abrir foto: ") + tile.alt}>
                <img src={tile.src} alt={tile.alt} />
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* VOTING TIPS */}
      <section className="ta-tips">
        <div className="container">
          <div className="two-col">
            <div className="two-col-side sticky">
              <Eyebrow>{t("Voting Info", "Info Electoral")}</Eyebrow>
              <h2>{t("What every Californian should know.", "Lo que todo californiano debe saber.")}</h2>
              <div className="red-rule" />
              <p className="muted">
                {t("Six things that don't change cycle to cycle.",
                   "Seis cosas que no cambian de ciclo a ciclo.")}
              </p>
            </div>
            <div className="two-col-body">
              <ul className="tips-list star-list">
                {VOTING_TIPS.map(([h, b], i) => (
                  <li key={i}>
                    <span className="star-bullet" aria-hidden="true">
                      <svg viewBox="0 0 24 24"><path d="M12 2l2.9 6.6 7.1.6-5.4 4.7 1.7 7-6.3-3.8L5.7 21l1.7-7L2 9.2l7.1-.6L12 2z"/></svg>
                    </span>
                    <div>
                      <h4>{h}</h4>
                      <p>{b}</p>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </section>

      {/* DISTRICTS */}
      <section className="ta-districts">
        <div className="container">
          <div className="section-head">
            <Eyebrow>{t("Find Your Districts", "Tus Distritos")}</Eyebrow>
            <h2>{t("Know whose ballot you're on.", "Conoce tu boleta.")}</h2>
          </div>
          <div className="districts-grid">
            {DISTRICT_LINKS.map((d, i) => (
              <a key={i} className="district-card" href={d.href} target="_blank" rel="noopener noreferrer">
                <div className="dc-icon" aria-hidden="true">
                  <Icon.Pin size={20} />
                </div>
                <h4>{d.title}</h4>
                <span className="dc-cta">{t("Open lookup", "Abrir")} <Icon.External /></span>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* ENDORSEMENTS */}
      <section className="ta-endorse" id="endorsements">
        <div className="container">
          <div className="section-head">
            <Eyebrow>{t("Endorsements", "Apoyos")}</Eyebrow>
            <h2>{t("Who we're standing behind.", "A quién apoyamos.")}</h2>
            <p className="lede muted">
              {t("Endorsements coming as the cycle progresses — full list will appear here.",
                 "Los apoyos llegan conforme avanza el ciclo — la lista completa aparecerá aquí.")}
            </p>
          </div>

          {Object.entries(ENDORSEMENTS).map(([group, list]) => (
            <div key={group} className="endorse-group">
              <h3 className="endorse-group-h">{group}</h3>
              <div className="endorse-grid">
                {list.map((c, i) => {
                  const initials = c.name && c.name[0] !== "[" ? c.name.split(" ").map(s => s[0]).join("").slice(0, 2) : "—";
                  return (
                  <article key={i} className="endorse-card endorse-card-portrait">
                    <Portrait initials={initials} photo={c.photo} photoPos={c.photoPos} name={c.name} />
                    <div className="ec-body">
                      <h4>{c.name}</h4>
                      <div className="ec-office muted">{c.office}</div>
                      <div className="ec-actions">
                        {c.web && <a href={c.web} target="_blank" rel="noopener noreferrer">{t("Website", "Sitio web")} <Icon.External size={11}/></a>}
                        {c.instagram && <a href={c.instagram} target="_blank" rel="noopener noreferrer">{t("Instagram", "Instagram")} <Icon.Instagram size={13}/></a>}
                        {c.email && <a href={`mailto:${c.email}`}>{t("Email", "Correo")} <Icon.Mail size={12}/></a>}
                      </div>
                    </div>
                  </article>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* VOLUNTEER CALLOUT */}
      <section className="ta-volunteer">
        <div className="container">
          <div className="vol-card">
            <div>
              <Eyebrow>{t("Volunteer", "Voluntariado")}</Eyebrow>
              <h2 style={{ marginTop: 12 }}>
                {t("Help elect Democrats up and down the ballot.",
                   "Ayuda a elegir Demócratas en toda la boleta.")}
              </h2>
              <p>
                {t("Reach out to Jovany Medina, North County Field Organizer, to plug in.",
                   "Contacta a Jovany Medina, Organizador de Campo del Norte del Condado.")}
              </p>
            </div>
            <a className="btn btn-primary btn-lg" href="mailto:jovany@sbdems.org?subject=Volunteer">
              <Icon.Mail size={14} /> jovany@sbdems.org
            </a>
          </div>
        </div>
      </section>

      {/* CLOSING CTA BAND */}
      <section className="closing-cta closing-flat" aria-labelledby="closing-title">
        <div className="cta-marquee" aria-hidden="true">
          <div className="cta-row cta-row-1">
            <div className="cta-track">
              {Array.from({ length: 2 }).map((_, k) => (
                <span key={k} className="cta-track-inner">
                  <span>Your Vote Is Your Voice</span><span className="cta-star">★</span>
                  <span>Plan To Vote</span><span className="cta-star">★</span>
                  <span>The Future Of America Is With Your Vote</span><span className="cta-star">★</span>
                  <span>Vote Like Your Life Depends On It</span><span className="cta-star">★</span>
                </span>
              ))}
            </div>
          </div>
          <div className="cta-row cta-row-2">
            <div className="cta-track reverse">
              {Array.from({ length: 2 }).map((_, k) => (
                <span key={k} className="cta-track-inner">
                  <span>Real Friends Make Real Friends Vote</span><span className="cta-star">★</span>
                  <span>Make A Better Life By Voting</span><span className="cta-star">★</span>
                  <span>Voting Is The Reward For Loving Your Country</span><span className="cta-star">★</span>
                  <span>Vote Early By Mail</span><span className="cta-star">★</span>
                </span>
              ))}
            </div>
          </div>
          <div className="cta-row cta-row-3">
            <div className="cta-track">
              {Array.from({ length: 2 }).map((_, k) => (
                <span key={k} className="cta-track-inner">
                  <span>This Is The Most Important Vote Of Your Life</span><span className="cta-star">★</span>
                  <span>Your Children Are Depending On Your Vote</span><span className="cta-star">★</span>
                  <span>Your Vote Will Make You Proud</span><span className="cta-star">★</span>
                  <span>America's Democracy Is Decided By Your Vote</span><span className="cta-star">★</span>
                </span>
              ))}
            </div>
          </div>
          <div className="cta-row cta-row-4">
            <div className="cta-track reverse slow">
              {Array.from({ length: 2 }).map((_, k) => (
                <span key={k} className="cta-track-inner">
                  <span>Plan To Vote</span><span className="cta-star">★</span>
                  <span>Your Vote Is Your Voice</span><span className="cta-star">★</span>
                  <span>Show Up · Speak Up</span><span className="cta-star">★</span>
                  <span>The Future Of America Is With Your Vote</span><span className="cta-star">★</span>
                </span>
              ))}
            </div>
          </div>
        </div>
        <div className="container closing-inner on-dark">
          <h2 id="closing-title" className="sr-only">{t("Plan to vote.", "Planea votar.")}</h2>
          <a className="btn btn-primary btn-lg cta-pulse-btn" href="https://registertovote.ca.gov/" target="_blank" rel="noopener noreferrer">
            {t("Register to Vote", "Regístrate")} <Icon.Arrow className="arrow" />
          </a>
        </div>
      </section>

      <Lightbox
        images={mosaicTiles}
        index={lightboxIndex}
        onClose={() => setLightboxIndex(null)}
        onIndex={setLightboxIndex}
      />
    </>
  );
}

Object.assign(window, { TakeAction });
