// comic-book.jsx — homepage. Leest content uit props (geladen van /api/content).

function ComicBookHome({ content, config, onNavigate, fontScale, setFontScale }) {
  const [openStrip, setOpenStrip] = React.useState(null);
  const [openGame, setOpenGame] = React.useState(null);
  const [showSubmit, setShowSubmit] = React.useState(null);
  const [showParents, setShowParents] = React.useState(false);
  const [showReleases, setShowReleases] = React.useState(false);
  const [showWeetje, setShowWeetje] = React.useState(false);
  const [cartCount, setCartCount] = React.useState(0);

  const hero = content.hero || {};
  const strips = content.strips || [];
  const enemies = content.enemies || [];
  const merch = content.merch || [];
  const caps = content.capabilities || {};
  const accent = hero.accentKleur || "#E63946";
  const weetje = todaysWeetje(content.weetjes);

  const goSpelletjes = () => onNavigate ? onNavigate("spelletjes") : setOpenGame("reken");

  return (
    <div style={{
      background: "#D6EFC7", minHeight: "100%", width: "100%",
      fontFamily: "'Patrick Hand', cursive", color: "#1A1A1A",
      position: "relative", overflowX: "hidden",
    }}>
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(circle, rgba(0,0,0,0.07) 1.2px, transparent 1.4px)",
        backgroundSize: "12px 12px",
        pointerEvents: "none", zIndex: 0,
      }} />

      <Nav cartCount={cartCount} caps={caps} onNavigate={onNavigate}
        fontScale={fontScale} setFontScale={setFontScale} />

      <section style={{ position: "relative", zIndex: 1, padding: "28px 40px 10px" }}>
        <HeroStrip hero={hero} accent={accent} caps={caps} weetje={weetje}
          onWeetje={() => setShowWeetje(true)} />
      </section>

      {strips.length > 0 && (
        <Section title="STRIPS" ondertitel="Lees alle avonturen van Hete Peper" kleur="#E63946">
          <StripsCarousel strips={strips} onOpen={s => s.src && caps.stripReaderEnabled !== false && setOpenStrip(s)} />
        </Section>
      )}

      {config?.strafferEnabled !== false && (
        <Section title="WAT IS STRAFFER?" ondertitel="Een kettingspel — wie verslaat de huidige kampioen?" kleur="#E63946">
          <StrafferSpel config={config} onNavigate={onNavigate} />
        </Section>
      )}

      {caps.spelletjesEnabled !== false && (
        <Section title="SPELLETJES" ondertitel="Een eigen arcade vol spelletjes — speel & leer!" kleur="#3FA34D">
          <SpelletjesTeaser games={content.games || []} onAlles={goSpelletjes} onSpeel={() => setOpenGame("reken")} />
        </Section>
      )}

      {(caps.heldCardEnabled !== false || caps.vijandenGalerijEnabled !== false) && (() => {
        const showHeld = caps.heldCardEnabled !== false;
        const showVijanden = caps.vijandenGalerijEnabled !== false;
        const cols = showHeld && showVijanden ? "1.3fr 1fr" : "1fr";
        return (
          <Section title="OVER HETE PEPER" ondertitel="Ontmoet de helden & schurken" kleur="#FF8C1A">
            <div style={{ display: "grid", gridTemplateColumns: cols, gap: 28 }}>
              {showHeld && <HeldCard hero={hero} />}
              {showVijanden && (
                <div>
                  <div style={{
                    fontFamily: "'Bangers', sans-serif", fontSize: 28,
                    color: "#1A1A1A", marginBottom: 14, letterSpacing: "0.04em",
                  }}>VIJANDEN-GALERIJ</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                    {enemies.map(v => <VijandRow key={v.id} vijand={v} />)}
                  </div>
                </div>
              )}
            </div>
          </Section>
        );
      })()}

      {caps.merchEnabled !== false && merch.length > 0 && (
        <Section title="MERCH SHOP" ondertitel="Draag je held!" kleur="#8E44D1">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 26 }}>
            {merch.map(m => <MerchCard key={m.naam} {...m} onAdd={() => setCartCount(c => c + 1)} />)}
          </div>
        </Section>
      )}

      {caps.fanclubEnabled !== false && (
        <Section title="FANCLUB" ondertitel="Teken je eigen avontuur" kleur="#2D9CDB">
          <FanclubCard
            submissionsEnabled={caps.submissionsEnabled !== false}
            onUpload={() => setShowSubmit("drawing")}
            onIdee={() => setShowSubmit("suggestion")}
          />
        </Section>
      )}

      <Footer
        tekst={caps.footerTekst}
        onOuders={() => setShowParents(true)}
        onReleases={() => setShowReleases(true)}
      />

      {showParents && (
        <Modal onClose={() => setShowParents(false)}>
          <OudersInfo info={content["ouders-info"]} onClose={() => setShowParents(false)} />
        </Modal>
      )}

      {showReleases && (
        <Modal onClose={() => setShowReleases(false)}>
          <ReleasesModal data={content.releases} onClose={() => setShowReleases(false)} />
        </Modal>
      )}

      {showWeetje && (
        <Modal onClose={() => setShowWeetje(false)}>
          <WeetjeModal weetje={weetje} onClose={() => setShowWeetje(false)} />
        </Modal>
      )}

      {openStrip && <StripReader strip={openStrip} onClose={() => setOpenStrip(null)} />}
      {openGame === "reken" && (
        <Modal onClose={() => setOpenGame(null)}>
          <RekenSpel onClose={() => setOpenGame(null)} />
        </Modal>
      )}
      {showSubmit && (
        <Modal onClose={() => setShowSubmit(null)}>
          <SubmissionForm kind={showSubmit} config={config} onClose={() => setShowSubmit(null)} />
        </Modal>
      )}
    </div>
  );
}

function Nav({ cartCount, caps, onNavigate, fontScale, setFontScale }) {
  const items = ["Strips"];
  if (caps?.spelletjesEnabled !== false) items.push("Spelletjes");
  items.push("Over");
  if (caps?.merchEnabled !== false) items.push("Merch");
  if (caps?.fanclubEnabled !== false) items.push("Fanclub");

  return (
    <div style={{
      position: "sticky", top: 0, zIndex: 10,
      background: "#F0FAE6", borderBottom: "5px solid #1A1A1A",
      padding: "16px 40px",
      display: "flex", alignItems: "center", justifyContent: "flex-end",
      boxShadow: "0 4px 0 rgba(0,0,0,0.08)",
    }}>
      <nav style={{ display: "flex", gap: 10, alignItems: "center" }}>
        {items.map(l => (
          <a key={l} href={`#${l.toLowerCase()}`}
            onClick={e => {
              if (l === "Spelletjes" && onNavigate) { e.preventDefault(); onNavigate("spelletjes"); }
              if (l === "Over" && onNavigate) { e.preventDefault(); onNavigate("over"); }
            }}
            style={{
              fontFamily: "'Bangers', sans-serif", fontSize: 24,
              letterSpacing: "0.05em", color: "#1A1A1A",
              textDecoration: "none", padding: "6px 12px",
              border: "3px solid transparent",
              whiteSpace: "nowrap",
            }}
            onMouseEnter={e => {
              e.currentTarget.style.background = "#FFD23F";
              e.currentTarget.style.borderColor = "#1A1A1A";
              e.currentTarget.style.transform = "rotate(-1.5deg)";
            }}
            onMouseLeave={e => {
              e.currentTarget.style.background = "transparent";
              e.currentTarget.style.borderColor = "transparent";
              e.currentTarget.style.transform = "rotate(0)";
            }}>{l}</a>
        ))}
        {caps?.merchEnabled !== false && (
          <div style={{
            position: "relative", padding: "8px 18px", marginLeft: 6,
            background: "#FFD23F", border: "3px solid #1A1A1A",
            boxShadow: "4px 4px 0 #1A1A1A",
            fontFamily: "'Bangers', sans-serif", fontSize: 24,
            letterSpacing: "0.04em", cursor: "pointer",
          }}>🛒 {cartCount}</div>
        )}
        {setFontScale && <FontSizer scale={fontScale} setScale={setFontScale} />}
      </nav>
    </div>
  );
}

