// FUEGO Landing — Production Build
const { useState, useEffect, useRef, useMemo } = React;

// ===== SVG defs (burn filter + flames) =====
function SvgDefs() {
  return (
    <svg width="0" height="0" style={{ position: "absolute" }} aria-hidden>
      <defs>
        <filter id="burn" x="-10%" y="-10%" width="120%" height="120%">
          <feTurbulence type="fractalNoise" baseFrequency="0.02 0.05" numOctaves="2" seed="3">
            <animate attributeName="baseFrequency" dur="6s" values="0.02 0.05;0.03 0.08;0.02 0.05" repeatCount="indefinite" />
          </feTurbulence>
          <feDisplacementMap in="SourceGraphic" scale="6" />
        </filter>
        <filter id="goo">
          <feGaussianBlur in="SourceGraphic" stdDeviation="6" />
          <feColorMatrix values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 18 -8" />
        </filter>
        <linearGradient id="flameGrad" x1="0" y1="1" x2="0" y2="0">
          <stop offset="0%" stopColor="#7A0A36" />
          <stop offset="20%" stopColor="#C00E4A" />
          <stop offset="50%" stopColor="#E4125A" />
          <stop offset="75%" stopColor="#CBD400" />
          <stop offset="92%" stopColor="#FFED03" />
          <stop offset="100%" stopColor="#FFF77A" />
        </linearGradient>
      </defs>
    </svg>
  );
}

function FlamesSvg({ count = 28 }) {
  // Realistic fire tongues — tapered paths that flicker upward
  const flames = useMemo(() => Array.from({ length: count }, (_, i) => {
    const x = (i + 0.5) * (100 / count) + (Math.random() - 0.5) * 2;
    const h = 20 + Math.random() * 45;
    const w = 1.2 + Math.random() * 1.8;
    const delay = Math.random() * 3;
    const dur = 0.6 + Math.random() * 0.8;
    // Color variation: inner flames brighter, outer darker
    const isInner = Math.abs(x - 50) < 25;
    const opacity = isInner ? 0.7 + Math.random() * 0.3 : 0.3 + Math.random() * 0.4;
    return { x, h, w, delay, dur, opacity, isInner };
  }), [count]);

  // Additional ember/spark particles
  const embers = useMemo(() => Array.from({ length: 8 }, (_, i) => ({
    x: 15 + Math.random() * 70,
    delay: Math.random() * 4,
    dur: 1.5 + Math.random() * 2,
    size: 0.4 + Math.random() * 0.6,
  })), []);

  return (
    <svg className="flames-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
      {/* Base heat haze — wide soft glow */}
      <ellipse cx="50" cy="100" rx="45" ry="18" fill="url(#flameGrad)" opacity="0.25" style={{ filter: "blur(6px)" }}>
        <animate attributeName="ry" dur="2.5s" values="18;22;16;18" repeatCount="indefinite" />
        <animate attributeName="opacity" dur="2.5s" values="0.25;0.35;0.2;0.25" repeatCount="indefinite" />
      </ellipse>

      {/* Fire tongues — tall tapered shapes */}
      {flames.map((f, i) => {
        const tipY = 100 - f.h;
        const tipY2 = 100 - f.h - 12;
        const tipY3 = 100 - f.h + 5;
        return (
          <path
            key={i}
            d={`M${f.x - f.w},100 Q${f.x - f.w * 0.6},${tipY + f.h * 0.3} ${f.x - f.w * 0.2},${tipY} Q${f.x},${tipY - 8} ${f.x + f.w * 0.2},${tipY} Q${f.x + f.w * 0.6},${tipY + f.h * 0.3} ${f.x + f.w},100 Z`}
            fill="url(#flameGrad)"
            opacity={f.opacity}
            style={{ filter: `blur(${f.isInner ? 0.8 : 1.5}px)` }}
          >
            <animate
              attributeName="d"
              dur={f.dur + "s"}
              values={`M${f.x - f.w},100 Q${f.x - f.w * 0.6},${tipY + f.h * 0.3} ${f.x - f.w * 0.2},${tipY} Q${f.x},${tipY - 8} ${f.x + f.w * 0.2},${tipY} Q${f.x + f.w * 0.6},${tipY + f.h * 0.3} ${f.x + f.w},100 Z;M${f.x - f.w * 0.8},100 Q${f.x - f.w * 0.3},${tipY2 + f.h * 0.25} ${f.x + f.w * 0.1},${tipY2} Q${f.x + f.w * 0.3},${tipY2 - 6} ${f.x + f.w * 0.4},${tipY2 + 3} Q${f.x + f.w * 0.7},${tipY2 + f.h * 0.35} ${f.x + f.w * 1.1},100 Z;M${f.x - f.w * 1.1},100 Q${f.x - f.w * 0.5},${tipY3 + f.h * 0.35} ${f.x - f.w * 0.1},${tipY3} Q${f.x + f.w * 0.1},${tipY3 - 5} ${f.x + f.w * 0.3},${tipY3 + 2} Q${f.x + f.w * 0.5},${tipY3 + f.h * 0.3} ${f.x + f.w * 0.9},100 Z;M${f.x - f.w},100 Q${f.x - f.w * 0.6},${tipY + f.h * 0.3} ${f.x - f.w * 0.2},${tipY} Q${f.x},${tipY - 8} ${f.x + f.w * 0.2},${tipY} Q${f.x + f.w * 0.6},${tipY + f.h * 0.3} ${f.x + f.w},100 Z`}
              repeatCount="indefinite"
              begin={f.delay + "s"}
            />
            <animate attributeName="opacity" dur={f.dur * 1.3 + "s"} values={`${f.opacity};${f.opacity * 0.5};${f.opacity * 0.8};${f.opacity}`} repeatCount="indefinite" begin={f.delay + "s"} />
          </path>
        );
      })}

      {/* Rising embers / sparks */}
      {embers.map((e, i) => (
        <circle key={"e" + i} cx={e.x} cy="100" r={e.size} fill="#FFF77A" opacity="0">
          <animate attributeName="cy" dur={e.dur + "s"} values="100;40;-10" repeatCount="indefinite" begin={e.delay + "s"} />
          <animate attributeName="opacity" dur={e.dur + "s"} values="0;0.9;0" repeatCount="indefinite" begin={e.delay + "s"} />
          <animate attributeName="cx" dur={e.dur + "s"} values={`${e.x};${e.x + (Math.random() - 0.5) * 12};${e.x + (Math.random() - 0.5) * 20}`} repeatCount="indefinite" begin={e.delay + "s"} />
        </circle>
      ))}
    </svg>
  );
}

