// site/hero.jsx — Hero avec animation carte à jouer qui se retourne, puis
// révèle l'As de cœur (réutilisé de la DA 08 Phase 1).
// L'animation joue une fois par invité (flag localStorage), puis l'invité
// arrive directement sur la révélation lors des visites suivantes.

const HERO_FLAG = "ea-mariage:hero-played";

function Hero() {
  // stage : 0 deck idle · 1 shuffle · 2 flip · 3 reveal
  // Toujours démarrer en état initial (deck posé, bouton "Battre les cartes")
  // — l'invité doit cliquer pour lancer le tirage à chaque visite.
  const [stage, setStage] = React.useState(0);

  React.useEffect(() => {
    if (stage === 1) {
      const t = setTimeout(() => setStage(2), 1200);
      return () => clearTimeout(t);
    }
    if (stage === 2) {
      const t = setTimeout(() => setStage(3), 1100);
      return () => clearTimeout(t);
    }
  }, [stage]);

  const replay = () => {
    setStage(0);
  };

  return (
    <section id="section-accueil" style={{
      position: "relative", minHeight: "100vh", background: T.white,
      display: "flex", flexDirection: "column",
      overflow: "hidden",
    }}>
      {/* Bandeau top : marque mono + replay discret */}
      <div style={{
        position: "absolute", top: 0, left: 0, right: 0, zIndex: 10,
        padding: "20px 24px", display: "flex", justifyContent: "space-between", alignItems: "center",
        fontFamily: T.mono, fontSize: 10, letterSpacing: 3, color: T.inkSoft, textTransform: "uppercase",
      }}>
        <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <SuitMarker suit="♥" color={T.rouge} size={12} />
          E &amp; A · {DATA.dateShort}
        </span>
        {stage === 3 && (
          <button onClick={replay} style={{
            background: "transparent", border: "none", color: T.inkSoft, cursor: "pointer",
            fontFamily: T.mono, fontSize: 9, letterSpacing: 2, textTransform: "uppercase",
            textDecoration: "underline", padding: 0,
          }}>↺ revoir le tirage</button>
        )}
      </div>

      {/* Contenu central */}
      <div style={{
        flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
        padding: "80px 24px 40px", position: "relative",
      }}>
        {stage === 0 && <HeroDeck onPlay={() => setStage(1)} />}
        {stage === 1 && <HeroShuffle />}
        {stage === 2 && <HeroFlip />}
        {stage === 3 && <HeroReveal />}
      </div>

      <style>{`
        /* Toutes les keyframes incluent translate(-50%, -50%) pour garder
           les cartes centrées via top:50%/left:50% — sinon l'animation override le centrage. */
        @keyframes hero-shuffle-a {
          0%, 100% { transform: translate(-50%, -50%) translateX(-30px) rotate(-12deg) }
          50%      { transform: translate(-50%, -50%) translateX(0)    rotate(0) }
        }
        @keyframes hero-shuffle-b {
          0%, 100% { transform: translate(-50%, -50%) translateX(30px)  rotate(12deg) }
          50%      { transform: translate(-50%, -50%) translateX(0)    rotate(0) }
        }
        @keyframes hero-flip {
          0%   { transform: translate(-50%, -50%) rotateY(0deg)   scale(1) }
          50%  { transform: translate(-50%, -50%) rotateY(90deg)  scale(1.05) }
          100% { transform: translate(-50%, -50%) rotateY(180deg) scale(1) }
        }
        @keyframes hero-card-in {
          from { opacity: 0; transform: scale(.92) rotate(-2deg) }
          to   { opacity: 1; transform: scale(1)   rotate(-2deg) }
        }
        @keyframes hero-fade-up {
          from { opacity: 0; transform: translateY(20px) }
          to   { opacity: 1; transform: translateY(0) }
        }
      `}</style>
    </section>
  );
}

// ─── État 0 : deck posé, invitation à jouer ─────────────────────────
function HeroDeck({ onPlay }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 36, animation: "site-fade .5s ease both" }}>
      <div style={{ position: "relative", width: 220, height: 320 }}>
        {[-14, -10, -5, 0].map((rot, i) => (
          <div key={i} style={{
            position: "absolute", top: 0, left: i * 4, transform: `rotate(${rot * 0.7}deg)`, zIndex: i + 1,
          }}>
            <CardBack w={180} />
          </div>
        ))}
      </div>
      <div style={{ textAlign: "center", maxWidth: 460 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>★ Save the date ★</div>
        <div className="display-bold" style={{ fontSize: "clamp(36px, 5vw, 48px)", color: T.ink }}>
          Tirez la carte<br/>de notre destin.
        </div>
        <div style={{
          fontFamily: T.italic, fontStyle: "italic", fontSize: 17, color: T.inkSoft,
          marginTop: 12, lineHeight: 1.5,
        }}>
          Le {DATA.dateLong}, au Château Sentout en Gironde.
        </div>
      </div>
      <ButtonPrimary onClick={onPlay} style={{ padding: "16px 32px", fontSize: 12 }}>
        ♥ Battre les cartes
      </ButtonPrimary>
    </div>
  );
}

