// hero.jsx — Cinematic immersive Hero, fully reimagined
const { useState: _useState, useEffect: _useEffect, useRef: _useRef, useMemo } = React;

// ---------- Mascot (Burkina flag head + 3D body) ----------
// Tête animée :
//  - Idle : balance gauche/droite toutes les 5s (animation CSS)
//  - Mouse-aware : suit légèrement la souris (±8° de rotation max)
//  - Hover : pause idle pour laisser le tracking souris dominer
//
// PNG splits :
//  - assets/mascot-body.png : corps en costume + bras + ticket Faso Travel
//  - assets/mascot-head.png : tête loupe drapeau BF (avec manche)
function Mascot({ size = 380 }) {
  const containerRef = React.useRef(null);
  const [tilt, setTilt] = React.useState({ rot: 0, y: 0 });
  const [active, setActive] = React.useState(false);

  React.useEffect(() => {
    // Respect prefers-reduced-motion : pas de tracking souris si l'user
    // demande des animations réduites (accessibilité).
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    let raf = 0;
    let target = { rot: 0, y: 0 };
    const handle = (e) => {
      const rect = containerRef.current?.getBoundingClientRect();
      if (!rect) return;
      const cx = rect.left + rect.width / 2;
      const cy = rect.top + rect.height * 0.25; // ancre sur la zone tête (pas centre du body)
      const dx = (e.clientX - cx) / Math.max(400, window.innerWidth);
      const dy = (e.clientY - cy) / Math.max(400, window.innerHeight);
      target = {
        rot: Math.max(-1, Math.min(1, dx * 2)) * 8,
        y: Math.max(-1, Math.min(1, dy * 2)) * 4,
      };
      if (!raf) {
        raf = requestAnimationFrame(() => {
          setTilt(target);
          raf = 0;
        });
      }
    };
    window.addEventListener('mousemove', handle);
    return () => {
      window.removeEventListener('mousemove', handle);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  // translate3d force la couche GPU (compositor-only) → animation fluide
  // sans repaint. Cohérent avec @keyframes mascot-head-idle dans styles.css.
  const headStyle = {
    transform: `translate3d(-50%, ${tilt.y.toFixed(2)}px, 0) rotate(${tilt.rot.toFixed(2)}deg)`,
  };

  return (
    <div
      ref={containerRef}
      className={`mascot${active ? ' is-active' : ''}`}
      style={{ width: size, maxWidth: '100%' }}
      onMouseEnter={() => setActive(true)}
      onMouseLeave={() => setActive(false)}
      aria-label="Mascotte FasoTravel — Burkina explorateur"
    >
      <img
        src="./assets/mascot-body.png"
        alt=""
        className="mascot-body"
        draggable={false}
      />
      <img
        src="./assets/mascot-head.png"
        alt="Mascotte FasoTravel"
        className="mascot-head"
        style={headStyle}
        draggable={false}
      />
    </div>
  );
}

// ---------- Cinematic bus ----------
function DrivingBus() {
  return (
    <div className="bus-travel" aria-hidden>
      <div className="bus-shake">
        <svg width="280" height="140" viewBox="0 0 280 140" style={{ display: "block" }}>
          <defs>
            <linearGradient id="bus-body" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor="#fff7e8"/>
              <stop offset="0.45" stopColor="#e9d8b3"/>
              <stop offset="1" stopColor="#7d6a48"/>
            </linearGradient>
            <linearGradient id="bus-stripe" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0" stopColor="#dc2626"/>
              <stop offset="0.5" stopColor="#f59e0b"/>
              <stop offset="1" stopColor="#16a34a"/>
            </linearGradient>
            <radialGradient id="headlight" cx="0.5" cy="0.5" r="0.5">
              <stop offset="0" stopColor="#fff7d6"/>
              <stop offset="0.6" stopColor="#fde68a" stopOpacity="0.8"/>
              <stop offset="1" stopColor="#fde68a" stopOpacity="0"/>
            </radialGradient>
            <filter id="bus-glow" x="-50%" y="-50%" width="200%" height="200%">
              <feGaussianBlur stdDeviation="3"/>
            </filter>
          </defs>
          <g opacity="0.8">
            <ellipse cx="270" cy="92" rx="64" ry="11" fill="url(#headlight)" filter="url(#bus-glow)"/>
            <path d="M250 88 L370 64 L370 116 L250 96 Z" fill="url(#headlight)" opacity="0.32"/>
          </g>
          <rect x="22" y="38" width="226" height="64" rx="14" fill="url(#bus-body)" stroke="#4a3d28" strokeWidth="0.7"/>
          <rect x="22" y="86" width="226" height="5" fill="url(#bus-stripe)"/>
          <g fill="#0a1015" stroke="#1f1812" strokeWidth="0.4">
            <rect x="32" y="46" width="30" height="30" rx="3"/>
            <rect x="68" y="46" width="30" height="30" rx="3"/>
            <rect x="104" y="46" width="30" height="30" rx="3"/>
            <rect x="140" y="46" width="30" height="30" rx="3"/>
            <rect x="176" y="46" width="30" height="30" rx="3"/>
            <rect x="212" y="46" width="30" height="30" rx="3"/>
          </g>
          <g fill="#fff8e0" opacity="0.5">
            <rect x="34" y="48" width="6" height="26" rx="1"/>
            <rect x="70" y="48" width="6" height="26" rx="1"/>
            <rect x="106" y="48" width="6" height="26" rx="1"/>
            <rect x="142" y="48" width="6" height="26" rx="1"/>
            <rect x="178" y="48" width="6" height="26" rx="1"/>
            <rect x="214" y="48" width="6" height="26" rx="1"/>
          </g>
          <text x="135" y="32" textAnchor="middle" fill="#1f1812" fontSize="7" fontFamily="var(--font-mono)" fontWeight="700" letterSpacing="2">FASOTRAVEL</text>
          <rect x="120" y="92" width="34" height="6" rx="1" fill="#fbbf24"/>
          <text x="137" y="97" textAnchor="middle" fill="#1f1812" fontSize="4" fontWeight="700" fontFamily="var(--font-mono)">11 BF 226</text>
          <rect x="246" y="70" width="6" height="20" fill="#1f1812"/>
          <circle cx="250" cy="76" r="2.7" fill="#fff8e0"/>
          <circle cx="250" cy="76" r="4.5" fill="#fff8e0" opacity="0.4" filter="url(#bus-glow)"/>
          <rect x="241" y="34" width="4" height="6" fill="#4a3d28"/>
          <g transform="translate(60 108)">
            <circle r="14" fill="#0e0a06" stroke="#3d362b" strokeWidth="1"/>
            <circle r="6.5" fill="#1f1812"/>
            <g className="wheel-spin">
              <rect x="-1" y="-12" width="2" height="9" fill="#5c4a31"/>
              <rect x="-1" y="3" width="2" height="9" fill="#5c4a31"/>
              <rect x="-12" y="-1" width="9" height="2" fill="#5c4a31"/>
              <rect x="3" y="-1" width="9" height="2" fill="#5c4a31"/>
            </g>
          </g>
          <g transform="translate(208 108)">
            <circle r="14" fill="#0e0a06" stroke="#3d362b" strokeWidth="1"/>
            <circle r="6.5" fill="#1f1812"/>
            <g className="wheel-spin">
              <rect x="-1" y="-12" width="2" height="9" fill="#5c4a31"/>
              <rect x="-1" y="3" width="2" height="9" fill="#5c4a31"/>
              <rect x="-12" y="-1" width="9" height="2" fill="#5c4a31"/>
              <rect x="3" y="-1" width="9" height="2" fill="#5c4a31"/>
            </g>
          </g>
          <ellipse cx="135" cy="128" rx="120" ry="6" fill="#000" opacity="0.5" filter="url(#bus-glow)"/>
        </svg>
      </div>
      <div className="bus-dust">
        {Array.from({ length: 12 }).map((_, i) => (
          <span key={i} style={{ animationDelay: `${i * 0.14}s` }}/>
        ))}
      </div>
    </div>
  );
}

// ---------- Birds ----------
function Birds() {
  return (
    <div className="hero-birds" aria-hidden>
      {Array.from({ length: 5 }).map((_, i) => (
        <svg key={i} width="40" height="14" viewBox="0 0 40 14" style={{
          position: "absolute",
          top: `${10 + i * 6}%`,
          animation: `bird-fly ${22 + i * 4}s linear infinite`,
          animationDelay: `${i * -5}s`,
        }}>
          <g className="bird-flap">
            <path d="M2 7 Q10 1 18 7 Q26 1 34 7" stroke="#1a1612" strokeWidth="1.2" fill="none" opacity="0.7"/>
          </g>
        </svg>
      ))}
    </div>
  );
}

// ---------- Sun rays ----------
function SunRays() {
  return (
    <svg className="hero-rays" preserveAspectRatio="none" viewBox="0 0 1600 900" aria-hidden>
      <defs>
        <linearGradient id="ray-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#fbbf24" stopOpacity="0.0"/>
          <stop offset="0.4" stopColor="#fbbf24" stopOpacity="0.18"/>
          <stop offset="1" stopColor="#fbbf24" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {Array.from({ length: 9 }).map((_, i) => {
        const cx = 200 + i * 160;
        return (
          <path key={i} d={`M${cx} 0 L${cx - 80} 900 L${cx + 80} 900 Z`}
                fill="url(#ray-grad)" opacity="0.5">
            <animate attributeName="opacity" values="0.4;0.95;0.4" dur={`${6 + i}s`} repeatCount="indefinite"/>
          </path>
        );
      })}
    </svg>
  );
}

// ---------- Floating dust motes ----------
function HeroMotes() {
  const motes = useMemo(() => Array.from({ length: 28 }).map((_, i) => ({
    x: ((i * 37) + (i*i*7)) % 100,
    y: ((i * 53) + 13) % 100,
    s: 1 + (i % 4) * 0.6,
    dur: 12 + (i % 8) * 1.8,
    del: (i % 5) * -2.5,
  })), []);
  return (
    <div className="hero-motes" aria-hidden>
      {motes.map((m, i) => (
        <span key={i} style={{
          left: `${m.x}%`, top: `${m.y}%`,
          width: m.s, height: m.s,
          animationDuration: `${m.dur}s`,
          animationDelay: `${m.del}s`,
        }}/>
      ))}
    </div>
  );
}

// ---------- HeroScene ----------
// Background : photo réelle "Burkina Faso sur la carte d'Afrique de l'Ouest"
// fournie par l'utilisateur (assets/burkina-map.jpg). Les couches SVG
// précédentes (montagnes, sun, étoiles) sont conservées en superposition très
// atténuée pour la profondeur, mais ne dominent plus la scène.
function HeroScene() {
  const y = useScrollY();
  const px = (mult) => Math.min(y * mult, 400);
  return (
    <div className="hero-scene" aria-hidden>
      {/* Photo de fond — Burkina Faso planté sur la carte Afrique de l'Ouest */}
      <div
        className="hero-photo-bg"
        style={{ backgroundImage: "url('assets/burkina-map.jpg')" }}
      />
      {/* Overlay sombre dégradé pour garantir la lisibilité du texte par-dessus */}
      <div className="hero-photo-overlay"/>

      {/* Sun rays */}
      <SunRays/>

      {/* Stars */}
      <svg className="hero-stars" preserveAspectRatio="none" aria-hidden>
        {Array.from({ length: 80 }).map((_, i) => {
          const x = (i * 31 + (i*i)%17) % 100;
          const yy = ((i * 23) % 60);
          const r = 0.4 + ((i % 6) * 0.22);
          const op = 0.4 + ((i * 11) % 6) * 0.08;
          return <circle key={i} cx={`${x}%`} cy={`${yy}%`} r={r} fill="#f4ece0" opacity={op}>
            <animate attributeName="opacity" values={`${op};${op*0.3};${op}`} dur={`${2 + (i % 5)}s`} repeatCount="indefinite"/>
          </circle>;
        })}
      </svg>

      {/* Shooting stars */}
      {[0,1,2,3].map(i => (
        <div key={i} className="shooting-star" style={{
          top: `${10 + i * 15}%`,
          left: `${-20 - i * 10}%`,
          animationDelay: `${i * 4}s`,
        }}/>
      ))}

      {/* Sun disk */}
      <div className="hero-sun" style={{ transform: `translateY(${px(0.25)}px)` }}/>

      {/* Distant mountain layer */}
      <svg className="hero-mountains-far" preserveAspectRatio="none" viewBox="0 0 1600 320"
           style={{ transform: `translateY(${px(0.18)}px)` }}>
        <path d="M0 280 L80 220 L160 250 L240 180 L340 230 L440 160 L560 220 L680 190 L800 240 L920 170 L1040 220 L1180 180 L1300 230 L1420 200 L1520 230 L1600 220 L1600 320 L0 320 Z"
              fill="var(--mountain-far)"/>
      </svg>

      {/* Mid mountain layer */}
      <svg className="hero-mountains-mid" preserveAspectRatio="none" viewBox="0 0 1600 280"
           style={{ transform: `translateY(${px(0.32)}px)` }}>
        <path d="M0 260 L120 180 L240 230 L360 130 L480 200 L600 170 L720 220 L860 150 L980 200 L1120 130 L1240 200 L1360 160 L1480 200 L1600 180 L1600 280 L0 280 Z"
              fill="var(--mountain-mid)"/>
      </svg>

      {/* Near mountain layer */}
      <svg className="hero-mountains-near" preserveAspectRatio="none" viewBox="0 0 1600 220"
           style={{ transform: `translateY(${px(0.5)}px)` }}>
        <path d="M0 220 Q200 130 400 170 T800 150 T1200 170 T1600 155 L1600 220 L0 220 Z"
              fill="var(--mountain-near)"/>
      </svg>

      {/* Atmospheric fog bands */}
      <div className="hero-fog-band"/>
      <div className="hero-fog-band hero-fog-band-2"/>

      <Birds/>
      <HeroMotes/>

      {/* Horizon road + bus — épuré : route en perspective sobre, plus de
          traînée LED RGB qui traversait la scène. La voie centrale guide
          juste l'œil vers le point de fuite à l'horizon. */}
      <div className="hero-horizon">
        <DrivingBus/>
        <svg className="hero-road" preserveAspectRatio="none" viewBox="0 0 1600 300">
          <defs>
            <linearGradient id="road-grad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor="var(--road-top)"/>
              <stop offset="1" stopColor="var(--road-bot)"/>
            </linearGradient>
            <linearGradient id="ground-fade" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor="#3d2414" stopOpacity="0"/>
              <stop offset="1" stopColor="#1a0e0a" stopOpacity="0.6"/>
            </linearGradient>
          </defs>
          {/* Sol terre rouge sahélienne — gradient simple, pas de bandes */}
          <path d="M0 130 Q400 115 800 125 T1600 130 L1600 300 L0 300 Z" fill="url(#road-grad)"/>
          <path d="M0 130 Q400 115 800 125 T1600 130 L1600 300 L0 300 Z" fill="url(#ground-fade)"/>
          {/* Bande de route en perspective vers le point de fuite */}
          <path d="M720 300 L788 130 L812 130 L880 300 Z" fill="#1a1410" opacity="0.85"/>
          {/* Lignes blanches discontinues centrales (vraie marque routière) */}
          <g fill="#e8d9b8" opacity="0.7">
            <rect x="797" y="270" width="6" height="22"/>
            <rect x="796" y="225" width="8" height="18"/>
            <rect x="795" y="190" width="10" height="14"/>
            <rect x="795" y="160" width="10" height="10"/>
            <rect x="797" y="138" width="6" height="6"/>
          </g>
          {/* Quelques arbres sahéliens éparpillés (plus discrets, moins nombreux) */}
          <g fill="#1a1410" opacity="0.85">
            <g transform="translate(180 165)">
              <rect x="-1.5" y="0" width="3" height="32" rx="1"/>
              <ellipse cx="0" cy="-2" rx="14" ry="6"/>
            </g>
            <g transform="translate(1420 168)">
              <rect x="-1.5" y="0" width="3" height="30" rx="1"/>
              <ellipse cx="0" cy="-3" rx="16" ry="7"/>
            </g>
            <g transform="translate(420 178)">
              <rect x="-1" y="0" width="2" height="22" rx="1"/>
              <ellipse cx="0" cy="-1" rx="10" ry="4"/>
            </g>
            <g transform="translate(1180 178)">
              <rect x="-1" y="0" width="2" height="22" rx="1"/>
              <ellipse cx="0" cy="-1" rx="10" ry="4"/>
            </g>
          </g>
        </svg>
      </div>

      <div className="hero-vignette"/>
    </div>
  );
}

// Salutations rotatives — incarne l'identité culturelle dès le 1er regard
function GreetingRotator({ greetings }) {
  const [idx, setIdx] = _useState(0);
  _useEffect(() => {
    if (!greetings || greetings.length < 2) return;
    const id = setInterval(() => setIdx((i) => (i + 1) % greetings.length), 2400);
    return () => clearInterval(id);
  }, [greetings]);
  if (!greetings || greetings.length === 0) return null;
  const cur = greetings[idx];
  return (
    <div className="hero-greetings" aria-live="polite">
      <span key={idx} className="hero-greetings-text">
        <span className="hero-greetings-word">{cur.text}</span>
        <span className="hero-greetings-lang">— {cur.lang}</span>
      </span>
    </div>
  );
}

function Hero({ t, onNotify }) {
  const heroLogoParallax = useParallax(-0.06);
  const heroSceneParallax = useParallax(0.12);
  return (
    <section id="hero" className="section snap hero-section" style={{ minHeight: "100vh", padding: "0", display: "flex", alignItems: "center", position: "relative", overflow: "hidden" }}>
      <div ref={heroSceneParallax} style={{ position: "absolute", inset: 0, zIndex: 1, willChange: "transform" }}>
        <HeroScene />
      </div>

      {/* LogoCoin animé (spin + halo) — déplacé en floating top-right pour
       * laisser le Mascot prendre la place principale du hero sans perdre
       * l'animation signature du logo. Pointer-events:none pour ne pas
       * bloquer les interactions avec ce qui est dessous. */}
      <div className="hero-logo-floating" aria-hidden>
        <LogoCoin size={140}/>
      </div>

      <div className="container" style={{ position: "relative", zIndex: 3, padding: "140px 48px 60px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.25fr 1fr", gap: "60px", alignItems: "center" }} className="hero-grid">
          <div>
            <Reveal delay={100}>
              <div className="eyebrow" style={{ marginBottom: 24 }}>
                <FlagDot size={10} />
                <span>{t.hero.eyebrow}</span>
              </div>
            </Reveal>
            <Reveal delay={150}>
              <GreetingRotator greetings={t.hero.greetings}/>
            </Reveal>
            <Reveal delay={200} variant="blur">
              <h1 className="display" style={{ color: "var(--cream)" }}>
                {t.hero.title1}
                <br/>
                <span style={{
                  fontStyle: "italic",
                  background: "linear-gradient(92deg, #f59e0b 0%, #fbbf24 40%, #22c55e 100%)",
                  WebkitBackgroundClip: "text", backgroundClip: "text", color: "transparent"
                }}>
                  {t.hero.title2}
                </span>
              </h1>
            </Reveal>
            <Reveal delay={400}>
              <p className="lead" style={{ marginTop: 28, maxWidth: "52ch" }}>{t.hero.sub}</p>
            </Reveal>
            {/* LANDING-WEB-CTA (déploiement — 2026-06-18) : bouton principal qui
                ouvre directement l'app passager web (app.fasotravel.app). */}
            <Reveal delay={560}>
              <div style={{ marginTop: 40 }}>
                <MagneticButton strength={0.28} radius={120}>
                  <a href="https://app.fasotravel.app" data-hover
                     style={{ display: "inline-flex", alignItems: "center", gap: 10, padding: "16px 34px", fontSize: 16, background: "linear-gradient(92deg, #f59e0b, #fbbf24)", color: "#1a1207", border: "none", borderRadius: 10, fontWeight: 700, textDecoration: "none", boxShadow: "0 10px 32px rgba(245,158,11,.4)" }}>
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
                    <span>{t.hero.ctaWeb}</span>
                  </a>
                </MagneticButton>
              </div>
            </Reveal>
            <Reveal delay={600}>
              <div style={{ marginTop: 16, display: "flex", flexWrap: "wrap", gap: 14 }}>
                <MagneticButton strength={0.28} radius={120}>
                  <StoreButton store="apple" sub="Télécharger sur" label="App Store" onNotify={onNotify} />
                </MagneticButton>
                <MagneticButton strength={0.28} radius={120}>
                  <StoreButton store="google" sub="Disponible sur" label="Google Play" onNotify={onNotify} />
                </MagneticButton>
              </div>
            </Reveal>
            <Reveal delay={800}>
              <div className="hero-stats-row" style={{ marginTop: 56 }}>
                {t.stats.slice(0, 4).map((s, i) => (
                  <div key={i} className="hero-stat">
                    <div className="hero-stat-num"><Counter to={s.n} suffix={s.suf}/></div>
                    <div className="hero-stat-label">{s.l}</div>
                  </div>
                ))}
              </div>
            </Reveal>
          </div>

          <div className="hero-logo-side" ref={heroLogoParallax} style={{ willChange: "transform" }}>
            {/* variant="blur" et non "mask" car la tête est positionnée avec
             * top:-25% (dépasse au-dessus de sa bbox) et le mask clip-path
             * coupe les débordements. Le blur fade-in n'a pas ce souci. */}
            <Reveal delay={400} variant="blur">
              <Mascot size={400}/>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { HeroScene, Hero, DrivingBus, Birds, SunRays, HeroMotes, GreetingRotator, Mascot });