// ===== Countdown =====
function useCountdown(target) {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const i = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(i);
  }, []);
  const diff = Math.max(0, target - now);
  return {
    d: Math.floor(diff / 86400000),
    h: Math.floor((diff % 86400000) / 3600000),
    m: Math.floor((diff % 3600000) / 60000),
    s: Math.floor((diff % 60000) / 1000),
  };
}
const pad = (n) => String(n).padStart(2, "0");

function CdNum({ value }) {
  const [tick, setTick] = useState(false);
  const prev = useRef(value);
  useEffect(() => {
    if (prev.current !== value) {
      setTick(true);
      prev.current = value;
      const t = setTimeout(() => setTick(false), 380);
      return () => clearTimeout(t);
    }
  }, [value]);
  return <div className={"cd-num" + (tick ? " tick" : "")}>{pad(value)}</div>;
}

function Countdown() {
  const target = new Date("2026-06-11T00:00:00+02:00").getTime();
  const { d, h, m, s } = useCountdown(target);
  return (
    <div className="countdown-wrap">
      <div className="countdown-label">Verkaufsstart in</div>
      <div className="countdown">
        <div className="cd-cell"><CdNum value={d} /><div className="cd-label">Tage</div></div>
        <div className="cd-cell"><CdNum value={h} /><div className="cd-label">Std</div></div>
        <div className="cd-cell"><CdNum value={m} /><div className="cd-label">Min</div></div>
        <div className="cd-cell"><CdNum value={s} /><div className="cd-label">Sek</div></div>
      </div>
    </div>
  );
}

// ===== NAV =====
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="brand">
        <span className="blob" />
        LÜTOLF<span className="fuego-mark" style={{ marginLeft: 8 }}>FUEGO</span>
      </div>
      <div className="links">
        <a href="#story">Story</a>
        <a href="#facts">Produkt</a>
        <a href="#gewinnspiel">Gewinnen</a>
        <a href="#preise">Preise</a>
        <a href="#faq">FAQ</a>
      </div>
      <a href="#gewinnspiel" className="cta">Code prüfen</a>
    </nav>
  );
}

// ===== HERO =====
function Hero() {
  return (
    <header className="hero" data-screen-label="Hero">
      <div className="slash" />
      {/* Textband ausgeblendet
      <div className="tape" aria-hidden>
        <div className="roll">
          {Array.from({ length: 4 }).map((_, j) => (
            <React.Fragment key={j}>
              <span>Limited Edition</span><span>Nur 4'000 Packungen</span>
              <span>Exklusiv bei Migros</span><span>Verkaufsstart 11.06.26</span>
              <span>20 Gewinne · Jeder Code gewinnt</span><span>Wenn weg, dann weg</span>
            </React.Fragment>
          ))}
        </div>
      </div>
      */}

      <div className="hero-inner">
        <div className="hero-left">
          <div className="hero-eyebrow">
            <span className="pulse" /> Lütolf · Limited Edition · Sommer '26
          </div>

          <h1 className="fuego-mega" aria-label="FUEGO">
            <span className="word">FUEGO</span>
            <FlamesSvg count={18} />
          </h1>

          <div className="hero-sub">
            <span className="lime-w">Limette</span>
            <span className="x">×</span>
            <span className="chili-w">Chili</span>
          </div>

          <div className="hero-marker">
            Tortilla Chips, <span className="strike">aber endlich richtig</span>
          </div>

          <p className="hero-tag">
            Erst der frische Kick von Limette. Dann das volle Feuer von Chili. Aus 100% Schweizer Mais — <b>nur 4'000 Packungen</b>, exklusiv bei Migros.
          </p>

          <div className="hero-ctas">
            <a href="#gewinnspiel" className="btn btn-primary">🔥 Code eingeben</a>
            <a href="#story" className="btn btn-ghost">Mehr erfahren</a>
          </div>

          <Countdown />
        </div>

        <div className="hero-right">
          <div className="packshot-stage">
            <div className="packshot-glow" />
            <img src="assets/fuego-packshot.png" alt="Lütolf FUEGO Tortilla Chips" className="packshot-img" />

            <div className="sticker sticker-lime sticker-1">
              <span className="big">100%</span>
              <span className="small">Schweizer Mais</span>
            </div>
            <div className="sticker sticker-fire sticker-2">
              <span className="big">NEU</span>
              <span className="small">Limette × Chili</span>
            </div>
            <div className="sticker sticker-3">VEGAN<br/>GLUTEN<br/>FREI</div>
            <div className="scribble scribble-1">heiss!</div>
            <div className="scribble scribble-2" style={{ fontSize: "13px", whiteSpace: "nowrap", display: "flex", alignItems: "center", gap: "6px", transform: "rotate(-3deg)" }}>In allen <img src="assets/brand/migros-logo.png" alt="Migros" style={{ height: "18px", verticalAlign: "middle", display: "inline-block" }} /> Filialen in der Ostschweiz</div>
          </div>
        </div>
      </div>
    </header>
  );
}

