/* =============================================================
 * Stories (Impact) + About — per Fathers Arise Brief
 * ============================================================= */

function StoriesPage() {
  const [stories, setStories] = useState([]);
  const [filter, setFilter] = useState("all");
  const [loading, setLoading] = useState(true);
  // Phase 3.7: editable site content
  const [cms, setCms] = useState({});
  useEffect(() => {
    window.cms.getStories().then((s) => {setStories(s);setLoading(false);});
    if (window.cms && typeof window.cms.getSiteContent === "function") {
      window.cms.getSiteContent("stories").then(setCms);
    }
  }, []);
  const sHero = cms.hero || {};

  // Lightbox: click video card → play; click gallery image → expand
  const [lightbox, setLightbox] = useState(null);
  useEffect(() => {
    if (!lightbox) return;
    const onKey = (e) => { if (e.key === "Escape") setLightbox(null); };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [lightbox]);
  const filtered = filter === "all" ? stories : stories.filter((s) => s.kind === filter);
  const filters = [
  { k: "all", l: "All Stories" },
  { k: "be-a-man", l: "Be A Man" },
  { k: "nurturing-bonds", l: "Nurturing Bonds" },
  { k: "mobile-kanaabe", l: "Mobile Kanaabe" }];


  return (
    <div data-screen-label="07 Stories">
      <section data-cms-section="hero" data-cms-page="stories" className="relative bg-navy text-white overflow-hidden">
        <div className="absolute inset-0">
          <img src={sHero.image || "uploads/TRG_Father_sBreakfast56.jpg"} alt="" className="w-full h-full object-cover" />
          <div className="absolute inset-0 bg-gradient-to-br from-navy/90 via-navy/75 to-navy/55" />
        </div>
        <div className={`relative max-w-[1280px] mx-auto px-4 sm:px-6 py-28 md:py-36 ${sHero.align === "center" ? "text-center" : sHero.align === "right" ? "text-right" : "text-left"}`}>
          <div className="text-xs font-display font-bold uppercase tracking-[0.25em] text-gold">Impact / Stories</div>
          <h1 className="mt-6 font-display font-black text-5xl sm:text-6xl md:text-7xl leading-[0.95]">{sHero.headline || <>Stories of <span className="text-gold">Transformation</span></>}</h1>
          <p className="mt-6 max-w-3xl text-xl md:text-2xl text-white/95 font-display font-medium leading-snug">{sHero.subhead || "Every man in Fathers Arise carries a story. Some are stories of pain. Some are stories of healing. All are stories of becoming. Here are the men who said yes."}</p>
        </div>
      </section>

      <section className="py-16 bg-paper">
        <div className="max-w-[1280px] mx-auto px-4 sm:px-6">
          <div className="flex flex-wrap gap-2 mb-10">
            {filters.map((f) =>
            <button key={f.k} onClick={() => setFilter(f.k)}
            className={`px-5 py-2.5 rounded-full text-sm font-display font-bold uppercase tracking-wider ${filter === f.k ? "bg-navy text-white" : "bg-white border border-navy/15 text-ink/70 hover:border-navy/40"}`}>{f.l}</button>
            )}
          </div>
          {loading ?
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {Array.from({ length: 6 }).map((_, i) => <div key={i} className="rounded-2xl bg-white border border-navy/8 h-72 animate-pulse" />)}
            </div> :

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filtered.map((s, i) => <StoryCard key={s.id} s={s} featured={i === 0 && filter === "all"} onOpen={() => setLightbox({ kind: "video", videoId: s.videoId, title: s.title, author: s.author })} />)}
            </div>
          }
        </div>
      </section>

      {/* Podcast section */}
      <section className="py-24 bg-navy text-white relative overflow-hidden">
        <div className="absolute inset-0 grid-bg opacity-10" />
        <div className="relative max-w-[1100px] mx-auto px-4 sm:px-6 grid grid-cols-1 md:grid-cols-12 gap-10 items-center">
          <div className="md:col-span-7">
            <div className="text-xs font-display font-bold uppercase tracking-[0.3em] text-gold">The Podcast</div>
            <h2 className="mt-4 font-display font-black text-4xl md:text-5xl leading-tight">The Fathers Arise Podcast</h2>
            <p className="mt-5 text-lg text-white/85 leading-relaxed">Monthly episodes featuring father testimonies, expert conversations, and teaching from the B-E-A-M-A-N and Forge curricula.</p>
            <div className="mt-8 flex flex-wrap gap-3">
              <a href="https://www.instagram.com/fathersariseofficial/?__pwa=1#" target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 px-5 py-3 rounded-full bg-gradient-to-tr from-[#FEDA77] via-[#F58529] to-[#DD2A7B] text-white font-display font-bold text-sm uppercase tracking-wider">Instagram</a>
              <a href="#" className="inline-flex items-center gap-2 px-5 py-3 rounded-full bg-white text-navy font-display font-bold text-sm uppercase tracking-wider">Apple Podcasts</a>
              <a href="https://www.youtube.com/@FathersArse" target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 px-5 py-3 rounded-full bg-[#FF0000] text-white font-display font-bold text-sm uppercase tracking-wider">YouTube</a>
            </div>
          </div>
          <div className="md:col-span-5">
            <div className="rounded-3xl overflow-hidden border border-white/15 shadow-2xl" style={{ aspectRatio: "16/9" }}>
              <iframe
                src="https://www.youtube.com/embed/SbvTQpPklCo"
                title="The Fears We Buried the Day We Became Fathers."
                frameBorder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                referrerPolicy="strict-origin-when-cross-origin"
                allowFullScreen
                className="w-full h-full"
              ></iframe>
            </div>
          </div>
        </div>
      </section>

      {/* Gallery — categorized + click-through with arrows */}
      <CategorizedGallery onOpen={(photos, index) => setLightbox({ kind: "gallery", photos, index })} />

      {lightbox && <Lightbox item={lightbox} onClose={() => setLightbox(null)} />}
    </div>);

}

function StoryCard({ s, featured, onOpen }) {
  const isVideo = s.kind === "video";
  return (
    <article className={`group rounded-2xl bg-white border border-navy/8 shadow-card overflow-hidden lift ${featured ? "md:col-span-2 md:row-span-2" : ""}`}>
      <button onClick={onOpen} className="relative block w-full cursor-pointer text-left">
        {isVideo && s.videoId ?
        <img src={`https://img.youtube.com/vi/${s.videoId}/maxresdefault.jpg`} alt={s.title} className="w-full object-cover" style={{ aspectRatio: featured ? "16/9" : "16/10" }} /> :

        <img src="uploads/Forge 1-104.jpg" alt={s.title} className="w-full object-cover" style={{ aspectRatio: featured ? "16/9" : "16/10" }} />
        }
        {isVideo &&
        <div className="absolute inset-0 flex items-center justify-center">
            <span className="w-16 h-16 rounded-full bg-gold text-navy flex items-center justify-center shadow-lg">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z" /></svg>
            </span>
          </div>
        }
        <div className="absolute top-4 left-4 inline-flex items-center text-[10px] font-display font-bold uppercase tracking-widest bg-white/95 text-navy px-2.5 py-1 rounded-full">
          {isVideo ? "Video" : "Article"} · {s.tag}
        </div>
      </button>
      <div className={`p-6 ${featured ? "md:p-8" : ""}`}>
        <h3 className={`font-display font-black text-navy ${featured ? "text-3xl" : "text-xl"} leading-snug`}>{s.title}</h3>
        <p className="mt-3 text-ink/70 leading-relaxed">{s.excerpt}</p>
        <div className="mt-5 flex items-center justify-between text-xs text-ink/55"><span>{s.author}</span><span>{s.readTime || s.duration}</span></div>
      </div>
    </article>);

}

/* ===== About ===== */
function AboutPage() {
  const [team, setTeam] = useState(null);
  // Phase 3.7: editable site content from Supabase
  const [cms, setCms] = useState({});
  useEffect(() => {
    if (window.cms && window.cms.getTeam) {
      window.cms.getTeam().then((t) => setTeam(t && t.length ? t : null));
    }
    if (window.cms && typeof window.cms.getSiteContent === "function") {
      window.cms.getSiteContent("about").then(setCms);
    }
  }, []);
  const hero = cms.hero || {};

  // Fallback to hardcoded team if Supabase unreachable / table empty
  const teamMembers = team || [
    { img: "uploads/PR  ISAAC-59 (1).jpg", name: "Pastor Isaac Mukisa Ssebakijje", role: "Founder & Executive Director" },
    { img: "uploads/Staff photos-1.jpg", name: "Hudson Tumusiime", role: "Communications Director" },
    { img: "uploads/FATHERS ARISE-153.jpg", name: "Pastor Richard Kyakoonye", role: "Nurturing Bonds Program Lead" },
    { img: "uploads/FATHERS ARISE MEETING-68.jpg", name: "Pastor Elisha Lutalo", role: "Be A Man Lead & Mobile Kanaabe Coordinator" }
  ];

  const heroImage = hero.image || "uploads/FATHERS ARISE MEETING-79.jpg";
  const heroTitle = hero.headline || "Who We Are";
  const heroEyebrow = hero.subhead || "About Us";
  const heroAlign = hero.align || "left";
  const heroAlignClass = heroAlign === "center" ? "text-center" : heroAlign === "right" ? "text-right" : "text-left";

  return (
    <div data-screen-label="02 About">
      {/* Hero */}
      <section data-cms-section="hero" data-cms-page="about" className="relative bg-navy text-white overflow-hidden">
        <div className="absolute inset-0">
          <img src={heroImage} alt="" className="w-full h-full object-cover" />
          <div className="absolute inset-0 bg-gradient-to-br from-navy/95 via-navy/80 to-navy/50" />
        </div>
        <div className={`relative max-w-[1280px] mx-auto px-4 sm:px-6 py-28 md:py-36 ${heroAlignClass}`}>
          <div className="text-xs font-display font-bold uppercase tracking-[0.25em] text-gold">{heroEyebrow}</div>
          <h1 className="mt-6 font-display font-black text-5xl sm:text-6xl md:text-7xl leading-[0.95]">{heroTitle}</h1>
        </div>
      </section>

      {/* The Story */}
      <section className="py-24 bg-white">
        <div className="max-w-[1200px] mx-auto px-4 sm:px-6 grid grid-cols-1 lg:grid-cols-12 gap-12 items-stretch">
          <div className="lg:col-span-7 space-y-6">
            <div className="text-xs font-display font-bold uppercase tracking-[0.25em] text-sky">The Story</div>
            <p className="text-lg text-ink/85 leading-relaxed">Every generation faces a crisis that defines whether it rises or falls. Ours is the crisis of the absent father. Across our communities, our schools, our churches, and our prisons, the evidence is undeniable: when fathers disappear, families collapse. When families collapse, communities crumble. When communities crumble, nations lose their way.</p>
            <p className="text-lg text-ink/85 leading-relaxed">Fathers Arise was not born from theory. It was born from the wreckage — from the pain of children who grew up without a father's voice, from the silence of men who never learned how to stay, from the emptiness of homes that have everything except a present father.</p>
            <p className="text-lg text-ink/85 leading-relaxed font-display font-medium text-navy">We are not a program. We are a movement. We are the sound of men rising from the ashes of abandonment, silence, and shame — and saying, <span className="text-gold">"It ends with me. The cycle breaks here."</span></p>
          </div>
          <div className="lg:col-span-5 flex">
            <img
              src="uploads/PR  ISAAC-72.jpg"
              alt="Pastor Isaac"
              className="w-full h-full rounded-3xl shadow-card"
              style={{ objectFit: "cover", objectPosition: "center top", minHeight: "100%" }}
            />
          </div>
        </div>
      </section>

      {/* The Crisis */}
      <section className="py-24 bg-navy text-white relative overflow-hidden">
        <div className="absolute inset-0 grid-bg opacity-10" />
        <div className="relative max-w-3xl mx-auto px-4 sm:px-6">
          <div className="text-xs font-display font-bold uppercase tracking-[0.3em] text-gold">The Crisis</div>
          <h2 className="mt-4 font-display font-black text-4xl md:text-6xl leading-[1.05]">The Crisis We Answer</h2>
          <p className="mt-8 text-lg md:text-xl text-white/90 leading-relaxed">
            Fatherlessness is not a private family matter. It is the single most destructive force in any society. A boy who grows up without a father is not just missing a parent — he is missing a mirror. He does not know what a man looks like up close. He has no model for how to lead, how to love, how to stay when things get hard. And the wound does not stay in the home. It walks into schools, into relationships, into workplaces, into prisons.
          </p>
        </div>
      </section>

      {/* The Founder */}
      <section className="py-24 bg-paper">
        <div className="max-w-[1200px] mx-auto px-4 sm:px-6 grid grid-cols-1 lg:grid-cols-12 gap-12 items-center">
          <div className="lg:col-span-5">
            <img
              src="uploads/PR  ISAAC-19.jpg"
              alt="Pastor Isaac Mukisa"
              className="w-full rounded-3xl shadow-card"
              style={{ aspectRatio: "4/5", objectFit: "cover", objectPosition: "center top" }}
            />
          </div>
          <div className="lg:col-span-7">
            <div className="text-xs font-display font-bold uppercase tracking-[0.25em] text-sky">The Founder</div>
            <h2 className="mt-4 font-display font-black text-4xl md:text-5xl text-navy leading-tight">Pastor Isaac Mukisa Ssebakijje</h2>
            <div className="mt-2 font-display font-bold text-gold uppercase tracking-wider text-sm">Founder & Executive Director</div>
            <p className="mt-6 text-lg text-ink/80 leading-relaxed">In August 2015, Isaac and Annabelle Mukisa established The Remnant Generation. Out of years of youth outreach — and a recurring question from supporters about boys, men, and fathers — Fathers Arise was born during the COVID-19 lockdown of 2020, when the crisis of fatherlessness became impossible to ignore.</p>
            <div className="mt-8 border-l-4 border-gold pl-6 py-3">
              <p className="font-quote italic text-2xl text-navy leading-snug">"Fathers Arise exists to restore men to their God-given role as present, responsible, and spiritually grounded fathers who lead their families and communities with integrity."</p>
            </div>
          </div>
        </div>
      </section>

      {/* The Team */}
      <section className="py-24 bg-white">
        <div className="max-w-[1280px] mx-auto px-4 sm:px-6">
          <SectionTitle eyebrow="The Team" title="The men behind the movement" center />
          <div className="mt-14 grid grid-cols-2 md:grid-cols-4 gap-6">
            {teamMembers.map((m, i) =>
            <article key={i} className="rounded-3xl bg-paper overflow-hidden lift shadow-card">
                <img
                  src={m.img}
                  alt={m.name}
                  className="w-full"
                  style={{ aspectRatio: "3/4", objectFit: "cover", objectPosition: "center top" }}
                />
                <div className="p-5">
                  <div className="font-display font-black text-navy text-base leading-tight">{m.name}</div>
                  <div className="mt-2 text-xs text-ink/60 leading-snug">{m.role}</div>
                </div>
              </article>
            )}
          </div>
        </div>
      </section>

      {/* Under TRG */}
      <section className="py-20 bg-paper">
        <div className="max-w-3xl mx-auto px-4 sm:px-6 text-center">
          <div className="text-xs font-display font-bold uppercase tracking-[0.3em] text-sky">Our Parent Organisation</div>
          <h3 className="mt-4 font-display font-black text-3xl md:text-4xl text-navy leading-tight">Under The Remnant Generation</h3>
          <p className="mt-6 text-lg text-ink/75 leading-relaxed">Fathers Arise operates under The Remnant Generation, a faith-based organisation committed to raising leaders and restoring families across Uganda and beyond.</p>
        </div>
      </section>
    </div>);

}

/* ---------- Categorized gallery (Stories page) ---------- */
const STORIES_GALLERIES = [
    { key: "sports", label: "Sports", emoji: "\u26bd", photos: ["uploads/sports/Father's Arise Football tournament-116.jpg", "uploads/sports/Father's Arise Football tournament-117.jpg", "uploads/sports/Father's Arise Football tournament-135.jpg", "uploads/sports/Father's Arise Football tournament-138.jpg", "uploads/sports/Father's Arise Football tournament-171.jpg", "uploads/sports/Father's Arise Football tournament-172.jpg", "uploads/sports/Father's Arise Football tournament-173.jpg", "uploads/sports/Father's Arise Football tournament-179.jpg", "uploads/sports/Father's Arise Football tournament-185.jpg", "uploads/sports/Father's Arise Football tournament-74.jpg", "uploads/sports/Father's Arise Football tournament-84.jpg", "uploads/sports/Father's Arise Football tournament-98.jpg", "uploads/sports/Father's Arise Football tournament-99.jpg"] },
    { key: "outreach", label: "Outreach", emoji: "\ud83d\ude90", photos: ["uploads/outreach/Fathers Arise-103_Beautify.jpg", "uploads/outreach/Fathers Arise-118_Beautify.jpg", "uploads/outreach/Fathers Arise-131_Beautify.jpg", "uploads/outreach/Fathers Arise-139_Beautify.jpg", "uploads/outreach/Fathers Arise-15_Beautify.jpg", "uploads/outreach/Fathers Arise-16.jpg", "uploads/outreach/Fathers Arise-201_Beautify (1).jpg", "uploads/outreach/Fathers Arise-201_Beautify.jpg", "uploads/outreach/Fathers Arise-246_Beautify.jpg", "uploads/outreach/Fathers Arise-251_Beautify.jpg", "uploads/outreach/Fathers Arise-25_Beautify.jpg", "uploads/outreach/Fathers Arise-282_Beautify.jpg", "uploads/outreach/Fathers Arise-30.jpg", "uploads/outreach/Fathers Arise-309_Beautify.jpg", "uploads/outreach/Fathers Arise-311_Beautify.jpg", "uploads/outreach/Fathers Arise-4.jpg", "uploads/outreach/Fathers Arise-52.jpg", "uploads/outreach/Fathers Arise-58_Beautify.jpg", "uploads/outreach/Fathers Arise-60.jpg", "uploads/outreach/Fathers Arise-96_Beautify.jpg"] },
    { key: "forge", label: "The Forge", emoji: "\ud83d\udd25", photos: ["uploads/forge/FATHERS ARISE MEETING-21.jpg", "uploads/forge/FATHERS ARISE MEETING-3.jpg", "uploads/forge/FATHERS ARISE MEETING-7.jpg", "uploads/forge/FATHERS ARISE MEETING-84.jpg", "uploads/forge/Forge 1-102.jpg", "uploads/forge/Forge 1-106.jpg", "uploads/forge/Forge 1-18.jpg", "uploads/forge/Forge 1-36.jpg", "uploads/forge/Forge 1-42.jpg", "uploads/forge/Forge 1-45.jpg", "uploads/forge/Forge 1-58.jpg", "uploads/forge/Forge 1-64.jpg", "uploads/forge/Forge 1-71.jpg", "uploads/forge/Forge 1-8.jpg", "uploads/forge/Forge 1-83.jpg", "uploads/forge/Forge 1-85.jpg", "uploads/forge/Forge 1-95.jpg", "uploads/forge/Forge 1-96.jpg"] },
    { key: "breakfast", label: "Father's Breakfast", emoji: "\ud83c\udf73", photos: ["uploads/breakfast/FA--326.jpg", "uploads/breakfast/FA--328.jpg", "uploads/breakfast/FA-09310 (2).jpg", "uploads/breakfast/FA-09319 (1).jpg", "uploads/breakfast/FA-09334.jpg", "uploads/breakfast/FA-09340.jpg", "uploads/breakfast/FATHERS ARISE-135.jpg", "uploads/breakfast/FATHERS ARISE-208.jpg", "uploads/breakfast/FATHERS ARISE-213.jpg", "uploads/breakfast/FATHERS ARISE-226.jpg", "uploads/breakfast/FATHERS ARISE-232.jpg", "uploads/breakfast/FATHERS ARISE-237.jpg", "uploads/breakfast/FATHERS ARISE-270.jpg", "uploads/breakfast/FATHERS ARISE-275.jpg", "uploads/breakfast/FATHERS ARISE-295.jpg", "uploads/breakfast/FATHERS ARISE-304.jpg", "uploads/breakfast/FATHERS ARISE-308.jpg", "uploads/breakfast/FATHERS ARISE-42.jpg", "uploads/breakfast/FATHERS ARISE-90.jpg", "uploads/breakfast/TRG_Father_sBreakfast1.jpg", "uploads/breakfast/TRG_Father_sBreakfast10.jpg", "uploads/breakfast/TRG_Father_sBreakfast110.jpg", "uploads/breakfast/TRG_Father_sBreakfast115.jpg", "uploads/breakfast/TRG_Father_sBreakfast118.jpg", "uploads/breakfast/TRG_Father_sBreakfast121.jpg", "uploads/breakfast/TRG_Father_sBreakfast130.jpg", "uploads/breakfast/TRG_Father_sBreakfast156.jpg", "uploads/breakfast/TRG_Father_sBreakfast161.jpg", "uploads/breakfast/TRG_Father_sBreakfast162.jpg", "uploads/breakfast/TRG_Father_sBreakfast164.jpg", "uploads/breakfast/TRG_Father_sBreakfast20.jpg", "uploads/breakfast/TRG_Father_sBreakfast24.jpg", "uploads/breakfast/TRG_Father_sBreakfast27.jpg", "uploads/breakfast/TRG_Father_sBreakfast29.jpg", "uploads/breakfast/TRG_Father_sBreakfast33.jpg", "uploads/breakfast/TRG_Father_sBreakfast41.jpg", "uploads/breakfast/TRG_Father_sBreakfast76.jpg", "uploads/breakfast/TRG_Father_sBreakfast90.jpg", "uploads/breakfast/prof 1.jpg", "uploads/breakfast/prof10 -grad.jpg", "uploads/breakfast/prof2.jpg", "uploads/breakfast/prof4.jpg", "uploads/breakfast/prof5.jpg", "uploads/breakfast/prof6.jpg", "uploads/breakfast/prof8.jpg"] }
  ];

function CategorizedGallery({ onOpen }) {
  const [activeCategory, setActiveCategory] = useState(STORIES_GALLERIES[0].key);
  const current = STORIES_GALLERIES.find(g => g.key === activeCategory) || STORIES_GALLERIES[0];

  return (
    <section className="py-20 bg-white">
      <div className="max-w-[1280px] mx-auto px-4 sm:px-6">
        <SectionTitle eyebrow="Gallery" title="From the field" center />

        {/* Category tabs */}
        <div className="mt-10 flex flex-wrap justify-center gap-2">
          {STORIES_GALLERIES.map((g) => (
            <button
              key={g.key}
              onClick={() => setActiveCategory(g.key)}
              className={`px-5 py-2.5 rounded-full text-sm font-display font-bold uppercase tracking-wider transition-colors ${
                activeCategory === g.key
                  ? "bg-navy text-white"
                  : "bg-white border border-navy/15 text-ink/70 hover:border-navy/40 hover:text-navy"
              }`}
            >
              <span className="mr-1.5">{g.emoji}</span> {g.label}
              <span className="ml-2 text-[10px] opacity-60">{g.photos.length}</span>
            </button>
          ))}
        </div>

        {/* Photo grid for the active category */}
        <div className="mt-10 grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
          {current.photos.map((src, i) => (
            <button
              key={src}
              onClick={() => onOpen(current.photos, i)}
              className="rounded-2xl overflow-hidden bg-paper cursor-zoom-in group block w-full"
              aria-label={`Open photo ${i + 1} of ${current.photos.length}`}
            >
              <img
                src={src}
                alt=""
                loading="lazy"
                className="w-full object-cover transition-transform group-hover:scale-105"
                style={{ aspectRatio: "1/1" }}
              />
            </button>
          ))}
        </div>

        <div className="mt-6 text-center text-xs text-ink/55 font-display uppercase tracking-widest">
          Showing {current.photos.length} photos · click any to enlarge
        </div>
      </div>
    </section>
  );
}

/* ---------- Lightbox for stories videos + gallery images ---------- */
function Lightbox({ item, onClose }) {
  // For gallery-kind, track current index for prev/next navigation
  const [galleryIndex, setGalleryIndex] = useState(item.index || 0);

  const isGallery = item.kind === "gallery";
  const total = isGallery ? item.photos.length : 0;
  const currentSrc = isGallery ? item.photos[galleryIndex] : null;

  const goPrev = (e) => {
    if (e) e.stopPropagation();
    setGalleryIndex((galleryIndex - 1 + total) % total);
  };
  const goNext = (e) => {
    if (e) e.stopPropagation();
    setGalleryIndex((galleryIndex + 1) % total);
  };

  // Arrow-key navigation
  useEffect(() => {
    if (!isGallery) return;
    const onKey = (e) => {
      if (e.key === "ArrowLeft") goPrev();
      else if (e.key === "ArrowRight") goNext();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  });

  return (
    <div
      className="fixed inset-0 z-[200] bg-black/85 backdrop-blur-sm flex items-center justify-center p-4"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
    >
      <button
        onClick={onClose}
        aria-label="Close"
        className="absolute top-4 right-4 w-11 h-11 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition-colors z-10"
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
          <path d="M6 6l12 12M6 18L18 6" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" />
        </svg>
      </button>

      {/* Prev / Next arrows for gallery mode */}
      {isGallery && total > 1 && (
        <>
          <button
            onClick={goPrev}
            aria-label="Previous"
            className="absolute left-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition-colors z-10"
          >
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
              <path d="M15 18l-6-6 6-6" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
          <button
            onClick={goNext}
            aria-label="Next"
            className="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition-colors z-10"
          >
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
              <path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
        </>
      )}

      <div onClick={(e) => e.stopPropagation()} className="max-w-6xl w-full">
        {item.kind === "video" ? (
          <div className="w-full rounded-2xl overflow-hidden shadow-2xl bg-black" style={{ aspectRatio: "16/9" }}>
            <iframe
              src={`https://www.youtube.com/embed/${item.videoId}?autoplay=1&rel=0`}
              title={item.title || "Fathers Arise video"}
              frameBorder="0"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
              referrerPolicy="strict-origin-when-cross-origin"
              allowFullScreen
              className="w-full h-full"
            />
          </div>
        ) : isGallery ? (
          <img src={currentSrc} alt="" className="max-h-[85vh] w-auto mx-auto rounded-xl shadow-2xl" />
        ) : (
          <img src={item.src} alt={item.title || ""} className="max-h-[85vh] w-auto mx-auto rounded-xl shadow-2xl" />
        )}

        {isGallery && (
          <div className="mt-4 text-center text-white/70 text-sm font-display tracking-widest">
            {galleryIndex + 1} / {total}
          </div>
        )}

        {(item.title || item.author) && !isGallery && (
          <div className="mt-4 text-center text-white/85">
            {item.title && <div className="font-display font-bold text-lg">{item.title}</div>}
            {item.author && <div className="text-sm text-white/65 mt-1">{item.author}</div>}
          </div>
        )}
      </div>
    </div>
  );
}

window.StoriesPage = StoriesPage;
window.AboutPage = AboutPage;