function OliverWelkom({ image = "oliver.png" }) {
  return (
    <div style={{
      position: "absolute",
      top: -20, right: -20, zIndex: 6,
      display: "flex", alignItems: "flex-start", gap: 0,
      pointerEvents: "none",
    }}>
      <div style={{
        background: "#FFD23F",
        border: "5px solid #1A1A1A",
        boxShadow: "7px 7px 0 #1A1A1A",
        padding: "20px 24px 18px",
        fontFamily: "'Patrick Hand', cursive",
        fontSize: 26, lineHeight: 1.15,
        maxWidth: 280,
        transform: "rotate(-3deg)",
        position: "relative",
        zIndex: 2,
        marginRight: -6,
        marginTop: 60,
      }} className="wobble">
        <div style={{
          fontFamily: "'Bangers', sans-serif",
          fontSize: 38, letterSpacing: "0.04em",
          color: "#E63946", WebkitTextStroke: "1.5px #1A1A1A",
          lineHeight: 1, marginBottom: 4,
        }}>
          HOI!
        </div>
        Ik ben <b>Oliver</b>.<br/>
        Welkom op mijn website!
        <div style={{
          position: "absolute",
          right: -22, bottom: 28,
          width: 0, height: 0,
          borderTop: "14px solid transparent",
          borderBottom: "14px solid transparent",
          borderLeft: "22px solid #1A1A1A",
        }} />
        <div style={{
          position: "absolute",
          right: -15, bottom: 32,
          width: 0, height: 0,
          borderTop: "10px solid transparent",
          borderBottom: "10px solid transparent",
          borderLeft: "16px solid #FFD23F",
        }} />
      </div>

      <img src={`/assets/${image}`} alt="Oliver met Hete Peper t-shirt"
        className="float"
        style={{
          width: 520, height: "auto", display: "block",
          filter: "drop-shadow(6px 6px 0 rgba(0,0,0,0.25))",
          transform: "rotate(2deg)",
          position: "relative",
          zIndex: 1,
        }} />
    </div>
  );
}

function useIsWide(min = 980) {
  const [wide, setWide] = React.useState(() =>
    typeof window !== "undefined" ? window.innerWidth >= min : true
  );
  React.useEffect(() => {
    function onResize() { setWide(window.innerWidth >= min); }
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, [min]);
  return wide;
}

function HeroStrip({ hero, accent, caps, weetje, onWeetje }) {
  const isWide = useIsWide(980);
  const showOliver = caps?.oliverHomeEnabled !== false && isWide;
  return (
    <div style={{ position: "relative", marginBottom: 50 }}>
      <div style={{
        background: "#F0FAE6", border: "5px solid #1A1A1A",
        boxShadow: "10px 10px 0 #1A1A1A",
        padding: "22px 30px", marginBottom: 130,
        marginRight: showOliver ? 840 : 0,
        position: "relative", transform: "rotate(-0.3deg)",
        zIndex: 1,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
          <PeperIcon size={22} /><PeperIcon size={22} /><PeperIcon size={22} />
          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 18, color: "#6B5A3D",
            letterSpacing: "0.12em",
          }}>{hero.ondertitel || "DE OFFICIËLE WEBSITE VAN"}</div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 18 }}>
          <div style={{
            fontFamily: "'Bangers', sans-serif",
            fontSize: 200, lineHeight: 0.85, letterSpacing: "0.02em",
            color: accent, WebkitTextStroke: "5px #1A1A1A",
            textShadow: "10px 10px 0 #1A1A1A",
          }}>{hero.naam || "HETE PEPER"}</div>
          {hero.slogan && (
            <div style={{
              fontFamily: "'Patrick Hand', cursive", fontSize: 26, color: "#1A1A1A",
              lineHeight: 1.4, maxWidth: 760,
            }}>{hero.slogan}</div>
          )}
        </div>
      </div>

      <WeetjeBalk weetje={weetje} onClick={onWeetje} />

      {showOliver && <OliverWelkom image={caps?.oliverHomeImage || "oliver.png"} />}
    </div>
  );
}

function WeetjeBalk({ weetje, onClick }) {
  const [hover, setHover] = React.useState(false);
  const datumLabel = formatWeetjeDatum(weetje.datum);
  const heeftExtras = !!(weetje.uitleg || weetje.grapje);
  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      role="button"
      tabIndex={0}
      onKeyDown={e => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onClick(); } }}
      style={{
        position: "relative",
        zIndex: 2,
        background: "#F0FAE6",
        border: "5px solid #1A1A1A",
        boxShadow: hover ? "14px 14px 0 #1A1A1A" : "10px 10px 0 #1A1A1A",
        transform: `rotate(-0.8deg) translate(${hover ? "-2px,-2px" : "0,0"})`,
        transition: "transform 0.12s, box-shadow 0.12s",
        padding: "44px 56px 44px 540px",
        minHeight: 360,
        cursor: "pointer",
        overflow: "visible",
      }}>
      <div style={{
        position: "absolute", inset: 0, zIndex: 0, pointerEvents: "none",
        backgroundImage: "radial-gradient(circle, rgba(230,57,70,0.18) 1.6px, transparent 1.8px)",
        backgroundSize: "9px 9px",
      }} />

      <img src="/assets/hete-peper-weetje.png" alt="Hete Peper denkt na"
        className={hover ? "wobble" : ""}
        style={{
          position: "absolute",
          top: -200, left: -40,
          width: 540, height: "auto",
          filter: "drop-shadow(10px 10px 0 rgba(0,0,0,0.3))",
          pointerEvents: "none",
          zIndex: 3,
          transform: `rotate(-5deg) ${hover ? "scale(1.04)" : "scale(1)"}`,
          transition: "transform 0.18s",
        }} />

      <div style={{ position: "relative", zIndex: 1 }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 18, flexWrap: "wrap", marginBottom: 22 }}>
          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 78, lineHeight: 0.9,
            color: "#E63946", WebkitTextStroke: "3px #1A1A1A",
            textShadow: "7px 7px 0 #1A1A1A", letterSpacing: "0.04em",
          }}>WEETJE VAN DE DAG</div>
          <div style={{
            background: "#FFD23F", border: "4px solid #1A1A1A",
            boxShadow: "4px 4px 0 #1A1A1A",
            padding: "6px 16px",
            fontFamily: "'Bangers', sans-serif", fontSize: 26,
            letterSpacing: "0.06em", color: "#1A1A1A",
            transform: "rotate(-2.5deg)",
            marginTop: 8,
          }}>{datumLabel}</div>
        </div>

        <div className="ballon" style={{
          fontSize: 32, lineHeight: 1.3, maxWidth: 1100,
          padding: "22px 28px",
          color: "#1A1A1A",
        }}>
          {weetje.tekst}
        </div>

        <div style={{ marginTop: 26, display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <div style={{
            display: "inline-block",
            background: hover ? "#E63946" : "#FFD23F",
            color: hover ? "#FFF" : "#1A1A1A",
            border: "4px solid #1A1A1A",
            boxShadow: "5px 5px 0 #1A1A1A",
            padding: "10px 22px",
            fontFamily: "'Bangers', sans-serif", fontSize: 26,
            letterSpacing: "0.05em",
            textShadow: hover ? "1px 1px 0 #1A1A1A" : "none",
            transition: "background 0.15s, color 0.15s",
          }}>
            👉 KLIK VOOR {heeftExtras ? "HET HELE VERHAAL" : "MEER INFO"}
          </div>
          {heeftExtras && (
            <span style={{
              fontFamily: "'Patrick Hand', cursive", fontSize: 20,
              color: "#6B5A3D",
            }}>
              ✨ met uitleg{weetje.grapje ? " én een grapje" : ""}
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

function WeetjeModal({ weetje, onClose }) {
  const datumLabel = formatWeetjeDatum(weetje.datum);
  return (
    <div style={{
      background: "#F0FAE6",
      border: "5px solid #1A1A1A",
      boxShadow: "12px 12px 0 #1A1A1A",
      maxWidth: 760, width: "100%",
      padding: "28px 32px 24px",
      position: "relative",
      maxHeight: "85vh", overflow: "auto",
    }}>
      <button onClick={onClose} aria-label="Sluiten" style={{
        position: "absolute", top: 10, right: 14,
        background: "#FFD23F", border: "3px solid #1A1A1A",
        fontFamily: "'Bangers', sans-serif", fontSize: 22,
        padding: "2px 12px", cursor: "pointer", boxShadow: "3px 3px 0 #1A1A1A",
      }}>✕</button>

      <div style={{ display: "flex", alignItems: "flex-start", gap: 18, marginBottom: 16 }}>
        <img src="/assets/hete-peper-weetje.png" alt="" style={{
          width: 130, height: "auto", flexShrink: 0,
          filter: "drop-shadow(4px 4px 0 rgba(0,0,0,0.25))",
          transform: "rotate(-4deg)",
        }} />
        <div>
          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 22, color: "#6B5A3D",
            letterSpacing: "0.08em",
          }}>{datumLabel}</div>
          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 46, lineHeight: 1,
            color: "#E63946", WebkitTextStroke: "2px #1A1A1A",
            textShadow: "4px 4px 0 #1A1A1A", letterSpacing: "0.04em",
            marginTop: 4,
          }}>WEETJE VAN DE DAG</div>
        </div>
      </div>

      <div style={{
        background: "#FFF", border: "3px solid #1A1A1A",
        boxShadow: "5px 5px 0 #1A1A1A",
        padding: "18px 22px",
        fontFamily: "'Patrick Hand', cursive",
        fontSize: 26, lineHeight: 1.35, color: "#1A1A1A",
      }}>
        {weetje.tekst}
      </div>

      {weetje.uitleg && (
        <div style={{ marginTop: 16 }}>
          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 24,
            color: "#1A1A1A", letterSpacing: "0.04em", marginBottom: 6,
          }}>WIST JE OOK DAT…</div>
          <div style={{
            fontFamily: "'Patrick Hand', cursive", fontSize: 22,
            lineHeight: 1.45, color: "#2A2118", whiteSpace: "pre-wrap",
          }}>{weetje.uitleg}</div>
        </div>
      )}

      {weetje.grapje && (
        <div style={{
          marginTop: 16,
          background: "#FFF8E1", border: "3px solid #1A1A1A",
          boxShadow: "5px 5px 0 #FFD23F",
          padding: "14px 18px",
        }}>
          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 22,
            color: "#E63946", letterSpacing: "0.04em", marginBottom: 4,
          }}>EN VOOR DE LACH… 😄</div>
          <div style={{
            fontFamily: "'Patrick Hand', cursive", fontSize: 21,
            lineHeight: 1.4, color: "#2A2118", whiteSpace: "pre-wrap",
          }}>{weetje.grapje}</div>
        </div>
      )}

      {!weetje.uitleg && !weetje.grapje && (
        <div style={{
          marginTop: 16, padding: "12px 16px",
          border: "3px dashed #1A1A1A",
          fontFamily: "'Patrick Hand', cursive", fontSize: 18,
          color: "#6B5A3D", textAlign: "center",
        }}>
          Kom morgen terug voor een nieuw weetje! 🌶️
        </div>
      )}

      <div style={{ marginTop: 18, textAlign: "right" }}>
        <button onClick={onClose} className="btn-comic groen" style={{ fontSize: 20 }}>
          OK!
        </button>
      </div>
    </div>
  );
}