// ─── État 1 : cartes brassées ──────────────────────────────────────
function HeroShuffle() {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 36 }}>
      <div style={{ position: "relative", width: 280, height: 320 }}>
        <div style={{ position: "absolute", top: "50%", left: "50%", animation: "hero-shuffle-a .35s ease infinite" }}>
          <CardBack w={180} />
        </div>
        <div style={{ position: "absolute", top: "50%", left: "50%", animation: "hero-shuffle-b .35s ease infinite" }}>
          <CardBack w={180} />
        </div>
      </div>
      <div style={{ fontFamily: T.italic, fontStyle: "italic", fontSize: 20, color: T.orDeep }}>
        Les cartes se mêlent…
      </div>
    </div>
  );
}

// ─── État 2 : carte qui se retourne ────────────────────────────────
function HeroFlip() {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 36 }}>
      <div style={{ position: "relative", width: 280, height: 320 }}>
        <div style={{
          position: "absolute", top: "50%", left: "50%", transformStyle: "preserve-3d",
          animation: "hero-flip 1.1s cubic-bezier(.5,0,.5,1) both",
        }}>
          <CardBack w={180} />
        </div>
      </div>
      <div style={{ fontFamily: T.italic, fontStyle: "italic", fontSize: 20, color: T.orDeep }}>
        Et la carte se retourne…
      </div>
    </div>
  );
}

// ─── État 3 : révélation — As de cœur + typographie save-the-date ────
function HeroReveal() {
  return (
    <div className="hero-reveal-grid" style={{
      display: "grid", gridTemplateColumns: "1fr",
      gap: 48, width: "100%", maxWidth: 1080, alignItems: "center",
    }}>
      {/* As de cœur — issu de la DA 08 */}
      <div style={{
        animation: "hero-card-in .9s cubic-bezier(.34,1.56,.64,1) both",
        display: "flex", justifyContent: "center",
      }}>
        <AceOfHearts w={300} />
      </div>

      {/* Typographie alignée save-the-date */}
      <div style={{ textAlign: "center", animation: "hero-fade-up .9s .2s ease both" }}>
        <div className="eyebrow" style={{ marginBottom: 18, color: T.orDeep }}>★ Save the date ★</div>

        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
          <div className="display-bold" style={{
            fontSize: "clamp(58px, 11vw, 100px)", color: T.ink, letterSpacing: "-2px",
            textTransform: "uppercase", lineHeight: 0.95,
          }}>
            Enora
          </div>
          <GoldAmpersand size={Math.max(56, 80)} />
          <div className="display-bold" style={{
            fontSize: "clamp(58px, 11vw, 100px)", color: T.ink, letterSpacing: "-2px",
            textTransform: "uppercase", lineHeight: 0.95,
          }}>
            Antoine
          </div>
        </div>

        <div style={{
          marginTop: 28, fontFamily: T.italic, fontStyle: "italic",
          fontSize: "clamp(17px, 2.3vw, 22px)", color: T.ink, lineHeight: 1.5,
          maxWidth: 480, margin: "28px auto 0",
        }}>
          vous invitent à réserver leur week-end du
        </div>
        <div className="display" style={{
          fontFamily: T.italic, fontStyle: "italic", fontWeight: 400,
          fontSize: "clamp(34px, 5vw, 52px)", color: T.ink, letterSpacing: 0,
          marginTop: 8,
        }}>
          21 / 08 / 2027
        </div>

        <div style={{
          marginTop: 28, display: "inline-flex", justifyContent: "center", alignItems: "center", gap: 14,
          fontFamily: T.mono, fontSize: 10, letterSpacing: 3, color: T.inkSoft, textTransform: "uppercase",
        }}>
          <SuitMarker suit="♦" color={T.or} size={11} />
          <span>Château Sentout · Tabanac · Gironde</span>
          <SuitMarker suit="♦" color={T.or} size={11} />
        </div>

        {/* Compte-à-rebours + CTA */}
        <div style={{ maxWidth: 540, margin: "36px auto 0" }}>
          <div style={{ marginBottom: 14, fontFamily: T.mono, fontSize: 9, letterSpacing: 3, color: T.inkMute, textTransform: "uppercase" }}>
            Plus que
          </div>
          <Countdown iso={DATA.dateISO} variant="compact" />
          <div style={{ display: "flex", gap: 12, marginTop: 28, justifyContent: "center", flexWrap: "wrap" }}>
            <ButtonPrimary onClick={() => document.getElementById("section-rsvp")?.scrollIntoView({ behavior: "smooth", block: "start" })}>
              ♥ Confirmer ma présence
            </ButtonPrimary>
            <ButtonSecondary onClick={() => document.getElementById("section-programme")?.scrollIntoView({ behavior: "smooth", block: "start" })}>
              Voir le programme
            </ButtonSecondary>
          </div>
        </div>
      </div>

      <style>{`
        @media (min-width: 900px) {
          .hero-reveal-grid {
            grid-template-columns: 360px 1fr !important;
            gap: 64px !important;
            text-align: left;
          }
          .hero-reveal-grid > *:nth-child(2) { text-align: left; }
          .hero-reveal-grid > *:nth-child(2) > div:nth-child(2) { align-items: flex-start; }
          .hero-reveal-grid > *:nth-child(2) > div:nth-child(3) {
            margin-left: 0 !important;
          }
        }
      `}</style>
    </div>
  );
}

