// Shared components: Router, Header, Footer, Doodle primitives
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

// ============ Router (file-based) ============
// Each route is a real .html file (about.html, games.html, etc.). The current
// page is read from window.__page (set by each HTML file). go(route) navigates
// to that file. Hash links still work as fallback.
const ROUTE_FILES = {
  home: "index.html",
  about: "about.html",
  games: "games.html",
  cafe: "cafe.html",
  pricing: "pricing.html",
  faq: "faq.html",
  contact: "contact.html",
  booking: "booking.html",
};
const RouterCtx = createContext({ path: "home", go: () => {} });
function RouterProvider({ children }) {
  const initial = window.__page || (location.hash.replace("#/", "") || "home");
  const [path, setPath] = useState(initial);
  useEffect(() => {
    const onHash = () => {
      const p = location.hash.replace("#/", "");
      if (p && p !== path) setPath(p);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, [path]);
  const go = useCallback((p) => {
    const file = ROUTE_FILES[p];
    if (file) {
      window.location.href = file;
    } else {
      location.hash = "#/" + p;
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  }, []);
  return <RouterCtx.Provider value={{ path, go }}>{children}</RouterCtx.Provider>;
}
const useRouter = () => useContext(RouterCtx);

// ============ Language / Tweaks bridge ============
// Read tweaks from global window.__pixelTweaks set by the Tweaks panel.
// Default values are duplicated here so pages work even before tweaks mount.
const TweaksCtx = createContext({ lang: "en", palette: "sunshine", aesthetic: "crayon" });
function useT() {
  const ctx = useContext(TweaksCtx);
  const lang = ctx.lang === "th" ? "th" : "en";
  return { ...ctx, lang, L: window.I18N[lang], OTHER: window.I18N[lang === "th" ? "en" : "th"] };
}

// ============ Doodle SVG defs ============
// One <svg> in the body with global defs (wobble filters, markers).
function DoodleDefs() {
  return (
    <svg width="0" height="0" style={{ position: "absolute" }} aria-hidden="true">
      <defs>
        <filter id="wobble">
          <feTurbulence type="fractalNoise" baseFrequency="0.02" numOctaves="2" seed="3" />
          <feDisplacementMap in="SourceGraphic" scale="3" />
        </filter>
        <filter id="wobble-soft">
          <feTurbulence type="fractalNoise" baseFrequency="0.015" numOctaves="2" seed="7" />
          <feDisplacementMap in="SourceGraphic" scale="1.5" />
        </filter>
        <filter id="rough" x="-5%" y="-5%" width="110%" height="110%">
          <feTurbulence type="fractalNoise" baseFrequency="0.04" numOctaves="3" seed="11" />
          <feDisplacementMap in="SourceGraphic" scale="2.5" />
        </filter>
      </defs>
    </svg>
  );
}

// ============ Doodle primitives ============
function Star({ size = 40, color = "var(--red)", style }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={style} aria-hidden="true">
      <path d="M50 5 L60 38 L95 40 L67 60 L78 92 L50 73 L22 92 L33 60 L5 40 L40 38 Z"
        fill={color} stroke="var(--ink)" strokeWidth="4" strokeLinejoin="round" filter="url(#wobble-soft)" />
    </svg>
  );
}

function Squiggle({ width = 200, color = "var(--ink)", strokeWidth = 4, style }) {
  return (
    <svg width={width} height={20} viewBox="0 0 200 20" style={style} aria-hidden="true">
      <path d="M2 10 Q15 2, 28 10 T54 10 T80 10 T106 10 T132 10 T158 10 T184 10 T200 10"
        fill="none" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" />
    </svg>
  );
}

function Underline({ width = 200, color = "var(--red)", style }) {
  return (
    <svg width={width} height={14} viewBox="0 0 200 14" style={style} aria-hidden="true">
      <path d="M3 8 Q50 -2, 100 6 T197 5" fill="none" stroke={color} strokeWidth="6" strokeLinecap="round" filter="url(#wobble-soft)" />
    </svg>
  );
}

function ArrowDoodle({ width = 100, color = "var(--ink)", style, dir = "right" }) {
  const transform = dir === "right" ? undefined : dir === "left" ? "scale(-1,1) translate(-100,0)" : "rotate(90, 50, 30)";
  return (
    <svg width={width} height={60} viewBox="0 0 100 60" style={style} aria-hidden="true">
      <g transform={transform} filter="url(#wobble-soft)">
        <path d="M5 30 Q40 5, 75 30" fill="none" stroke={color} strokeWidth="4" strokeLinecap="round" />
        <path d="M75 30 L65 22 M75 30 L65 38" fill="none" stroke={color} strokeWidth="4" strokeLinecap="round" />
      </g>
    </svg>
  );
}

function Burst({ size = 90, color = "var(--green)", style }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={style} aria-hidden="true">
      <g filter="url(#wobble-soft)">
        {[0,1,2,3,4,5,6,7,8,9,10,11].map(i => {
          const a = (i / 12) * Math.PI * 2;
          const r1 = i % 2 === 0 ? 44 : 26;
          const x = 50 + Math.cos(a) * r1;
          const y = 50 + Math.sin(a) * r1;
          return null;
        })}
        <path d="M50 4 L58 36 L92 30 L66 52 L88 80 L54 70 L46 96 L40 70 L8 78 L30 52 L4 30 L42 36 Z"
          fill={color} stroke="var(--ink)" strokeWidth="3" strokeLinejoin="round" />
      </g>
    </svg>
  );
}

function Sparkle({ size = 22, color = "var(--orange)", style }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={style} aria-hidden="true">
      <path d="M12 1 L14 10 L23 12 L14 14 L12 23 L10 14 L1 12 L10 10 Z" fill={color} stroke="var(--ink)" strokeWidth="1.5" strokeLinejoin="round" />
    </svg>
  );
}