function formatWeetjeDatum(datum) {
  if (!datum) return "VANDAAG";
  const [mm, dd] = datum.split("-");
  const maanden = ["januari", "februari", "maart", "april", "mei", "juni",
    "juli", "augustus", "september", "oktober", "november", "december"];
  return `${parseInt(dd, 10)} ${maanden[parseInt(mm, 10) - 1]}`.toUpperCase();
}

function todaysWeetje(weetjes) {
  const rawFb = weetjes?.fallback;
  const fb = typeof rawFb === "string"
    ? { tekst: rawFb, uitleg: null, grapje: null }
    : {
        tekst: rawFb?.tekst || "Wist je dat... een octopus drie harten heeft?",
        uitleg: rawFb?.uitleg || null,
        grapje: rawFb?.grapje || null,
      };
  const d = new Date();
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  const datum = `${mm}-${dd}`;
  const v = weetjes?.weetjes?.[datum];
  if (!v) return { ...fb, datum };
  if (typeof v === "string") return { tekst: v, uitleg: null, grapje: null, datum };
  return {
    tekst: v.tekst || fb.tekst,
    uitleg: v.uitleg || null,
    grapje: v.grapje || null,
    datum,
  };
}

function StripsCarousel({ strips, onOpen }) {
  const scrollerRef = React.useRef(null);
  const [canLeft, setCanLeft] = React.useState(false);
  const [canRight, setCanRight] = React.useState(true);

  const update = React.useCallback(() => {
    const el = scrollerRef.current;
    if (!el) return;
    setCanLeft(el.scrollLeft > 8);
    setCanRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 8);
  }, []);

  React.useEffect(() => {
    update();
    const el = scrollerRef.current;
    if (!el) return;
    el.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update);
    return () => {
      el.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
    };
  }, [update]);

  const scrollBy = (dir) => {
    const el = scrollerRef.current;
    if (!el) return;
    const card = el.querySelector("[data-strip-card]");
    const step = card ? card.getBoundingClientRect().width + 26 : 320;
    el.scrollBy({ left: dir * step * 2, behavior: "smooth" });
  };

  const Arrow = ({ dir, disabled }) => (
    <button onClick={() => scrollBy(dir)} disabled={disabled}
      aria-label={dir < 0 ? "Vorige" : "Volgende"}
      style={{
        position: "absolute", top: "50%", transform: "translateY(-50%)",
        [dir < 0 ? "left" : "right"]: -10, zIndex: 5,
        width: 56, height: 56, borderRadius: "50%",
        background: disabled ? "#F4EBDD" : "#FFF8EC",
        border: "3px solid #1A1A1A",
        boxShadow: disabled ? "2px 2px 0 #1A1A1A" : "4px 4px 0 #1A1A1A",
        cursor: disabled ? "default" : "pointer",
        opacity: disabled ? 0.35 : 1,
        fontFamily: "'Bangers', sans-serif", fontSize: 32,
        color: "#1A1A1A", lineHeight: 1,
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
      {dir < 0 ? "‹" : "›"}
    </button>
  );

  return (
    <div style={{ position: "relative" }}>
      <Arrow dir={-1} disabled={!canLeft} />
      <Arrow dir={1} disabled={!canRight} />

      <div ref={scrollerRef} style={{
        display: "flex", gap: 26, overflowX: "auto", overflowY: "visible",
        scrollSnapType: "x mandatory",
        padding: "30px 8px 40px",
        scrollbarWidth: "none", msOverflowStyle: "none",
      }}>
        {strips.map((s) => (
          <div key={s.id} data-strip-card onClick={() => onOpen(s)}
            style={{
              flex: "0 0 300px", scrollSnapAlign: "start",
              cursor: s.src ? "pointer" : "default",
              position: "relative",
            }}>
            <ComicThumb src={s.src} title={s.titel} nummer={s.nummer} rotate={s.rotate} />
            {!s.src && (
              <div style={{
                position: "absolute", top: "50%", left: "50%",
                transform: `translate(-50%, -50%) rotate(${s.rotate || 0}deg)`,
                background: "#FFD23F", border: "3px solid #1A1A1A",
                padding: "10px 18px", boxShadow: "4px 4px 0 #1A1A1A",
                fontFamily: "'Bangers', sans-serif", fontSize: 24, color: "#1A1A1A",
                letterSpacing: "0.05em", zIndex: 3, whiteSpace: "nowrap",
              }}>BINNENKORT!</div>
            )}
            <div style={{
              marginTop: 10, textAlign: "center",
              fontFamily: "'Bangers', sans-serif", fontSize: 20,
              color: "#1A1A1A", letterSpacing: "0.04em", opacity: 0.8,
            }}>
              #{String(s.nummer).padStart(2, "0")} — {s.titel}
            </div>
          </div>
        ))}

        <div style={{
          flex: "0 0 240px", scrollSnapAlign: "start",
          display: "flex", alignItems: "center", justifyContent: "center",
          flexDirection: "column", gap: 10,
          border: "3px dashed #1A1A1A", borderRadius: 12,
          background: "rgba(255,255,255,0.4)",
          padding: "20px", fontFamily: "'Bangers', sans-serif",
          color: "#1A1A1A", textAlign: "center",
        }}>
          <div style={{ fontSize: 48, lineHeight: 1 }}>🌶️</div>
          <div style={{ fontSize: 22, letterSpacing: "0.04em" }}>MEER STRIPS<br />OP KOMST!</div>
          <div style={{ fontFamily: "'Patrick Hand', cursive", fontSize: 16, opacity: 0.7 }}>Elke maand een nieuwe</div>
        </div>
      </div>
    </div>
  );
}

function Section({ title, ondertitel, kleur, children }) {
  return (
    <section id={title.toLowerCase().split(" ")[0]} style={{
      position: "relative", zIndex: 1, padding: "32px 40px",
    }}>
      <div style={{
        display: "flex", alignItems: "baseline", gap: 14, marginBottom: 20,
        borderBottom: "3px dashed #1A1A1A", paddingBottom: 10,
      }}>
        <div style={{
          fontFamily: "'Bangers', sans-serif", fontSize: 54,
          color: kleur, WebkitTextStroke: "2px #1A1A1A",
          textShadow: "4px 4px 0 #1A1A1A", letterSpacing: "0.03em", lineHeight: 0.95,
        }}>{title}</div>
        <div style={{ fontFamily: "'Patrick Hand', cursive", fontSize: 22, color: "#6B5A3D" }}>
          {ondertitel}
        </div>
      </div>
      {children}
    </section>
  );
}

function SpelletjesTeaser({ games, onAlles, onSpeel }) {
  const perCat = {};
  for (const g of games) {
    if (g.enabled === false) continue;
    perCat[g.categorie] = (perCat[g.categorie] || 0) + 1;
  }
  const meta = {
    rekenen: { icon: "➕", kleur: "#3FA34D", label: "REKENEN" },
    spelling: { icon: "🔤", kleur: "#FF8C1A", label: "SPELLING" },
    geheugen: { icon: "🧠", kleur: "#8E44D1", label: "GEHEUGEN" },
    puzzels: { icon: "🧩", kleur: "#2D9CDB", label: "PUZZELS" },
    kleuren: { icon: "🎨", kleur: "#FFD23F", label: "KLEUREN" },
  };

  return (
    <div style={{
      background: "#F0FAE6", border: "4px solid #1A1A1A",
      boxShadow: "8px 8px 0 #1A1A1A", padding: 22,
      display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 22, alignItems: "center",
      position: "relative",
    }}>
      <div>
        <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 40, color: "#3FA34D", WebkitTextStroke: "1.8px #1A1A1A", textShadow: "4px 4px 0 #1A1A1A", letterSpacing: "0.03em", lineHeight: 1 }}>
          HETE PEPER ARCADE
        </div>
        <div style={{ fontSize: 19, color: "#3A3025", marginTop: 8, maxWidth: 460 }}>
          Rekenen, spelling, geheugen, puzzels en kleuren — steeds meer spellen erbij!
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 14 }}>
          {Object.entries(perCat).map(([cat, n]) => {
            const m = meta[cat] || { icon: "⭐", kleur: "#ddd", label: cat.toUpperCase() };
            return (
              <div key={cat} style={{
                background: m.kleur, border: "3px solid #1A1A1A",
                padding: "4px 10px", fontFamily: "'Bangers', sans-serif",
                fontSize: 16, letterSpacing: "0.04em", boxShadow: "2px 2px 0 #1A1A1A",
                display: "flex", alignItems: "center", gap: 6,
                color: ["REKENEN", "SPELLING", "GEHEUGEN"].includes(m.label) ? "#F0FAE6" : "#1A1A1A",
              }}>
                <span>{m.icon}</span>{m.label}<span style={{ opacity: 0.7, fontSize: 13 }}>×{n}</span>
              </div>
            );
          })}
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
          <button className="btn-comic rood" onClick={onAlles}>🎮 ALLE SPELLEN →</button>
          <button className="btn-comic oranje" onClick={onSpeel}>⚡ SPEEL NU</button>
        </div>
      </div>
      <div style={{ position: "relative", minHeight: 220, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div style={{ position: "absolute", top: 10, left: 30 }} className="float">
          <Sticker color="#FFD23F" rotate={-10} size={90}>NIEUW!</Sticker>
        </div>
        <div style={{ position: "absolute", bottom: 10, right: 10 }}>
          <Burst color="#E63946" rotate={6} size={100}>
            <span style={{ color: "#F0FAE6" }}>PIT!</span>
          </Burst>
        </div>
        <img src="/assets/hete-peper-games.png" alt="Hete Peper aan het gamen"
          className="float"
          style={{
            width: 320, height: "auto",
            filter: "drop-shadow(5px 5px 0 rgba(0,0,0,0.2))",
            transform: "scaleX(-1) rotate(3deg)",
          }} />
      </div>
    </div>
  );
}