// ─── As de cœur aquarellé (Voie C, Option A) ──────────────────────────
function AceOfHearts({ w = 240 }) {
  const h = w * 1.45;
  return (
    <div style={{
      width: w, height: h, background: T.white, color: T.ink, position: "relative",
      borderRadius: w * 0.04,
      boxShadow: "0 1px 1px rgba(26,22,18,0.04), 0 12px 30px rgba(26,22,18,0.10), 0 28px 60px rgba(26,22,18,0.08)",
      padding: w * 0.07, boxSizing: "border-box",
      transform: "rotate(-2deg)",
    }}>
      {/* Cadre intérieur — trait au pinceau, irrégulier */}
      <svg style={{ position: "absolute", inset: w * 0.06, width: `calc(100% - ${w * 0.12}px)`, height: `calc(100% - ${w * 0.12}px)`, pointerEvents: "none" }} viewBox="0 0 100 145" preserveAspectRatio="none">
        <path d="M 2 3 Q 1.5 2 3 2 L 97 2.5 Q 98 2 98 3 L 98.5 142 Q 98 143.5 97 143 L 3 142.5 Q 2 143 2 142 Z"
          fill="none" stroke={T.or} strokeWidth="0.4" strokeLinecap="round" opacity="0.55" />
      </svg>

      {/* Index haut-gauche — "A♥" tracé à la main */}
      <div style={{ position: "absolute", top: w * 0.07, left: w * 0.08, color: T.rougeDeep, lineHeight: 0.85 }}>
        <div style={{
          fontFamily: T.bold, fontWeight: 600, fontSize: w * 0.17,
          transform: "rotate(-2deg)", display: "inline-block",
        }}>A</div>
        <AceHeartIcon size={w * 0.13} y={-3} />
      </div>

      {/* Index bas-droit */}
      <div style={{ position: "absolute", bottom: w * 0.07, right: w * 0.08, color: T.rougeDeep, lineHeight: 0.85, transform: "rotate(180deg)" }}>
        <div style={{
          fontFamily: T.bold, fontWeight: 600, fontSize: w * 0.17,
          transform: "rotate(2deg)", display: "inline-block",
        }}>A</div>
        <AceHeartIcon size={w * 0.13} y={-3} />
      </div>

      {/* Cœur central aquarellé */}
      <div style={{
        position: "absolute", top: "32%", left: "50%", transform: "translate(-50%, -50%)",
      }}>
        <WatercolorHeart size={w * 0.55} />
      </div>

      {/* Texte central — type save-the-date */}
      <div style={{ position: "absolute", top: "62%", left: "50%", transform: "translate(-50%, 0)", textAlign: "center", width: "82%" }}>
        <div style={{ fontFamily: T.italic, fontStyle: "italic", fontSize: w * 0.085, color: T.ink, lineHeight: 1.1 }}>
          Enora &amp; Antoine
        </div>
        <div style={{ fontFamily: T.mono, fontSize: w * 0.038, letterSpacing: 2.5, color: T.orDeep, marginTop: 8 }}>
          21 · 08 · 2027
        </div>
      </div>
    </div>
  );
}

// Cœur stylisé pour les coins
function AceHeartIcon({ size = 30, y = 0 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 40 40" style={{ display: "block", marginTop: y, transform: "rotate(-3deg)" }}>
      <path d="M 20 35 C 6 25, 4 12, 12 8 C 17 6, 20 10, 20 13 C 20 10, 23 6, 28 8 C 36 12, 34 25, 20 35 Z"
        fill={T.rouge} opacity="0.92" />
      <path d="M 20 35 C 6 25, 4 12, 12 8 C 17 6, 20 10, 20 13 C 20 10, 23 6, 28 8 C 36 12, 34 25, 20 35 Z"
        fill="none" stroke={T.rougeDeep} strokeWidth="0.6" opacity="0.45" />
    </svg>
  );
}