function Cloud({ size = 80, color = "var(--paper)", style }) {
  return (
    <svg width={size} height={size * 0.6} viewBox="0 0 100 60" style={style} aria-hidden="true">
      <path d="M20 45 Q5 45, 8 30 Q5 18, 22 18 Q28 8, 42 12 Q52 4, 65 14 Q82 12, 82 28 Q95 32, 88 45 Z"
        fill={color} stroke="var(--ink)" strokeWidth="3" strokeLinejoin="round" filter="url(#wobble-soft)" />
    </svg>
  );
}

function Tape({ width = 100, rotation = -3, color = "rgba(255,59,107,0.5)", style }) {
  return (
    <div style={{
      position: "absolute",
      width,
      height: 26,
      background: color,
      backgroundImage: "repeating-linear-gradient(45deg, rgba(255,255,255,0.25) 0 6px, transparent 6px 12px)",
      transform: `rotate(${rotation}deg)`,
      borderLeft: "1px dashed rgba(0,0,0,0.25)",
      borderRight: "1px dashed rgba(0,0,0,0.25)",
      ...style,
    }} />
  );
}

// Placeholder for a kid's drawing (intentionally chunky/cute)
function KidDoodle({ kind = "blob", color = "var(--red)", size = 100, style }) {
  const shapes = {
    blob: (
      <path d="M50 8 Q78 8, 86 36 Q96 60, 78 80 Q60 96, 36 88 Q10 80, 10 52 Q10 22, 50 8 Z"
        fill={color} stroke="var(--ink)" strokeWidth="4" strokeLinejoin="round" />
    ),
    monster: (
      <g>
        <path d="M20 30 Q15 12, 32 12 Q40 4, 50 12 Q60 4, 68 12 Q85 12, 80 30 L84 70 Q84 88, 70 88 Q60 96, 50 88 Q40 96, 30 88 Q16 88, 16 70 Z"
          fill={color} stroke="var(--ink)" strokeWidth="4" strokeLinejoin="round" />
        <circle cx="38" cy="42" r="7" fill="white" stroke="var(--ink)" strokeWidth="2" />
        <circle cx="62" cy="42" r="7" fill="white" stroke="var(--ink)" strokeWidth="2" />
        <circle cx="38" cy="44" r="3" fill="var(--ink)" />
        <circle cx="62" cy="44" r="3" fill="var(--ink)" />
        <path d="M38 64 Q50 72, 62 64" stroke="var(--ink)" strokeWidth="3" fill="none" strokeLinecap="round" />
        <path d="M22 16 L18 8 M78 16 L82 8" stroke="var(--ink)" strokeWidth="3" strokeLinecap="round" />
      </g>
    ),
    rocket: (
      <g>
        <path d="M50 6 Q30 22, 30 60 L30 78 L70 78 L70 60 Q70 22, 50 6 Z" fill={color} stroke="var(--ink)" strokeWidth="4" strokeLinejoin="round" />
        <circle cx="50" cy="38" r="9" fill="var(--paper)" stroke="var(--ink)" strokeWidth="3" />
        <path d="M30 60 L14 80 L30 78 Z M70 60 L86 80 L70 78 Z" fill="var(--blue)" stroke="var(--ink)" strokeWidth="3" strokeLinejoin="round" />
        <path d="M40 82 Q42 92, 48 86 Q50 96, 54 86 Q58 92, 60 82" stroke="var(--orange)" strokeWidth="4" fill="var(--orange)" strokeLinejoin="round" />
      </g>
    ),
    star: (
      <path d="M50 6 L62 36 L94 38 L68 60 L78 92 L50 74 L22 92 L32 60 L6 38 L38 36 Z"
        fill={color} stroke="var(--ink)" strokeWidth="4" strokeLinejoin="round" />
    ),
    cat: (
      <g>
        <path d="M22 30 L14 14 L36 22 Q50 16, 64 22 L86 14 L78 30 Q92 44, 86 64 Q80 88, 50 88 Q20 88, 14 64 Q8 44, 22 30 Z"
          fill={color} stroke="var(--ink)" strokeWidth="4" strokeLinejoin="round" />
        <circle cx="38" cy="50" r="4" fill="var(--ink)" />
        <circle cx="62" cy="50" r="4" fill="var(--ink)" />
        <path d="M48 62 L50 66 L52 62 Z" fill="var(--ink)" />
        <path d="M40 70 Q50 76, 60 70" stroke="var(--ink)" strokeWidth="2.5" fill="none" />
        <path d="M28 62 L18 64 M28 66 L18 70 M72 62 L82 64 M72 66 L82 70" stroke="var(--ink)" strokeWidth="2" />
      </g>
    ),
    food: (
      <g>
        <path d="M14 60 Q14 30, 50 30 Q86 30, 86 60 L86 70 Q86 76, 80 76 L20 76 Q14 76, 14 70 Z"
          fill="var(--orange)" stroke="var(--ink)" strokeWidth="4" strokeLinejoin="round" />
        <path d="M14 60 Q50 50, 86 60" stroke="var(--ink)" strokeWidth="3" fill="none" />
        <circle cx="36" cy="40" r="6" fill="var(--red)" stroke="var(--ink)" strokeWidth="2" />
        <circle cx="58" cy="36" r="5" fill="var(--green)" stroke="var(--ink)" strokeWidth="2" />
        <circle cx="70" cy="44" r="4" fill="var(--purple)" stroke="var(--ink)" strokeWidth="2" />
      </g>
    ),
  };
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={style} aria-hidden="true">
      <g filter="url(#wobble-soft)">{shapes[kind] || shapes.blob}</g>
    </svg>
  );
}