function StrafferSpel({ config, onNavigate }) {
  const [current, setCurrent] = React.useState(null);
  const [total, setTotal] = React.useState(0);
  const [naam, setNaam] = React.useState("");
  const [item, setItem] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [err, setErr] = React.useState(null);
  const [loadErr, setLoadErr] = React.useState(null);

  const reload = React.useCallback(() => {
    fetch("/api/straffer/current")
      .then(async r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        const ct = r.headers.get("content-type") || "";
        if (!ct.includes("application/json")) throw new Error("API niet beschikbaar — herstart de server.");
        return r.json();
      })
      .then(d => { setCurrent(d.current); setTotal(d.total || 0); setLoadErr(null); })
      .catch(e => setLoadErr(e.message || "Kan spel niet laden"));
  }, []);

  React.useEffect(reload, [reload]);

  async function submit(e) {
    e.preventDefault();
    if (!item.trim()) return;
    setBusy(true); setErr(null); setResult(null);
    try {
      const r = await fetch("/api/straffer/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ naam: naam.trim(), item: item.trim() }),
      });
      const data = await r.json();
      if (!r.ok) throw new Error(data.error || "Verzenden mislukt");
      setResult(data);
      if (data.accepted) {
        setItem("");
        reload();
      }
    } catch (e) {
      setErr(e.message);
    } finally {
      setBusy(false);
    }
  }

  if (loadErr) {
    return (
      <div style={strafferShell}>
        <div style={{ fontFamily: "'Patrick Hand', cursive", fontSize: 22, color: "#B23A2E" }}>
          ⚠️ Het spel kan niet geladen worden: {loadErr}
        </div>
      </div>
    );
  }
  if (!current) {
    return <div style={strafferShell}><div style={{ padding: 12, fontSize: 22 }}>🌶️ Spel laden…</div></div>;
  }

  const itemLen = current.item.length;
  const itemFontSize = itemLen > 16 ? 32 : itemLen > 12 ? 42 : itemLen > 8 ? 54 : 68;

  return (
    <div style={{ ...strafferShell, position: "relative" }}>
      <img src="/assets/hete-peper-straffer.png" alt="Sterke Hete Peper"
        className="float"
        style={{
          position: "absolute",
          top: 30, left: -160,
          width: 460, height: "auto",
          filter: "drop-shadow(10px 10px 0 rgba(0,0,0,0.25))",
          transform: "rotate(-8deg)",
          pointerEvents: "none",
          zIndex: 5,
        }} />
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))",
        gap: 28, alignItems: "stretch",
      }}>
        {/* ────── KAMPIOEN-KAART ────── */}
        <div style={{
          background: "linear-gradient(135deg, #FFE066 0%, #FFD23F 100%)",
          border: "5px solid #1A1A1A",
          boxShadow: "8px 8px 0 #1A1A1A",
          padding: "20px 20px 26px",
          transform: "rotate(-1.2deg)",
          display: "flex", flexDirection: "column",
          alignItems: "center", justifyContent: "center",
          position: "relative", textAlign: "center",
        }}>
          {/* Kampioens-sticker rechtsboven */}
          <div style={{
            position: "absolute", top: -16, right: -10,
            background: "#E63946", color: "#F0FAE6",
            border: "4px solid #1A1A1A", boxShadow: "3px 3px 0 #1A1A1A",
            padding: "6px 14px", transform: "rotate(8deg)",
            fontFamily: "'Bangers', sans-serif", fontSize: 22,
            letterSpacing: "0.05em",
          }}>
            KAMPIOEN #{total}
          </div>

          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 22,
            letterSpacing: "0.08em", color: "#6B5A3D", marginTop: 14,
          }}>HUIDIGE KAMPIOEN</div>

          <div style={{
            fontSize: 130, lineHeight: 1, margin: "10px 0 4px",
            filter: "drop-shadow(4px 4px 0 rgba(0,0,0,0.18))",
          }} aria-hidden="true">{current.emoji || "✨"}</div>

          <div style={{
            fontFamily: "'Bangers', sans-serif",
            fontSize: itemFontSize, lineHeight: 1,
            color: "#E63946",
            WebkitTextStroke: "2.5px #1A1A1A",
            textShadow: "5px 5px 0 #1A1A1A",
            letterSpacing: "0.02em",
            textTransform: "uppercase",
            overflowWrap: "anywhere", maxWidth: "100%",
            marginTop: 4,
          }}>{current.item}</div>

          <div style={{
            fontFamily: "'Patrick Hand', cursive", fontSize: 22,
            color: "#3A3025", marginTop: 14,
          }}>
            door <b>{current.submitter}</b>
          </div>
          <div style={{
            fontFamily: "'Patrick Hand', cursive", fontSize: 18,
            color: "#6B5A3D",
          }}>{formatDatum(current.datum)}</div>

          {current.uitleg && (
            <div style={{
              fontFamily: "'Patrick Hand', cursive", fontSize: 20,
              color: "#1A1A1A", marginTop: 16, textAlign: "center",
              background: "#FFF8DA", border: "3px dashed #1A1A1A",
              padding: "12px 14px", maxWidth: 420, lineHeight: 1.3,
            }}>
              💬 {current.uitleg}
            </div>
          )}
        </div>

        {/* ────── FORMULIER ────── */}
        <form onSubmit={submit} style={{
          display: "flex", flexDirection: "column", gap: 16, minWidth: 0,
          background: "#FFF8EC", border: "5px solid #1A1A1A",
          boxShadow: "8px 8px 0 #1A1A1A",
          padding: "22px 24px", transform: "rotate(0.6deg)",
          position: "relative",
        }}>
          {/* Speech bubble tail */}
          <div style={{
            position: "absolute", left: -22, top: 60,
            width: 0, height: 0,
            borderTop: "16px solid transparent",
            borderBottom: "16px solid transparent",
            borderRight: "24px solid #1A1A1A",
            display: "none",
          }} />

          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 38, lineHeight: 1.05,
            color: "#1A1A1A", letterSpacing: "0.03em", overflowWrap: "anywhere",
          }}>
            Wat is straffer dan{" "}
            <span style={{
              color: "#E63946",
              WebkitTextStroke: "1.5px #1A1A1A",
              textShadow: "3px 3px 0 #1A1A1A",
            }}>{current.item.toUpperCase()}</span>?
          </div>
          <div style={{ fontFamily: "'Patrick Hand', cursive", fontSize: 22, color: "#3A3025", lineHeight: 1.3 }}>
            🌶️ Typ iets straffers, sterker of heter. Hete Peper bekijkt het en zegt of het wint!
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <label style={lblStraffer}>👤 Jouw naam</label>
            <input style={inpStraffer} value={naam} onChange={e => setNaam(e.target.value)} maxLength={40} placeholder="bv. Oliver" />
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <label style={lblStraffer}>💡 Jouw straffe woord</label>
            <input style={inpStraffer} value={item} onChange={e => setItem(e.target.value)} maxLength={60} placeholder="bv. vulkaan, draak, hete soep…" required />
          </div>

          {err && <div style={{
            color: "#B23A2E", background: "#FBE9E7",
            border: "2px dashed #B23A2E", padding: "8px 12px",
            fontFamily: "'Patrick Hand', cursive", fontSize: 18,
          }}>⚠️ {err}</div>}

          <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 6 }}>
            <button type="submit" className="btn-comic rood" disabled={busy || !item.trim()}
              style={{ fontSize: 28, padding: "14px 28px" }}>
              {busy ? "🌶️ DENKEN…" : "🔥 PROBEER!"}
            </button>
            <button type="button" className="btn-comic" onClick={() => onNavigate && onNavigate("straffer-historiek")}
              style={{ fontSize: 24, padding: "14px 22px" }}>
              📜 BEKIJK ALLES ({total})
            </button>
          </div>

          {result && <StrafferResult result={result} onClose={() => setResult(null)} />}
        </form>
      </div>
    </div>
  );
}

