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

/* =============================================================================
 * Mission carousel — S141 v19 Phase v19-7 (CEO directive D2 + D22).
 *
 * Mixed media carousel: video loops + still images, auto-advance with hover-pause,
 * mobile swipe, lazy-load all but first.
 *
 * Provisional content (v19-7a): reuses the 5 existing Azure Blob assets that
 * thematically align with the Mission narrative (cassava field, intergen table,
 * Montréal kitchen, cassava prep, festival ambiance) PLUS 2 hero stills as
 * still slides. Far stronger than the dashed-border placeholder.
 *
 * Full 8K Mission-specific generation (v19-7b) replaces these provisional URLs
 * once the 2 new Veo loops + 4 new Imagen 4 stills land:
 *   - wiin-mission-brossard-garden-loop.mp4 (women + youth, golden hour)
 *   - wiin-mission-cassava-hands-loop.mp4 (close-up, ASMR pace)
 *   - wiin-mission-brossard-garden-still.jpg
 *   - wiin-mission-classroom-still.jpg
 *   - wiin-mission-jcm-ambiance-still.jpg
 *   - wiin-mission-katia-atelier-still.jpg
 *
 * Quality bar: 8K realistic professional + audacious + sleek + engaging (D22).
 * ===========================================================================*/

// S141 v19-7b — Mission-specific 8K Imagen 4 Ultra stills + Veo 3.1 loops.
// Generated 2026-05-14 via scripts/wiin_mission_carousel_generate.py.
// Stills (4): generated + uploaded.
// Loops (2): TBD — pending Veo 3.1 generation completion (10-15 min async).
//   The two loop slides at the bottom will swap to the actual mp4 SAS URLs once
//   the script writes them out; until then they render the still version of the
//   same scene from Imagen 4 (graceful fallback).
const MISSION_CAROUSEL_SLIDES = [
  {
    kind: "image",
    src: "https://stn8ndigigle.blob.core.windows.net/brand-assets/wiin-canada/generated/wiin-mission-brossard-garden-still.jpg?se=2027-05-14T23%3A59%3A00Z&sp=r&spr=https&sv=2026-02-06&sr=b&sig=7N6a4FfFqjnofTcM1AdQoseT7jpKRDGjwcUMcnb7Rms%3D",
    captionFr: "Jardins communautaires · biodiversité urbaine · transition écologique",
    captionEn: "Community gardens · urban biodiversity · ecological transition",
  },
  {
    kind: "image",
    src: "https://stn8ndigigle.blob.core.windows.net/brand-assets/wiin-canada/generated/wiin-mission-classroom-still.jpg?se=2027-05-14T23%3A59%3A00Z&sp=r&spr=https&sv=2026-02-06&sr=b&sig=FmF%2Bzrtq1DWE5JGigps0gpIWABZovXeP%2B6GT4xRhkwA%3D",
    captionFr: "Éducation et autonomisation · cohorte diaspora et alliés",
    captionEn: "Education and empowerment · diaspora cohort and allies",
  },
  {
    kind: "image",
    src: "https://stn8ndigigle.blob.core.windows.net/brand-assets/wiin-canada/generated/wiin-mission-jcm-ambiance-still.jpg?se=2027-05-14T23%3A59%3A00Z&sp=r&spr=https&sv=2026-02-06&sr=b&sig=mksg2UyVEa32EKssdEDm6920vb2SBEk3hZ3TqWL6mxc%3D",
    captionFr: "Table solidaire · diaspora et hospitalité partagées",
    captionEn: "Solidarity table · shared diaspora and hospitality",
  },
  {
    kind: "image",
    src: "https://stn8ndigigle.blob.core.windows.net/brand-assets/wiin-canada/generated/wiin-mission-katia-atelier-still.jpg?se=2027-05-14T23%3A59%3A00Z&sp=r&spr=https&sv=2026-02-06&sr=b&sig=VoGWTdYGVGo2cQ1SEZEKdDDVbRZdiAfI%2B75i2hOdx4o%3D",
    captionFr: "Savoir-faire culinaire · transmission ethno-culturelle",
    captionEn: "Culinary know-how · ethno-cultural transmission",
  },
  // Veo 3.1 loops — Mission-specific cinematic loops generated 2026-05-14.
  {
    kind: "video",
    src: "https://stn8ndigigle.blob.core.windows.net/brand-assets/wiin-canada/generated/wiin-mission-brossard-garden-loop.mp4?se=2027-05-14T23%3A59%3A00Z&sp=r&spr=https&sv=2026-02-06&sr=b&sig=Y4Uh1a0DmMEbgag0sbuoHgcEffvSXF%2BLh4h4vNIiCmo%3D",
    captionFr: "Jardins en mouvement · femmes et jeunes · lumière dorée",
    captionEn: "Gardens in motion · women and youth · golden hour",
  },
  {
    kind: "video",
    src: "https://stn8ndigigle.blob.core.windows.net/brand-assets/wiin-canada/generated/wiin-mission-cassava-hands-loop.mp4?se=2027-05-14T23%3A59%3A00Z&sp=r&spr=https&sv=2026-02-06&sr=b&sig=nJjxPG%2BtItMsymLfiAP9aCqInjO70LLMjGnJKOXPRbI%3D",
    captionFr: "Mains qui transforment · gestes de mémoire vivante",
    captionEn: "Hands transforming · gestures of living memory",
  },
];