// ============ Site Header ============
function SiteHeader() {
  const { path, go } = useRouter();
  const { lang } = useT();
  const L = window.I18N[lang];
  const [mobileOpen, setMobileOpen] = useState(false);

  const links = [
    ["home", L.nav.home],
    ["about", L.nav.about],
    ["games", L.nav.games],
    ["cafe", L.nav.cafe],
    ["pricing", L.nav.pricing],
    ["faq", L.nav.faq],
    ["contact", L.nav.contact],
  ];

  const fileFor = (k) => ROUTE_FILES[k] || "index.html";

  return (
    <header className="site-header">
      <div className="nav-inner">
        <a className="logo" href="index.html" onClick={(e) => { e.preventDefault(); go("home"); }}>
          <div className="logo-mark" aria-hidden="true">
            <div /><div /><div /><div /><div /><div /><div /><div /><div />
          </div>
          <div className="logo-name">
            Pixel Craft
            <small>make games like a kid</small>
          </div>
        </a>
        <ul className={"nav-links" + (mobileOpen ? " open" : "")}>
          {links.map(([k, label]) => (
            <li key={k}>
              <a href={fileFor(k)} className={"nav-link" + (path === k ? " active" : "")} onClick={(e) => { e.preventDefault(); go(k); setMobileOpen(false); }}>
                {label}
              </a>
            </li>
          ))}
        </ul>
        <div className="nav-actions">
          <LanguageToggle />
          <a className="btn btn-red btn-small" href="booking.html" onClick={(e) => { e.preventDefault(); go("booking"); }}>{L.nav.book}</a>
          <button className="nav-mobile-btn" onClick={() => setMobileOpen(!mobileOpen)} aria-label="Menu">☰</button>
        </div>
      </div>
    </header>
  );
}