function StrafferResult({ result, onClose }) {
  if (result.accepted) {
    return (
      <div style={{
        background: "#D6F0C2", border: "4px solid #1A1A1A", boxShadow: "5px 5px 0 #1A1A1A",
        padding: "16px 18px", marginTop: 10, fontFamily: "'Patrick Hand', cursive",
        position: "relative", transform: "rotate(-0.5deg)",
      }}>
        <button onClick={onClose} aria-label="sluiten" style={miniClose}>✕</button>
        <div style={{
          fontFamily: "'Bangers', sans-serif", fontSize: 32, color: "#2D7B1F",
          letterSpacing: "0.04em", lineHeight: 1.05,
        }}>
          🎉 JOEPIE! {result.entry.emoji} {result.entry.item.toUpperCase()} wint!
        </div>
        {result.entry.uitleg && <div style={{ fontSize: 20, marginTop: 8, lineHeight: 1.3 }}>{result.entry.uitleg}</div>}
      </div>
    );
  }
  const isInappropriate = result.reason === "ongepast";
  return (
    <div style={{
      background: isInappropriate ? "#FBE9E7" : "#FFF4D6",
      border: "4px solid #1A1A1A", boxShadow: "5px 5px 0 #1A1A1A",
      padding: "16px 18px", marginTop: 10, fontFamily: "'Patrick Hand', cursive",
      position: "relative", transform: "rotate(-0.5deg)",
    }}>
      <button onClick={onClose} aria-label="sluiten" style={miniClose}>✕</button>
      <div style={{
        fontFamily: "'Bangers', sans-serif", fontSize: 28,
        color: isInappropriate ? "#B23A2E" : "#A66A00",
        letterSpacing: "0.04em", lineHeight: 1.05,
      }}>
        {isInappropriate ? "🙊 OEPS — DAT HOUDEN WE NETJES" : "🤔 NIET STRAFFER GENOEG"}
      </div>
      <div style={{ fontSize: 20, marginTop: 8, lineHeight: 1.3 }}>{result.reden}</div>
    </div>
  );
}

function formatDatum(iso) {
  if (!iso) return "";
  try {
    const d = new Date(iso);
    return d.toLocaleDateString("nl-BE", { day: "numeric", month: "long", year: "numeric" });
  } catch { return ""; }
}

const strafferShell = {
  background: "#FFF8EC",
  backgroundImage: "radial-gradient(circle, rgba(230,57,70,0.07) 1.4px, transparent 1.6px)",
  backgroundSize: "14px 14px",
  border: "5px solid #1A1A1A",
  boxShadow: "10px 10px 0 #1A1A1A",
  padding: 26,
};
const lblStraffer = {
  fontFamily: "'Bangers', sans-serif", fontSize: 22, letterSpacing: "0.05em", color: "#6B5A3D",
};
const inpStraffer = {
  border: "4px solid #1A1A1A", background: "#FFF",
  padding: "14px 18px", fontFamily: "'Patrick Hand', cursive", fontSize: 24,
  boxShadow: "4px 4px 0 #1A1A1A",
};
const miniClose = {
  position: "absolute", top: 4, right: 6,
  background: "transparent", border: "none", fontFamily: "'Bangers', sans-serif",
  fontSize: 18, cursor: "pointer", color: "#1A1A1A",
};

function HeldCard({ hero }) {
  return (
    <div style={{
      background: "#F0FAE6", border: "4px solid #1A1A1A",
      boxShadow: "6px 6px 0 #1A1A1A", padding: 20,
      display: "flex", gap: 18, alignItems: "center", position: "relative",
    }}>
      <div style={{
        position: "absolute", top: -14, left: 16,
        background: "#E63946", color: "#F0FAE6", border: "3px solid #1A1A1A",
        padding: "2px 12px", fontFamily: "'Bangers', sans-serif",
        fontSize: 16, letterSpacing: "0.05em", boxShadow: "2px 2px 0 #1A1A1A",
      }}>DE HELD</div>
      <PeperMascotte size={170} mood="happy" image={hero.image} />
      <div>
        <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 40, color: "#E63946", letterSpacing: "0.03em", lineHeight: 1 }}>
          {hero.naam || "HETE PEPER"}
        </div>
        <div style={{ fontSize: 18, color: "#3A3025", marginTop: 6, maxWidth: 320 }}>
          {hero.beschrijving}
        </div>
        <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 4, fontSize: 16 }}>
          {(hero.feiten || []).map((f, i) => <Feit key={i} label={f.label} waarde={f.waarde} />)}
        </div>
      </div>
    </div>
  );
}

function Feit({ label, waarde }) {
  return (
    <div style={{ display: "flex", gap: 8 }}>
      <span style={{ fontFamily: "'Bangers', sans-serif", fontSize: 15, color: "#6B5A3D", letterSpacing: "0.04em" }}>
        {(label || "").toUpperCase()}:
      </span>
      <span style={{ fontSize: 17, color: "#1A1A1A" }}>{waarde}</span>
    </div>
  );
}