function MissionCarousel({ lang, ariaLabel, slotKey }) {
  const [activeIdx, setActiveIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const containerRef = useRef(null);
  const touchStartX = useRef(null);
  const isFr = lang === "fr";
  const slides = MISSION_CAROUSEL_SLIDES;
  const total = slides.length;

  const advance = useCallback(() => {
    setActiveIdx((i) => (i + 1) % total);
  }, [total]);

  const goPrev = () => setActiveIdx((i) => (i - 1 + total) % total);
  const goNext = () => setActiveIdx((i) => (i + 1) % total);

  // Auto-advance every 5s when not paused
  useEffect(() => {
    if (paused) return;
    const id = setInterval(advance, 5000);
    return () => clearInterval(id);
  }, [paused, advance]);

  // Mobile swipe handlers
  const onTouchStart = (e) => { touchStartX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchStartX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchStartX.current;
    if (Math.abs(dx) > 50) {
      if (dx > 0) goPrev(); else goNext();
    }
    touchStartX.current = null;
  };

  // Keyboard handler (S141 v23-lite F3): Space toggles pause; Arrow keys navigate.
  const onKeyDown = (e) => {
    if (e.code === "Space") {
      e.preventDefault();
      setPaused((p) => !p);
    } else if (e.code === "ArrowLeft") {
      e.preventDefault();
      goPrev();
    } else if (e.code === "ArrowRight") {
      e.preventDefault();
      goNext();
    }
  };

  return (
    <div
      ref={containerRef}
      className="mission-carousel"
      role="region"
      aria-roledescription={isFr ? "carrousel" : "carousel"}
      aria-label={ariaLabel || (isFr ? "Carrousel mission WIIN" : "WIIN mission carousel")}
      aria-live="polite"
      tabIndex={0}
      onKeyDown={onKeyDown}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      onFocus={() => setPaused(true)}
      onBlur={() => setPaused(false)}
      onTouchStart={onTouchStart}
      onTouchEnd={onTouchEnd}
      data-slot={slotKey || "mission-carousel"}
      data-paused={paused ? "true" : "false"}
    >
      <div className="mission-carousel-stage" style={{ aspectRatio: "16 / 10" }}>
        {slides.map((s, i) => {
          const isActive = i === activeIdx;
          const cap = isFr ? s.captionFr : s.captionEn;
          return (
            <div
              key={i}
              className={`mission-carousel-slide${isActive ? " is-active" : ""}`}
              aria-hidden={!isActive}
            >
              {s.kind === "video" ? (
                <video
                  src={isActive || i === (activeIdx + 1) % total ? s.src : undefined}
                  poster={s.poster}
                  autoPlay={isActive}
                  muted
                  loop
                  playsInline
                  preload={i === 0 ? "metadata" : "none"}
                  aria-label={cap}
                  className="mission-carousel-media"
                />
              ) : (
                <img
                  src={s.src}
                  alt={cap}
                  loading={i === 0 ? "eager" : "lazy"}
                  className="mission-carousel-media"
                />
              )}
              <div className="mission-carousel-caption">
                <span className="mission-carousel-caption-eyebrow">{isFr ? "Mission · phase 1 · 2026" : "Mission · phase 1 · 2026"}</span>
                <span className="mission-carousel-caption-text">{cap}</span>
              </div>
            </div>
          );
        })}
      </div>

      <div className="mission-carousel-controls">
        <button className="mission-carousel-arrow" onClick={goPrev} aria-label={isFr ? "Précédent" : "Previous"}>‹</button>
        <div className="mission-carousel-dots" role="tablist">
          {slides.map((_, i) => (
            <button
              key={i}
              className={`mission-carousel-dot${i === activeIdx ? " is-active" : ""}`}
              role="tab"
              aria-selected={i === activeIdx}
              aria-label={`${isFr ? "Diapositive" : "Slide"} ${i + 1}/${total}`}
              onClick={() => setActiveIdx(i)}
            />
          ))}
        </div>
        <button className="mission-carousel-arrow" onClick={goNext} aria-label={isFr ? "Suivant" : "Next"}>›</button>
      </div>
    </div>
  );
}

window.MissionCarousel = MissionCarousel;