// ===== STORY with Lüti — Horizontal Polaroid Scroll =====
function Story() {
  const slides = [
    {
      img: "assets/story-1.jpg",
      rotation: -2,
      caption: "Amerika. Vulkane. Maisfelder. Christian Lütolf reist durch Amerika — auf der Suche nach der perfekten Gewürzmischung."
    },
    {
      img: "assets/story-2.jpg",
      rotation: 1.5,
      caption: "Wochenlang besucht er Märkte und kleine Dörfer. Er probiert unzählige Gewürze. Gut ist nicht gut genug. Christian sucht das Besondere."
    },
    {
      img: "assets/story-3.jpg",
      rotation: -1,
      caption: "Spät nachts in einem kleinen Labor am Vulkanhang: Christian mischt, dosiert, verwirft. Erschöpft und frustriert passiert ihm ein Missgeschick — eine ganze Schale voller Limettenschnitze fällt in die Würzmischung. «Auch das noch…»"
    },
    {
      img: "assets/story-4.jpg",
      rotation: 2,
      caption: "Mit letzter Kraft streut Christian die Mischung über einen Tortilla-Chip. Bevor er probieren kann, schläft er erschöpft ein. Die Uhr schlägt Mitternacht. Der Chip beginnt zu funkeln..."
    },
    {
      img: "assets/story-5.jpg",
      rotation: 1.5,
      caption: "Am nächsten Morgen wacht Christian auf — und traut seinen Augen kaum. Neben ihm steht tatsächlich ein kleiner grinsender Tortilla Chip. Mit Sonnenbrille."
    },
    {
      img: "assets/story-6.jpg",
      rotation: -1.5,
      caption: "«Keine Angst, amigo. Ich bin Lüti. Du hast mich mit deiner Würzmischung zum Leben erweckt!» Christian glaubt zuerst, er träume noch. Er würzt einen weiteren Chip und probiert. Sein Gaumen explodiert vor Geschmack. «Wow… das ist definitiv kein Traum.»"
    },
    {
      img: "assets/story-7.jpg",
      rotation: 1,
      caption: "Gemeinsam entwerfen Christian und Lüti die Verpackung für ihre neue Chips-Sorte und starten die erste Produktion. Dann öffnen sie die erste fertige Packung. Ein Crunch. Zwei Grinsen."
    },
    {
      img: "assets/story-8.jpg",
      rotation: -1.5,
      caption: "Doch Christian muss Lüti unbedingt in die Schweiz nehmen. «Aber wie bringt man einen lebendigen Chip durch den Zoll?» Lüti grinst: «Ganz einfach, amigo. Pack mich einfach ein.»"
    },
    {
      img: "assets/story-9.jpg",
      rotation: 2,
      caption: "Im Flugzeug starrt ein kleines Mädchen auf die Chips-Packung. Hat die Chipspackung ihr gerade zugezwinkert? Sie reibt sich die Augen. Beim zweiten Blick ist alles wieder normal. Fast alles."
    },
    {
      img: "assets/story-10.jpg",
      rotation: -2.5,
      caption: "Zurück in St. Margrethen bringt Christian die Rezeptur in die Produktion von Lütolf. Und Lüti? Der ist natürlich immer noch dabei. Heute grinst er von jeder einzelnen FUEGO-Packung. 🔥"
    }
  ];

  return (
    <section id="story" className="story" data-screen-label="Story">
      <div className="ghost-num">01</div>
      <div className="container">
        <div className="story-header">
          <div>
            <span className="eyebrow"><span className="marker-icon" /> Die Story</span>
            <h2 className="h-section">Wie das <span className="fire">Feuer</span><br/>entstand.</h2>
          </div>
          <div className="story-nav-arrows">
            <button className="story-arrow" aria-label="Zurück" onClick={() => {
              document.querySelector('.polaroid-scroll')?.scrollBy({ left: -332, behavior: 'smooth' });
            }}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5"/><path d="M12 19l-7-7 7-7"/></svg>
            </button>
            <button className="story-arrow" aria-label="Weiter" onClick={() => {
              document.querySelector('.polaroid-scroll')?.scrollBy({ left: 332, behavior: 'smooth' });
            }}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="M12 5l7 7-7 7"/></svg>
            </button>
          </div>
        </div>
      </div>

      <div className="polaroid-scroll-wrapper">
        <div className="polaroid-scroll">
          {slides.map((s, i) => (
            <div key={i} className="polaroid-card" style={{ transform: `rotate(${s.rotation}deg)` }}>
              <div className="polaroid-img">
                <img src={s.img} alt={`Story ${i + 1}`} />
              </div>
              <div className="polaroid-caption">{s.caption}</div>
              <div className="polaroid-number">{String(i + 1).padStart(2, '0')}</div>
            </div>
          ))}
        </div>
        <div className="polaroid-hint">
          <span>Swipe</span>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" width="20" height="20"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
        </div>
      </div>

      <div className="container">
        <div className="reveal" style={{ textAlign: "center", marginTop: 60 }}>
          <p style={{ fontFamily: "'Permanent Marker', cursive", color: "var(--gold)", fontSize: "20px", transform: "rotate(-2deg)" }}>
            Geboren aus Leidenschaft, geweckt durch Magie, mitgereist in einer Chipspackung. 🔥
          </p>
          <p style={{ color: "var(--text-dim)", fontSize: "15px", marginTop: "12px", fontStyle: "italic" }}>
            Wie es mit Lüti weitergeht? Das ist eine andere Geschichte...
          </p>
        </div>

        {/* Limited Edition Block */}
        <div className="limited-block reveal" style={{ marginTop: 100 }}>
          <div className="taler" aria-hidden>
            <div className="taler-content">
              <div className="num">4000</div>
              <div className="lab">Packungen</div>
              <div className="stars">✦ ✦ ✦</div>
            </div>
          </div>
          <div>
            <span className="eyebrow" style={{ color: "var(--gold)" }}><span className="marker-icon" style={{ background: "var(--gold)" }} /> Limited Edition</span>
            <h3 className="anton" style={{ fontSize: "clamp(48px, 6vw, 88px)", lineHeight: 0.9, marginTop: 16, textTransform: "uppercase" }}>
              Nur <span style={{ color: "var(--gold)", textShadow: "5px 5px 0 var(--ink)" }}>4'000 Stück</span>.<br/>
              <span style={{ color: "var(--fire)", textShadow: "5px 5px 0 var(--ink)" }}>Wenn weg, dann weg.</span>
            </h3>
            <p style={{ color: "var(--text)", marginTop: 18, maxWidth: "44ch", fontSize: 17 }}>
              In <b style={{ color: "var(--gold)" }}>20 von 4'000 Packungen</b> versteckt sich ein goldener Taler. Wer ihn findet, gewinnt. Garantiert. Vom Apple-Gutschein bis zur PlayStation 5.
            </p>
            <a href="#gewinnspiel" className="btn btn-fire" style={{ marginTop: 24 }}>Code prüfen →</a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== FACTS =====
function Facts() {
  const facts = window.FUEGO_DATA.facts;
  return (
    <section id="facts" className="facts" data-screen-label="Facts">
      <div className="ghost-num">02</div>
      <div className="container">
        <div className="facts-head">
          <div>
            <span className="eyebrow"><span className="marker-icon" /> Was drin steckt</span>
            <h2 className="h-section"><span className="outline">Ehrlich.</span> <span className="accent">Scharf.</span> <span className="fire">Gut.</span></h2>
          </div>
          <div className="lead">FUEGO. feuer im namen. feuer im geschmack.</div>
        </div>
        <div className="facts-grid">
          {facts.map((f, i) => (
            <div className="fact reveal" style={{ "--accent": f.color }} key={i}>
              <div className="stripe" />
              <div className="num-tag">0{i + 1}</div>
              <span className="ico">{f.ico}</span>
              <h3>{f.title}</h3>
              <p>{f.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ===== Confetti =====
function fireConfetti() {
  const root = document.createElement("div");
  root.className = "confetti";
  document.body.appendChild(root);
  const colors = ["#FFED03", "#CBD400", "#E4125A", "#40BFEF", "#F4EBD9"];
  for (let i = 0; i < 120; i++) {
    const p = document.createElement("div");
    p.className = "conf-piece";
    p.style.left = Math.random() * 100 + "vw";
    p.style.background = colors[i % colors.length];
    p.style.animationDuration = (3 + Math.random() * 2) + "s";
    p.style.animationDelay = (Math.random() * 0.6) + "s";
    p.style.transform = `rotate(${Math.random() * 360}deg)`;
    root.appendChild(p);
  }
  setTimeout(() => root.remove(), 6000);
}

// ===== Supabase config (publishable key — safe for client) =====
const SUPABASE_URL = "https://qdiassvxeticolakqact.supabase.co";
const SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InFkaWFzc3Z4ZXRpY29sYWtxYWN0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ5NDQ0NjQsImV4cCI6MjA5MDUyMDQ2NH0.AHp9k2GLprPLKklFPFCnrwzWYdEMHBEfigb5uxE0F2g";
const BACKUP_URL = "https://wwfdowpjpzgnzdnawbcd.supabase.co";
const BACKUP_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind3ZmRvd3BqcHpnbnpkbmF3YmNkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzIwNDI0OTEsImV4cCI6MjA4NzYxODQ5MX0.TV0xUA2SlRSTN9okTc2v6XjsGguQvSVkNlzu8_7oTXo";

async function sbLookupCode(code) {
  const url = `${SUPABASE_URL}/rest/v1/fuego_codes?code=eq.${encodeURIComponent(code)}&select=*`;
  const res = await fetch(url, {
    headers: { apikey: SUPABASE_KEY, Authorization: `Bearer ${SUPABASE_KEY}` },
  });
  if (!res.ok) throw new Error("Lookup fehlgeschlagen");
  const rows = await res.json();
  return rows[0] || null;
}

async function sbRedeemCode(code, winner) {
  const url = `${SUPABASE_URL}/rest/v1/fuego_codes?code=eq.${encodeURIComponent(code)}&redeemed=is.false`;
  const res = await fetch(url, {
    method: "PATCH",
    headers: {
      apikey: SUPABASE_KEY,
      Authorization: `Bearer ${SUPABASE_KEY}`,
      "Content-Type": "application/json",
      Prefer: "return=representation",
    },
    body: JSON.stringify({
      redeemed: true,
      redeemed_at: new Date().toISOString(),
      winner_name: winner.name,
      winner_email: winner.email,
      winner_phone: winner.phone,
      winner_address: winner.address,
      winner_plz: winner.plz,
      winner_ort: winner.ort,
    }),
  });
  if (!res.ok) throw new Error("Speichern fehlgeschlagen");
  const rows = await res.json();
  return rows[0] || null;
}

async function sbBackupWinner(payload) {
  try {
    await fetch(`${BACKUP_URL}/rest/v1/fuego_winners_backup`, {
      method: "POST",
      headers: {
        apikey: BACKUP_KEY,
        Authorization: `Bearer ${BACKUP_KEY}`,
        "Content-Type": "application/json",
        Prefer: "return=minimal",
      },
      body: JSON.stringify(payload),
    });
  } catch (_) { /* best-effort */ }
}

// ===== Gewinnspiel =====
function Gewinnspiel() {
  const steps = window.FUEGO_DATA.steps;
  const [code, setCode] = useState("");
  const [state, setState] = useState({ kind: "idle" });
  const [checking, setChecking] = useState(false);
  const [form, setForm] = useState({ vorname: "", nachname: "", email: "", tel: "", strasse: "", plz: "", ort: "" });
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");

  const onCheck = async () => {
    const c = code.trim().toUpperCase();
    if (c.length < 6) {
      setState({ kind: "error", msg: "Code zu kurz — mind. 6 Zeichen." });
      return;
    }
    setChecking(true);
    try {
      const row = await sbLookupCode(c);
      if (!row) {
        setState({ kind: "error", msg: "Ungültiger Code" });
        return;
      }
      if (row.redeemed) {
        setState({ kind: "error", msg: "Dieser Code wurde bereits eingelöst" });
        return;
      }
      setState({
        kind: "win",
        prize: { name: row.prize, emoji: row.prize_emoji || "🎉" },
        codeId: row.id,
      });
      setSubmitted(false);
      setSubmitError("");
      fireConfetti();
      // Force reveal + auto-scroll to win banner
      setTimeout(() => {
        const card = document.querySelector(".code-card");
        if (card) card.classList.add("in");
        const banner = document.querySelector(".win-banner");
        if (banner) {
          banner.style.opacity = "1";
          banner.style.transform = "none";
          banner.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      }, 100);
    } catch (err) {
      setState({ kind: "error", msg: "Verbindungsfehler — bitte erneut versuchen." });
    } finally {
      setChecking(false);
    }
  };

  const onSubmitForm = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    setSubmitError("");
    const c = code.trim().toUpperCase();
    const fullName = `${form.vorname} ${form.nachname}`.trim();
    const fullAddress = form.strasse;
    try {
      const updated = await sbRedeemCode(c, {
        name: fullName,
        email: form.email,
        phone: form.tel,
        address: fullAddress,
        plz: form.plz,
        ort: form.ort,
      });
      if (!updated) {
        setSubmitError("Dieser Code wurde gerade eingelöst. Bitte erneut prüfen.");
        setSubmitting(false);
        return;
      }
      sbBackupWinner({
        code: c,
        prize: state.prize?.name || updated.prize,
        winner_name: fullName,
        winner_email: form.email,
        winner_phone: form.tel,
        winner_address: fullAddress,
        winner_plz: form.plz,
        winner_ort: form.ort,
        redeemed_at: updated.redeemed_at || new Date().toISOString(),
      });
      setSubmitted(true);
    } catch (err) {
      setSubmitError("Speichern fehlgeschlagen. Bitte erneut versuchen.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section id="gewinnspiel" className="win" data-screen-label="Gewinnspiel">
      <div className="ghost-num">03</div>
      <div className="container">
        <span className="eyebrow" style={{ color: "var(--gold)" }}><span className="marker-icon" style={{ background: "var(--gold)" }} /> Gewinnspiel</span>
        <h2 className="h-section">Goldener <span className="gold">Taler</span><br/>gefunden?</h2>

        <div className="steps">
          {steps.map((s, i) => (
            <div className="step reveal" key={i}>
              <div className="num">{s.n}</div>
              <h4>{s.t}</h4>
              <p>{s.d}</p>
            </div>
          ))}
        </div>

        <div className={"code-card reveal" + (state.kind === "win" ? " win-state" : "")}>
          <div className="perf" />
          <div className="stamp">CHECK!</div>
          <div className="label">Code vom Taler</div>
          <div className="code-row">
            <input
              className={"code-input" + (state.kind === "error" ? " error" : "")}
              placeholder="FUEGO-XXXXX"
              maxLength={12}
              value={code}
              onChange={(e) => { setCode(e.target.value.toUpperCase()); if (state.kind === "error") setState({ kind: "idle" }); }}
              onKeyDown={(e) => e.key === "Enter" && onCheck()}
              autoComplete="off"
              spellCheck={false}
            />
            <button className="btn-check" onClick={onCheck} disabled={checking}>{checking ? "Prüfe…" : "Prüfen →"}</button>
          </div>
          <div className="code-hint">
            <span className="gold-pip" />
            <b style={{ color: "var(--gold)" }}>20 von 4'000</b> Packungen — jeder Code gewinnt sofort.
          </div>

          {state.kind === "error" && <div className="code-error">⚠ {state.msg}</div>}

          {state.kind === "win" && (
            <div className="win-banner">
              <div className="crown">👑</div>
              <h4>Gratulation!<br/><span className="gold-w">Du hast gewonnen.</span></h4>
              <p>Code <span className="mono" style={{ background: "var(--ink)", color: "var(--lime)", padding: "2px 8px" }}>{code}</span> ist gültig.</p>
              <div className="prize-line">{state.prize.emoji} {state.prize.name}</div>

              {!submitted ? (
                <form className="form-grid" onSubmit={onSubmitForm}>
                  <div className="field"><label>Vorname</label><input required value={form.vorname} onChange={e => setForm({ ...form, vorname: e.target.value })} /></div>
                  <div className="field"><label>Nachname</label><input required value={form.nachname} onChange={e => setForm({ ...form, nachname: e.target.value })} /></div>
                  <div className="field full"><label>E-Mail</label><input type="email" required value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
                  <div className="field full"><label>Telefon</label><input type="tel" required value={form.tel} onChange={e => setForm({ ...form, tel: e.target.value })} /></div>
                  <div className="field full"><label>Strasse & Hausnr.</label><input required value={form.strasse} onChange={e => setForm({ ...form, strasse: e.target.value })} /></div>
                  <div className="field"><label>PLZ</label><input required value={form.plz} onChange={e => setForm({ ...form, plz: e.target.value })} /></div>
                  <div className="field"><label>Ort</label><input required value={form.ort} onChange={e => setForm({ ...form, ort: e.target.value })} /></div>
                  <div className="full note">Mit dem Absenden bestätigst du, dass du älter als 18 Jahre bist und die Teilnahmebedingungen akzeptierst.</div>
                  {submitError && <div className="full" style={{ color: "var(--fire)", fontWeight: 700 }}>⚠ {submitError}</div>}
                  <button className="form-submit full" type="submit" disabled={submitting}>{submitting ? "Speichere…" : "Gewinn einlösen 🔥"}</button>
                </form>
              ) : (
                <div style={{ marginTop: 24, padding: 22, background: "var(--ink)", color: "var(--lime)", border: "3px solid var(--lime)", fontFamily: "Anton, sans-serif", fontSize: 16, letterSpacing: "0.04em", lineHeight: 1.5 }}>
                  ✓ Deine Daten wurden gespeichert! Du erhältst eine Bestätigung per E-Mail innerhalb von 5 Werktagen.
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

// ===== Prizes =====
function Prizes() {
  const prizes = window.FUEGO_DATA.prizes;
  return (
    <section id="preise" className="prizes" data-screen-label="Preise">
      <div className="ghost-num">04</div>
      <div className="container">
        <span className="eyebrow" style={{ color: "var(--gold)" }}><span className="marker-icon" style={{ background: "var(--gold)" }} /> 20 Gewinne · 4000 Packungen</span>
        <h2 className="h-section">Das kannst<br/>du <span className="gold">gewinnen</span>.</h2>

        <div className="prizes-grid">
          {prizes.map((p, i) => (
            <div className={"prize reveal" + (p.hero ? " hero-prize" : "")} key={i}>
              <div className="stripe-top" />
              {p.hero && <div className="badge-stamp">Haupt-<br/>gewinn</div>}
              <span className="ico-big">{p.ico}</span>
              <h4>{p.t}</h4>
              <div className="qty">{p.q}</div>
              <div className="ticket-id">№ {String(1001 + i)}</div>
              <div className="right-notch" />
            </div>
          ))}
        </div>

        <div className="prizes-foot reveal">
          <div>
            <span className="num">20</span>
            <span className="lbl" style={{ marginLeft: 14 }}>Gewinne</span>
          </div>
          <div className="lbl" style={{ color: "var(--fire)" }}>· · ·</div>
          <div className="note">
            Jeder gefundene Taler gewinnt — <span className="marker caveat" style={{ fontFamily: "Permanent Marker, cursive", color: "var(--gold)", fontSize: 18 }}>garantiert.</span>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== FAQ =====
function FAQ() {
  const faqs = window.FUEGO_DATA.faqs;
  return (
    <section id="faq" className="faq" data-screen-label="FAQ">
      <div className="ghost-num">05</div>
      <div className="container">
        <span className="eyebrow"><span className="marker-icon" /> Teilnahme & FAQ</span>
        <h2 className="h-section">Alles was<br/>du <span className="accent">wissen</span> musst.</h2>

        <div className="faq-cols">
          <div className="faq-list reveal">
            {faqs.map((f, i) => (
              <details className="faq-item" key={i}>
                <summary>{f.q}<span className="plus">+</span></summary>
                <div className="ans">{f.a}</div>
              </details>
            ))}
          </div>

          <div className="contact-card reveal">
            <h4>Kontakt</h4>
            <div className="row"><span className="ico">🏭</span><div><div className="lab">Hersteller</div><div className="val">Lütolf Spezialitäten AG · 9430 St. Margrethen SG</div></div></div>
            <div className="row"><span className="ico">✉️</span><div><div className="lab">E-Mail</div><div className="val">verkauf@luetolfag.com</div></div></div>
            <div className="row"><span className="ico">📞</span><div><div className="lab">Telefon</div><div className="val">+41 71 744 58 58</div></div></div>
            <div className="row"><span className="ico">📅</span><div><div className="lab">Aktion läuft</div><div className="val">11.06. — 30.09.2026</div></div></div>
            <div className="row"><span className="ico">⚖️</span><div><div className="lab">Voraussetzungen</div><div className="val">Ab 18 · CH oder FL</div></div></div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== Footer =====
function Footer({ onLegal }) {
  return (
    <footer data-screen-label="Footer">
      <div className="footer-grid">
        <div>
          <div className="footer-logo"><img src="assets/luetolf-logo-white.png" alt="Lütolf" style={{ height: "40px", width: "auto" }} /></div>
          <p className="footer-tag">Limitierte Edition Tortilla Chips. Limette × Chili. Nur 4'000 Packungen, exklusiv bei Migros. Hergestellt in St. Margrethen seit 2019.</p>
          <div className="socials">
            <a className="social" href="https://www.instagram.com/luetolfag/" target="_blank" rel="noopener" aria-label="Instagram">IG</a>
            <a className="social" href="https://www.facebook.com/luetolfag/" target="_blank" rel="noopener" aria-label="Facebook">FB</a>
            <a className="social" href="#" aria-label="TikTok">TT</a>
          </div>
        </div>
        <div>
          <h5>Navigation</h5>
          <ul>
            <li><a href="#story">Story</a></li>
            <li><a href="#facts">Produkt</a></li>
            <li><a href="#gewinnspiel">Gewinnspiel</a></li>
            <li><a href="#preise">Preise</a></li>
            <li><a href="#faq">FAQ</a></li>
          </ul>
        </div>
        <div>
          <h5>Rechtliches</h5>
          <ul>
            <li><a href="#" onClick={(e) => { e.preventDefault(); onLegal("teilnahme"); }}>Teilnahmebedingungen</a></li>
            <li><a href="#" onClick={(e) => { e.preventDefault(); onLegal("datenschutz"); }}>Datenschutz</a></li>
            <li><a href="#" onClick={(e) => { e.preventDefault(); onLegal("impressum"); }}>Impressum</a></li>
          </ul>
        </div>
        <div>
          <h5>Lütolf Spezialitäten AG</h5>
          <ul>
            <li>9430 St. Margrethen SG</li>
            <li>verkauf@luetolfag.com</li>
            <li>+41 71 744 58 58</li>
            <li><a href="https://luetolfag.com" target="_blank" rel="noopener">luetolfag.com</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 Lütolf Spezialitäten AG · Alle Rechte vorbehalten</span>
        <span>🇨🇭 Made in Switzerland · Since 2019</span>
      </div>
    </footer>
  );
}

// ===== Reveal =====
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ===== Legal Modal =====
function LegalModal({ id, title, onClose, children }) {
  useEffect(() => {
    document.body.style.overflow = "hidden";
    const handleKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", handleKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", handleKey); };
  }, [onClose]);
  return (
    <div className="legal-overlay" onClick={onClose}>
      <div className="legal-modal" onClick={(e) => e.stopPropagation()}>
        <button className="legal-close" onClick={onClose}>✕</button>
        <h2 className="legal-title">{title}</h2>
        <div className="legal-body">{children}</div>
      </div>
    </div>
  );
}

const LEGAL_CONTENT = {
  teilnahme: {
    title: "Teilnahmebedingungen",
    body: () => (
      <>
        <h3>1. Veranstalter</h3>
        <p>Lütolf Spezialitäten AG, 9430 St. Margrethen SG, Schweiz («Veranstalter»).</p>

        <h3>2. Teilnahmeberechtigung</h3>
        <p>Teilnahmeberechtigt sind natürliche Personen ab 18 Jahren mit Wohnsitz in der Schweiz oder im Fürstentum Liechtenstein. Mitarbeitende der Lütolf Spezialitäten AG und deren Angehörige sind von der Teilnahme ausgeschlossen.</p>

        <h3>3. Aktionszeitraum</h3>
        <p>Die Aktion läuft vom 11. Juni 2026 bis 30. September 2026. Die Eingabe eines Gewinn-Codes ist nur innerhalb dieses Zeitraums möglich.</p>

        <h3>4. Teilnahme</h3>
        <p>In 20 von 4'000 FUEGO-Packungen befindet sich ein goldener Taler mit einem einzigartigen Gewinn-Code. Zur Teilnahme muss der Code auf der Aktionsseite (fuego-chips.ch) eingegeben werden. Jeder Code kann nur einmal eingelöst werden.</p>

        <h3>5. Gewinne</h3>
        <p>Es gibt insgesamt 20 Gewinne: 1× PlayStation 5, 1× Samsung Galaxy A56, 2×2 FC St. Gallen Tickets, 5×2 Schifffahrtsgutscheine Bodensee, 1× Jahresvorrat Lütolf Chips, 5× CHF 20.– Apple Store Gutschein, 5× CHF 20.– PlayStation Store Gutschein. Der Gewinn ist nicht übertragbar und kann nicht bar ausbezahlt werden.</p>

        <h3>6. Gewinnbenachrichtigung</h3>
        <p>Der Gewinn wird sofort nach Code-Eingabe auf der Aktionsseite angezeigt. Zur Zustellung des Gewinns müssen Name, Adresse und E-Mail-Adresse angegeben werden. Ohne vollständige Angaben verfällt der Anspruch nach 30 Tagen.</p>

        <h3>7. Haftung</h3>
        <p>Der Veranstalter haftet nicht für technische Störungen, Netzwerkprobleme oder sonstige Umstände, die ausserhalb seines Einflussbereichs liegen. Der Rechtsweg ist ausgeschlossen.</p>

        <h3>8. Datenschutz</h3>
        <p>Die im Rahmen des Gewinnspiels erhobenen Daten werden ausschliesslich zur Durchführung und Abwicklung der Aktion verwendet. Siehe Datenschutzerklärung.</p>

        <h3>9. Vorzeitige Beendigung</h3>
        <p>Der Veranstalter behält sich vor, das Gewinnspiel jederzeit ohne Vorankündigung und ohne Angabe von Gründen vorzeitig zu beenden.</p>

        <h3>10. Anwendbares Recht</h3>
        <p>Es gilt ausschliesslich Schweizer Recht. Gerichtsstand ist St. Margrethen SG.</p>
      </>
    )
  },
  datenschutz: {
    title: "Datenschutzerklärung",
    body: () => (
      <>
        <h3>1. Verantwortliche Stelle</h3>
        <p>Lütolf Spezialitäten AG, 9430 St. Margrethen SG, Schweiz<br/>E-Mail: verkauf@luetolfag.com</p>

        <h3>2. Erhobene Daten</h3>
        <p>Im Rahmen des Gewinnspiels werden folgende Daten erhoben: Vorname, Nachname, E-Mail-Adresse, Postadresse (Strasse, PLZ, Ort) sowie der eingegebene Gewinn-Code.</p>

        <h3>3. Zweck der Datenerhebung</h3>
        <p>Die Daten werden ausschliesslich zur Abwicklung des Gewinnspiels und zur Zustellung der Gewinne verwendet. Eine weitergehende Nutzung findet nicht statt.</p>

        <h3>4. Speicherdauer</h3>
        <p>Die Daten werden nach Abschluss des Gewinnspiels und Zustellung aller Gewinne, spätestens jedoch am 31. Dezember 2026, gelöscht.</p>

        <h3>5. Weitergabe an Dritte</h3>
        <p>Eine Weitergabe der Daten an Dritte erfolgt nicht, es sei denn, dies ist zur Zustellung eines Gewinns erforderlich (z.B. Versanddienstleister).</p>

        <h3>6. Rechte der betroffenen Personen</h3>
        <p>Du hast das Recht auf Auskunft, Berichtigung, Löschung und Einschränkung der Verarbeitung deiner personenbezogenen Daten. Kontaktiere uns unter verkauf@luetolfag.com.</p>

        <h3>7. Cookies & Tracking</h3>
        <p>Diese Aktionsseite verwendet keine Cookies und kein Tracking. Es werden keine Analysedienste eingesetzt.</p>
      </>
    )
  },
  impressum: {
    title: "Impressum",
    body: () => (
      <>
        <h3>Verantwortlich für den Inhalt</h3>
        <p>
          <strong>Lütolf Spezialitäten AG</strong><br/>
          9430 St. Margrethen SG<br/>
          Schweiz
        </p>
        <p>
          Telefon: +41 71 744 58 58<br/>
          E-Mail: verkauf@luetolfag.com<br/>
          Website: <a href="https://luetolfag.com" target="_blank" rel="noopener">luetolfag.com</a>
        </p>

        <h3>Konzeption & Umsetzung</h3>
        <p>
          <strong>FSP Nowscale GmbH</strong><br/>
          Auerstrasse 43<br/>
          9442 Berneck<br/>
          Schweiz
        </p>
        <p>
          Website: <a href="https://nowscale.ch" target="_blank" rel="noopener">nowscale.ch</a><br/>
          E-Mail: hello@nowscale.ch
        </p>

        <h3>Haftungsausschluss</h3>
        <p>Die Inhalte dieser Aktionsseite wurden mit grösster Sorgfalt erstellt. Für die Richtigkeit, Vollständigkeit und Aktualität der Inhalte übernehmen wir keine Gewähr.</p>
      </>
    )
  }
};

// ===== App =====
function App() {
  useReveal();
  const [modal, setModal] = useState(null);
  
  // Expose modal opener globally for footer links
  useEffect(() => {
    window.__openLegal = (id) => setModal(id);
    return () => { delete window.__openLegal; };
  }, []);

  return (
    <>
      <SvgDefs />
      {/* <Nav /> */}
      <Hero />
      <Story />
      <Facts />
      <Gewinnspiel />
      <Prizes />
      <FAQ />
      <Footer onLegal={setModal} />
      {modal && LEGAL_CONTENT[modal] && (
        <LegalModal id={modal} title={LEGAL_CONTENT[modal].title} onClose={() => setModal(null)}>
          {LEGAL_CONTENT[modal].body()}
        </LegalModal>
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