function VijandRow({ vijand }) {
  return (
    <div style={{
      background: "#F0FAE6", border: "3px solid #1A1A1A",
      padding: "10px 14px",
      display: "flex", alignItems: "center", gap: 14,
      boxShadow: "4px 4px 0 #1A1A1A",
    }}>
      <div style={{
        width: 70, height: 90, display: "flex", alignItems: "center", justifyContent: "center",
        background: "#D6EFC7", border: "2px solid #1A1A1A",
      }}>
        <EnemyVisual visual={vijand.visual} image={vijand.image} size={55} />
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 22, letterSpacing: "0.03em" }}>
          {vijand.naam}
        </div>
        <div style={{ fontSize: 15, color: "#3A3025" }}>
          <b>Kracht:</b> {vijand.kracht} · <b>Zwakte:</b> {vijand.zwakte}
        </div>
      </div>
    </div>
  );
}

function MerchCard({ naam, prijs, kleur, type, onAdd }) {
  const [added, setAdded] = React.useState(false);
  return (
    <div style={{
      background: "#F0FAE6", border: "4px solid #1A1A1A",
      boxShadow: "6px 6px 0 #1A1A1A", padding: 16, position: "relative",
    }}>
      <div style={{
        aspectRatio: "1/1", background: kleur,
        border: "3px solid #1A1A1A",
        display: "flex", alignItems: "center", justifyContent: "center",
        position: "relative", overflow: "hidden",
      }}>
        {type === "tshirt" && <TshirtGrafiek />}
        {type === "stickers" && <StickersGrafiek />}
        {type === "poster" && <PosterGrafiek />}
      </div>
      <div style={{ marginTop: 10, display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
        <div>
          <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 22, letterSpacing: "0.03em", lineHeight: 1 }}>{naam}</div>
          <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 24, color: "#E63946", marginTop: 4 }}>
            €{Number(prijs).toFixed(2)}
          </div>
        </div>
        <button className="btn-comic groen" style={{ fontSize: 16, padding: "6px 12px" }}
          onClick={() => { setAdded(true); onAdd(); setTimeout(() => setAdded(false), 900); }}>
          {added ? "✓ TOE" : "+ KOOP"}
        </button>
      </div>
    </div>
  );
}

function TshirtGrafiek() {
  return (
    <svg viewBox="0 0 200 200" width="90%" height="90%">
      <path d="M 50 50 L 80 30 Q 100 50 120 30 L 150 50 L 175 80 L 150 95 L 145 170 L 55 170 L 50 95 L 25 80 Z"
        fill="#F0FAE6" stroke="#1A1A1A" strokeWidth="5" strokeLinejoin="round" />
      <g transform="translate(75 70) scale(0.6)">
        <path d="M 50 20 Q 25 22 22 65 Q 20 115 50 130 Q 80 115 78 65 Q 75 22 50 20 Z"
          fill="#E63946" stroke="#1A1A1A" strokeWidth="5" strokeLinejoin="round" />
        <path d="M 30 10 Q 50 -5 70 10 L 75 22 L 25 22 Z"
          fill="#3FA34D" stroke="#1A1A1A" strokeWidth="5" strokeLinejoin="round" />
      </g>
    </svg>
  );
}
function StickersGrafiek() {
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 6, padding: 10, justifyContent: "center", alignItems: "center", height: "100%" }}>
      <Sticker color="#E63946" rotate={-8} size={58}><span style={{ color: "#F0FAE6" }}>PIT!</span></Sticker>
      <Sticker color="#F0FAE6" rotate={6} size={58}>VUUR</Sticker>
      <Sticker color="#3FA34D" rotate={-4} size={58}><span style={{ color: "#F0FAE6" }}>HELD</span></Sticker>
      <Sticker color="#FF8C1A" rotate={10} size={58}>BAM!</Sticker>
    </div>
  );
}
function PosterGrafiek() {
  return (
    <div style={{ width: "75%", height: "88%", background: "#D6EFC7", border: "3px solid #1A1A1A", position: "relative", padding: 8 }}>
      <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 16, color: "#E63946", WebkitTextStroke: "0.5px #1A1A1A", lineHeight: 1 }}>
        HETE PEPER<br/>& DE BOZE<br/>WASKNIJPER
      </div>
      <div style={{ position: "absolute", bottom: 8, right: 8 }}>
        <PeperMascotte size={50} mood="determined" fire />
      </div>
    </div>
  );
}

function FanclubCard({ submissionsEnabled, onUpload, onIdee }) {
  return (
    <div style={{
      background: "#F0FAE6", border: "4px solid #1A1A1A",
      boxShadow: "6px 6px 0 #1A1A1A", padding: 24,
      display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20,
      alignItems: "center",
    }}>
      <div>
        <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 34, color: "#2D9CDB", letterSpacing: "0.03em", WebkitTextStroke: "1.5px #1A1A1A", lineHeight: 1 }}>
          WORD GEHEIM AGENT!
        </div>
        <div style={{ fontSize: 18, color: "#3A3025", marginTop: 8 }}>
          Upload je eigen tekening van Hete Peper, bedenk een nieuwe vijand, of stuur je eigen strip-idee in.
          De beste inzendingen komen op de site!
        </div>
        <div style={{ marginTop: 14, display: "flex", gap: 10, flexWrap: "wrap" }}>
          <button className="btn-comic blauw" disabled={!submissionsEnabled} onClick={onUpload}>📸 UPLOAD TEKENING</button>
          <button className="btn-comic oranje" disabled={!submissionsEnabled} onClick={onIdee}>💡 NIEUWE VIJAND</button>
        </div>
        {!submissionsEnabled && (
          <div style={{ marginTop: 10, color: "#6B5A3D", fontStyle: "italic" }}>
            Inzendingen staan even uit — probeer later nog eens!
          </div>
        )}
      </div>
      <div style={{ position: "relative", minHeight: 200 }}>
        <div style={{ position: "absolute", top: 10, left: 40 }} className="float">
          <Sticker color="#FFD23F" rotate={-8} size={110}>AGENT<br/>KAART</Sticker>
        </div>
        <div style={{ position: "absolute", top: 30, left: 160 }} className="float">
          <Burst color="#E63946" rotate={6} size={120}>
            <span style={{ color: "#F0FAE6" }}>JIJ!</span>
          </Burst>
        </div>
        <div style={{ position: "absolute", bottom: 0, right: 0 }}>
          <PeperMascotte size={110} mood="wink" />
        </div>
      </div>
    </div>
  );
}

function Footer({ tekst, onOuders, onReleases }) {
  const linkStyle = {
    color: "#F0FAE6", background: "none", border: "none",
    padding: 0, cursor: "pointer",
    fontFamily: "inherit", fontSize: "inherit",
    textDecoration: "underline", textUnderlineOffset: "3px",
  };
  return (
    <footer style={{
      background: "#1A1A1A", color: "#F0FAE6",
      padding: "26px 40px", borderTop: "5px solid #1A1A1A",
      display: "flex", justifyContent: "space-between", alignItems: "center",
      marginTop: 40, fontFamily: "'Patrick Hand', cursive", fontSize: 16,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <PeperIcon size={30} />
        <span style={{ fontFamily: "'Bangers', sans-serif", fontSize: 24, letterSpacing: "0.05em" }}>HETE PEPER</span>
        <span>{tekst || "© 2026 — Alle avonturen voorbehouden"}</span>
      </div>
      <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
        <span>Veilig voor kids</span>
        <span>·</span>
        <button type="button" onClick={onOuders} style={linkStyle}>Info voor ouders</button>
        <span>·</span>
        <button type="button" onClick={onReleases} style={linkStyle}>Wat is nieuw?</button>
      </div>
    </footer>
  );
}

function OudersInfo({ info, onClose }) {
  if (!info) return (
    <div style={{
      background: "#F0FAE6", border: "5px solid #1A1A1A",
      boxShadow: "8px 8px 0 #1A1A1A", padding: 32,
      maxWidth: 520, textAlign: "center",
    }}>
      <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 28, marginBottom: 10 }}>
        Info voor ouders
      </div>
      <div>Deze informatie is nog niet beschikbaar. Probeer later opnieuw.</div>
      <div style={{ marginTop: 16 }}>
        <button className="btn-comic rood" onClick={onClose}>SLUITEN</button>
      </div>
    </div>
  );
  return (
    <div style={{
      background: "#F0FAE6", border: "5px solid #1A1A1A",
      boxShadow: "10px 10px 0 #1A1A1A",
      padding: "24px 28px",
      maxWidth: 720, width: "min(720px, 92vw)", maxHeight: "88vh",
      overflowY: "auto", position: "relative",
      fontFamily: "'Patrick Hand', cursive",
      color: "#1A1A1A",
    }}>
      <button onClick={onClose} style={{
        position: "absolute", top: -18, right: -18,
        width: 44, height: 44, borderRadius: "50%",
        background: "#1A1A1A", color: "#F0FAE6",
        border: "3px solid #F0FAE6", boxShadow: "2px 2px 0 #1A1A1A",
        fontFamily: "'Bangers', sans-serif", fontSize: 22, cursor: "pointer",
      }}>✕</button>

      <div style={{
        fontFamily: "'Bangers', sans-serif", fontSize: 36,
        color: "#E63946", letterSpacing: "0.04em",
        WebkitTextStroke: "1.5px #1A1A1A",
        marginBottom: 6,
      }}>{info.titel || "Info voor ouders"}</div>

      {info.intro && (
        <div style={{ fontSize: 20, lineHeight: 1.6, color: "#3A3025", marginBottom: 22, maxWidth: "62ch" }}>
          {info.intro}
        </div>
      )}

      {(info.secties || []).map((s, i) => (
        <div key={i} style={{ marginBottom: 22 }}>
          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 24,
            letterSpacing: "0.04em", color: "#1A1A1A",
            marginBottom: 6,
          }}>{s.kop}</div>
          <div style={{ fontSize: 19, lineHeight: 1.6, color: "#3A3025", whiteSpace: "pre-wrap", maxWidth: "62ch" }}>
            {s.tekst}
          </div>
        </div>
      ))}

      {info.laatstBijgewerkt && (
        <div style={{ fontSize: 13, color: "#6B5A3D", marginTop: 20, fontStyle: "italic" }}>
          Laatst bijgewerkt: {info.laatstBijgewerkt}
        </div>
      )}
    </div>
  );
}