function LanguageToggle() {
  const { lang } = useT();
  const setLang = (l) => {
    window.dispatchEvent(new CustomEvent("pixelcraft:setTweak", { detail: { key: "language", value: l } }));
  };
  return (
    <div className="lang-toggle" role="group" aria-label="Language">
      <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
      <button className={lang === "th" ? "active" : ""} onClick={() => setLang("th")}>TH</button>
    </div>
  );
}

// ============ Site Footer ============
function SiteFooter() {
  const { go } = useRouter();
  const { lang } = useT();
  const L = window.I18N[lang];
  return (
    <footer className="site-footer">
      <div className="container">
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
            <div className="logo-mark" aria-hidden="true" style={{ transform: "rotate(-4deg)" }}>
              <div /><div /><div /><div /><div /><div /><div /><div /><div />
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: "1.4rem" }}>Pixel Craft</div>
          </div>
          <p className="hand" style={{ fontSize: "1.15rem", margin: 0, opacity: 0.85, maxWidth: 280 }}>
            {lang === "th"
              ? "แล็บนวัตกรรมเล็กๆ ที่เด็กออกแบบเกมเอง — ไม่มีโค้ด มีแต่ความคิดสร้างสรรค์"
              : "A tiny innovation lab where kids design real games — no code, all imagination."}
          </p>
        </div>
        <div>
          <h4>{lang === "th" ? "สำรวจ" : "Explore"}</h4>
          <a href="about.html" onClick={(e) => { e.preventDefault(); go("about"); }}>{L.nav.about}</a>
          <a href="games.html" onClick={(e) => { e.preventDefault(); go("games"); }}>{L.nav.games}</a>
          <a href="cafe.html" onClick={(e) => { e.preventDefault(); go("cafe"); }}>{L.nav.cafe}</a>
          <a href="pricing.html" onClick={(e) => { e.preventDefault(); go("pricing"); }}>{L.nav.pricing}</a>
        </div>
        <div>
          <h4>{lang === "th" ? "ช่วยเหลือ" : "Help"}</h4>
          <a href="faq.html" onClick={(e) => { e.preventDefault(); go("faq"); }}>{L.nav.faq}</a>
          <a href="contact.html" onClick={(e) => { e.preventDefault(); go("contact"); }}>{L.nav.contact}</a>
          <a href="booking.html" onClick={(e) => { e.preventDefault(); go("booking"); }}>{L.nav.book}</a>
        </div>
        <div>
          <h4>{lang === "th" ? "ตามมาเลย" : "Follow along"}</h4>
          <a href="#">Instagram</a>
          <a href="#">TikTok</a>
          <a href="#">YouTube</a>
          <a href="#">LINE</a>
        </div>
        <div className="footer-bottom">
          © 2026 Pixel Craft Co. — {lang === "th" ? "ทำด้วยรักและกลิตเตอร์" : "made with glitter and love"} ✨
        </div>
      </div>
    </footer>
  );
}

// ============ Marquee strip ============
function FunMarquee() {
  const { lang } = useT();
  const items = lang === "th"
    ? ["สนุก!", "★", "ไม่ต้องเขียนโค้ด", "★", "เกมจริง", "★", "เล่นได้จริง", "★", "แชร์ได้", "★", "อายุ 6–10"]
    : ["FUN!", "★", "NO CODE", "★", "REAL GAMES", "★", "REALLY PLAYS", "★", "SHAREABLE", "★", "AGES 6–10"];
  const row = (
    <span>
      {items.map((it, i) => <span key={i}>{it}</span>)}
    </span>
  );
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        {row}{row}{row}{row}
      </div>
    </div>
  );
}

// Export to global so other Babel scripts can use them
Object.assign(window, {
  ROUTE_FILES,
  RouterProvider, RouterCtx, useRouter,
  TweaksCtx, useT,
  DoodleDefs, Star, Squiggle, Underline, ArrowDoodle, Burst, Sparkle, Cloud, Tape, KidDoodle,
  SiteHeader, SiteFooter, FunMarquee,
});