// Cœur central aquarellé — multiples lavis superposés
function WatercolorHeart({ size = 160 }) {
  const heart = "M 50 88 C 14 60, 8 28, 26 18 C 38 12, 48 18, 50 24 C 52 18, 62 12, 74 18 C 92 28, 86 60, 50 88 Z";
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ display: "block", filter: "blur(0.2px)" }}>
      <defs>
        <filter id="ace-aqua" x="-20%" y="-20%" width="140%" height="140%">
          <feTurbulence baseFrequency="0.022" numOctaves="2" seed="3" />
          <feDisplacementMap in="SourceGraphic" scale="3.5" />
        </filter>
        <filter id="ace-aqua2" x="-20%" y="-20%" width="140%" height="140%">
          <feTurbulence baseFrequency="0.04" numOctaves="3" seed="7" />
          <feDisplacementMap in="SourceGraphic" scale="5" />
        </filter>
        <radialGradient id="ace-heart-grad" cx="0.4" cy="0.35">
          <stop offset="0%" stopColor="#C8786E" />
          <stop offset="55%" stopColor="#B85A4E" />
          <stop offset="100%" stopColor="#9A4438" />
        </radialGradient>
      </defs>
      <path d={heart} fill="#B85A4E" opacity="0.18" transform="scale(1.18) translate(-9, -7)" filter="url(#ace-aqua2)" />
      <path d={heart} fill="#C8786E" opacity="0.35" transform="scale(1.05) translate(-2.5, -2)" filter="url(#ace-aqua)" />
      <path d={heart} fill="url(#ace-heart-grad)" filter="url(#ace-aqua)" opacity="0.92" />
      <ellipse cx="40" cy="38" rx="8" ry="4" fill="#FFF" opacity="0.18" transform="rotate(-25 40 38)" />
      <circle cx="14" cy="22" r="1.4" fill="#B85A4E" opacity="0.4" />
      <circle cx="86" cy="24" r="1" fill="#B85A4E" opacity="0.35" />
      <circle cx="9" cy="48" r="0.7" fill="#B85A4E" opacity="0.3" />
      <circle cx="92" cy="52" r="1.2" fill="#B85A4E" opacity="0.4" />
    </svg>
  );
}

// ─── Carte face cachée (dos v3 — feuilles aquarelle + monogramme E&A) ─
function CardBack({ w = 180 }) {
  const h = w * 1.45;
  return (
    <div style={{
      width: w, height: h, background: T.paper, borderRadius: w * 0.05, position: "relative",
      boxShadow: "0 2px 6px rgba(0,0,0,0.10), 0 18px 40px rgba(0,0,0,0.14)",
      boxSizing: "border-box", overflow: "hidden",
    }}>
      {/* Lavis très léger en fond */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "url(assets/wash-pink.png)",
        backgroundSize: "cover", backgroundPosition: "center",
        mixBlendMode: "multiply", opacity: 0.18,
      }}/>
      {/* 2 feuilles en diagonale */}
      <img src="assets/leaf-eucalyptus.png" alt="" style={{
        position: "absolute", top: w * 0.06, left: -w * 0.02, width: w * 0.36, height: "auto",
        transform: "rotate(-15deg)", opacity: 0.88, mixBlendMode: "multiply",
      }}/>
      <img src="assets/leaf-stem.png" alt="" style={{
        position: "absolute", bottom: w * 0.06, right: -w * 0.02, width: w * 0.36, height: "auto",
        transform: "rotate(165deg)", opacity: 0.85, mixBlendMode: "multiply",
      }}/>
      {/* Cadre or fin */}
      <div style={{ position: "absolute", inset: w * 0.1, border: `0.6px solid ${T.or}`, borderRadius: w * 0.04, opacity: 0.45 }}/>
      {/* Monogramme */}
      <div style={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", textAlign: "center", width: "70%" }}>
        <div style={{ fontFamily: T.bold, fontWeight: 700, fontSize: w * 0.22, color: T.ink, letterSpacing: -1, lineHeight: 1 }}>
          E<span style={{ fontFamily: T.italic, fontStyle: "italic", color: T.or, fontWeight: 400, padding: "0 5px" }}>&amp;</span>A
        </div>
        <div style={{ marginTop: 10, fontFamily: T.mono, fontSize: w * 0.045, letterSpacing: 2.5, color: T.orDeep }}>
          21 · 08 · 2027
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Hero });