function ReleasesModal({ data, onClose }) {
  const titel = data?.titel || "Wat is nieuw?";
  const items = Array.isArray(data?.items) ? data.items : [];

  const typeStyle = {
    feature:    { bg: "#FFD23F", label: "NIEUW" },
    milestone:  { bg: "#2D9CDB", label: "MIJLPAAL" },
    fix:        { bg: "#5BB85B", label: "FIX" },
    "in-progress": { bg: "#B86A4D", label: "IN ONTWIKKELING" },
  };

  return (
    <div style={{
      background: "#F0FAE6", border: "5px solid #1A1A1A",
      boxShadow: "10px 10px 0 #1A1A1A",
      padding: "24px 28px",
      maxWidth: 720, width: "min(720px, 92vw)", maxHeight: "88vh",
      overflowY: "auto", position: "relative",
      fontFamily: "'Patrick Hand', cursive",
      color: "#1A1A1A",
    }}>
      <button onClick={onClose} style={{
        position: "absolute", top: -18, right: -18,
        width: 44, height: 44, borderRadius: "50%",
        background: "#1A1A1A", color: "#F0FAE6",
        border: "3px solid #F0FAE6", boxShadow: "2px 2px 0 #1A1A1A",
        fontFamily: "'Bangers', sans-serif", fontSize: 22, cursor: "pointer",
      }} aria-label="Sluiten">✕</button>

      <div style={{
        fontFamily: "'Bangers', sans-serif", fontSize: 36,
        color: "#E63946", letterSpacing: "0.04em",
        WebkitTextStroke: "1.5px #1A1A1A",
        marginBottom: 6,
      }}>{titel}</div>

      {data?.intro && (
        <div style={{ fontSize: 19, lineHeight: 1.6, color: "#3A3025", marginBottom: 22, maxWidth: "62ch" }}>
          {data.intro}
        </div>
      )}

      {items.length === 0 && (
        <div style={{ fontSize: 18, color: "#6B5A3D", fontStyle: "italic" }}>
          Nog geen items om te tonen.
        </div>
      )}

      {items.map((it, i) => {
        const style = typeStyle[it.type] || { bg: "#E0E0E0", label: (it.type || "UPDATE").toUpperCase() };
        return (
          <div key={i} style={{
            marginBottom: 22, paddingBottom: 18,
            borderBottom: i === items.length - 1 ? "none" : "2px dashed #B86A4D",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", marginBottom: 6 }}>
              <span style={{
                background: style.bg, color: "#1A1A1A",
                fontFamily: "'Bangers', sans-serif", fontSize: 14,
                padding: "2px 10px", border: "2px solid #1A1A1A",
                letterSpacing: "0.05em",
              }}>{style.label}</span>
              <span style={{ fontSize: 15, color: "#6B5A3D" }}>{it.datum}</span>
            </div>
            <div style={{
              fontFamily: "'Bangers', sans-serif", fontSize: 22,
              letterSpacing: "0.03em", marginBottom: 4,
            }}>{it.titel}</div>
            {it.tekst && (
              <div style={{ fontSize: 18, lineHeight: 1.6, color: "#3A3025", whiteSpace: "pre-wrap", maxWidth: "62ch" }}>
                {it.tekst}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function StripReader({ strip, onClose }) {
  return (
    <Modal onClose={onClose}>
      <div style={{
        background: "#D6EFC7", border: "5px solid #1A1A1A",
        boxShadow: "10px 10px 0 #1A1A1A",
        padding: 20, maxWidth: 820, maxHeight: "88vh",
        overflowY: "auto",
      }}>
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          marginBottom: 14,
        }}>
          <div>
            <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 34, color: "#E63946", letterSpacing: "0.03em", WebkitTextStroke: "1.5px #1A1A1A", lineHeight: 1 }}>
              {strip.titel}
            </div>
            <div style={{ fontSize: 16, color: "#6B5A3D" }}>Aflevering #{strip.nummer}</div>
          </div>
          <button onClick={onClose} style={{
            width: 44, height: 44, borderRadius: "50%",
            background: "#1A1A1A", color: "#F0FAE6",
            border: "3px solid #F0FAE6", boxShadow: "2px 2px 0 #1A1A1A",
            fontFamily: "'Bangers', sans-serif", fontSize: 22, cursor: "pointer",
          }}>✕</button>
        </div>
        {strip.src ? (
          <img src={strip.src} alt={strip.titel}
            style={{ width: "100%", border: "3px solid #1A1A1A", display: "block" }} />
        ) : (
          <div style={{ padding: 40, textAlign: "center", fontFamily: "'Bangers', sans-serif", fontSize: 40, color: "#8B5A2B" }}>
            BINNENKORT BESCHIKBAAR!
          </div>
        )}
      </div>
    </Modal>
  );
}

function Modal({ children, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(0,0,0,0.6)",
      display: "flex", alignItems: "center", justifyContent: "center",
      zIndex: 100, padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{ position: "relative" }}>
        {children}
      </div>
    </div>
  );
}

function useTurnstile(siteKey, containerRef, onToken) {
  React.useEffect(() => {
    if (!siteKey || !containerRef.current) return;
    let widgetId = null;
    let cancelled = false;

    function render() {
      if (cancelled || !window.turnstile || !containerRef.current) return;
      try {
        widgetId = window.turnstile.render(containerRef.current, {
          sitekey: siteKey,
          callback: onToken,
          "error-callback": () => onToken(null),
          "expired-callback": () => onToken(null),
        });
      } catch {}
    }

    if (!window.turnstile) {
      const existing = document.querySelector("script[data-turnstile]");
      if (!existing) {
        const s = document.createElement("script");
        s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";
        s.async = true; s.defer = true;
        s.setAttribute("data-turnstile", "1");
        s.onload = render;
        document.head.appendChild(s);
      } else {
        existing.addEventListener("load", render);
      }
    } else {
      render();
    }

    return () => {
      cancelled = true;
      if (widgetId && window.turnstile) {
        try { window.turnstile.remove(widgetId); } catch {}
      }
    };
  }, [siteKey]);
}

function SubmissionForm({ kind, config, onClose }) {
  const isDrawing = kind === "drawing";
  const [naam, setNaam] = React.useState("");
  const [leeftijd, setLeeftijd] = React.useState("");
  const [bericht, setBericht] = React.useState("");
  const [idee, setIdee] = React.useState("");
  const [categorie, setCategorie] = React.useState("vijand");
  const [file, setFile] = React.useState(null);
  const [token, setToken] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const captchaRef = React.useRef(null);

  useTurnstile(config?.turnstileSiteKey, captchaRef, setToken);

  async function submit(e) {
    e.preventDefault();
    setBusy(true); setErr(null);
    try {
      if (isDrawing) {
        if (!file) throw new Error("Kies eerst een tekening");
        const fd = new FormData();
        fd.append("image", file);
        fd.append("naam", naam);
        fd.append("leeftijd", leeftijd);
        fd.append("bericht", bericht);
        if (token) fd.append("captchaToken", token);
        const r = await fetch("/api/submissions/drawing", { method: "POST", body: fd });
        if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || "Verzenden mislukt");
      } else {
        if (!idee.trim()) throw new Error("Schrijf je idee");
        const r = await fetch("/api/submissions/suggestion", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ naam, idee, categorie, captchaToken: token }),
        });
        if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || "Verzenden mislukt");
      }
      setDone(true);
    } catch (e) {
      setErr(e.message);
    } finally {
      setBusy(false);
    }
  }

  if (done) {
    return (
      <div style={formStyle}>
        <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 40, color: "#3FA34D", letterSpacing: "0.03em" }}>
          DANKJEWEL! 🔥
        </div>
        <div style={{ fontSize: 18, marginTop: 10 }}>
          We hebben je {isDrawing ? "tekening" : "idee"} ontvangen. Mama of papa kijkt er snel naar!
        </div>
        <div style={{ marginTop: 18 }}>
          <button className="btn-comic rood" onClick={onClose}>SLUITEN</button>
        </div>
      </div>
    );
  }

  return (
    <form onSubmit={submit} style={formStyle}>
      <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 32, color: "#E63946", letterSpacing: "0.03em", lineHeight: 1 }}>
        {isDrawing ? "UPLOAD JE TEKENING" : "BEDENK EEN NIEUWE VIJAND"}
      </div>
      <div style={{ fontSize: 15, color: "#6B5A3D", marginTop: 4, marginBottom: 14 }}>
        Vraag het altijd eerst aan mama of papa voor je iets inzendt.
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 120px", gap: 10 }}>
        <div style={fieldCol}>
          <label style={lbl}>Jouw naam (of bijnaam)</label>
          <input style={inp} value={naam} onChange={e => setNaam(e.target.value)} maxLength={80} />
        </div>
        {isDrawing && (
          <div style={fieldCol}>
            <label style={lbl}>Leeftijd</label>
            <input style={inp} type="number" min="0" max="99" value={leeftijd} onChange={e => setLeeftijd(e.target.value)} />
          </div>
        )}
      </div>

      {isDrawing ? (
        <>
          <div style={fieldCol}>
            <label style={lbl}>Jouw tekening (png/jpg, max 5 MB)</label>
            <input type="file" accept="image/*" onChange={e => setFile(e.target.files?.[0] || null)} />
          </div>
          <div style={fieldCol}>
            <label style={lbl}>Berichtje (optioneel)</label>
            <textarea style={ta} value={bericht} onChange={e => setBericht(e.target.value)} maxLength={500} />
          </div>
        </>
      ) : (
        <>
          <div style={fieldCol}>
            <label style={lbl}>Wat is het?</label>
            <select style={inp} value={categorie} onChange={e => setCategorie(e.target.value)}>
              <option value="vijand">Een nieuwe vijand</option>
              <option value="strip">Een strip-idee</option>
              <option value="spel">Een spelletjes-idee</option>
              <option value="anders">Iets anders</option>
            </select>
          </div>
          <div style={fieldCol}>
            <label style={lbl}>Beschrijf je idee</label>
            <textarea style={ta} value={idee} onChange={e => setIdee(e.target.value)} maxLength={2000} />
          </div>
        </>
      )}

      {config?.turnstileSiteKey ? (
        <div ref={captchaRef} style={{ marginTop: 10 }} />
      ) : (
        <div style={{ fontSize: 13, color: "#6B5A3D", marginTop: 10 }}>
          (Captcha niet actief — dev-modus)
        </div>
      )}

      {err && <div style={{ color: "#E63946", marginTop: 10 }}>{err}</div>}

      <div style={{ marginTop: 16, display: "flex", gap: 10 }}>
        <button type="submit" className="btn-comic groen" disabled={busy || (config?.captchaEnabled && !token)}>
          {busy ? "VERZENDEN…" : "🔥 VERSTUREN"}
        </button>
        <button type="button" className="btn-comic" onClick={onClose}>ANNULEREN</button>
      </div>
    </form>
  );
}

const formStyle = {
  background: "#F0FAE6", border: "5px solid #1A1A1A",
  boxShadow: "8px 8px 0 #1A1A1A", padding: 26,
  width: "min(560px, 92vw)", position: "relative",
  fontFamily: "'Patrick Hand', cursive",
};
const fieldCol = { display: "flex", flexDirection: "column", gap: 4, marginBottom: 10 };
const lbl = { fontFamily: "'Bangers', sans-serif", fontSize: 14, letterSpacing: "0.05em", color: "#6B5A3D" };
const inp = { border: "3px solid #1A1A1A", background: "#FFF", padding: "8px 10px", fontFamily: "inherit", fontSize: 16, boxShadow: "2px 2px 0 #1A1A1A" };
const ta = { ...inp, minHeight: 80, resize: "vertical" };

function OpbouwDisclaimer({ titel, tekst, onClose }) {
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 2000,
      background: "rgba(0,0,0,0.65)",
      display: "flex", alignItems: "center", justifyContent: "center",
      padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: "#FFF8EC",
        border: "6px solid #1A1A1A",
        boxShadow: "16px 16px 0 #1A1A1A",
        maxWidth: 1400, width: "100%",
        position: "relative",
        padding: "48px 56px 44px",
        display: "grid",
        gridTemplateColumns: "minmax(360px, 520px) minmax(0, 1fr)",
        gap: 44,
        alignItems: "center",
        backgroundImage: "radial-gradient(circle, rgba(230,57,70,0.08) 1.4px, transparent 1.6px)",
        backgroundSize: "10px 10px",
      }}>
        <button onClick={onClose} aria-label="Sluiten" style={{
          position: "absolute", top: -22, right: -22,
          width: 52, height: 52, borderRadius: "50%",
          background: "#1A1A1A", color: "#FFF8EC",
          border: "4px solid #FFF8EC",
          boxShadow: "3px 3px 0 #1A1A1A",
          fontFamily: "'Bangers', sans-serif", fontSize: 26,
          cursor: "pointer", lineHeight: 1,
        }}>✕</button>

        <img src="/assets/hete-peper-shy.png" alt="Verlegen Hete Peper"
          style={{
            width: "100%", height: "auto", display: "block",
            filter: "drop-shadow(8px 8px 0 rgba(0,0,0,0.25))",
            transform: "rotate(-3deg)",
          }} />

        <div>
          <div style={{
            background: "#FFD23F", border: "4px solid #1A1A1A",
            boxShadow: "4px 4px 0 #1A1A1A",
            display: "inline-block", padding: "4px 14px",
            fontFamily: "'Bangers', sans-serif", fontSize: 18,
            letterSpacing: "0.1em", color: "#1A1A1A",
            transform: "rotate(-2deg)", marginBottom: 14,
          }}>🚧 IN OPBOUW 🚧</div>

          <div style={{
            fontFamily: "'Bangers', sans-serif",
            fontSize: 64, lineHeight: 0.95,
            color: "#E63946", WebkitTextStroke: "3px #1A1A1A",
            textShadow: "8px 8px 0 #1A1A1A", letterSpacing: "0.03em",
            marginBottom: 24,
          }}>{titel || "PSST… DEZE WEBSITE IS NOG IN OPBOUW!"}</div>

          <div style={{
            fontFamily: "'Patrick Hand', cursive",
            fontSize: 28, lineHeight: 1.4, color: "#2A2118",
            whiteSpace: "pre-wrap",
            background: "#FFF", border: "4px solid #1A1A1A",
            boxShadow: "6px 6px 0 #1A1A1A",
            padding: "22px 28px",
          }}>{tekst}</div>

          <div style={{ marginTop: 28, textAlign: "right" }}>
            <button onClick={onClose} className="btn-comic groen" style={{
              fontFamily: "'Bangers', sans-serif", fontSize: 30,
              padding: "14px 34px", letterSpacing: "0.04em",
              cursor: "pointer",
            }}>
              OKÉ, IK BEGRIJP HET! 🌶️
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ComicBookHome, OpbouwDisclaimer });
