// Home page — Pixel Craft

function HomePage() {
  const { go } = useRouter();
  const { lang } = useT();
  const L = window.I18N[lang].home;
  return (
    <div className="page-enter">
      <Hero L={L} go={go} lang={lang} />
      <FunMarquee />
      <HowItWorks L={L} lang={lang} />
      <TemplatesStrip lang={lang} go={go} />
      <FeaturedGames L={L} lang={lang} go={go} />
      <CafeTeaser L={L} lang={lang} go={go} />
      <BigCTA L={L} go={go} lang={lang} />
    </div>
  );
}

// ============ Hero ============
function Hero({ L, go, lang }) {
  return (
    <section style={{ paddingTop: 40, paddingBottom: 40, position: "relative", overflow: "hidden" }}>
      {/* Floating doodles in corners */}
      <div style={{ position: "absolute", top: 30, right: 60, opacity: 0.6 }} className="bouncey">
        <Star size={60} color="var(--green)" />
      </div>
      <div className="bouncey" style={{ position: "absolute", bottom: 40, left: 40, opacity: 0.7, animationDelay: "0.6s" }}>
        <Sparkle size={40} color="var(--red)" />
      </div>

      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "1.05fr 1fr", gap: 40, alignItems: "center" }} className="hero-grid">
          <div>
            <div className="eyebrow">{L.eyebrow} ✏️</div>
            <h1 style={{ marginTop: 20, marginBottom: 16 }}>
              <span style={{ display: "inline-block" }}>{L.title1}</span>
              <br />
              <span style={{ display: "inline-block", position: "relative" }}>
                {L.title2}
                <Underline width={280} color="var(--red)" style={{ position: "absolute", left: 0, bottom: -8 }} />
              </span>
              <br />
              <span style={{ color: "var(--blue)", display: "inline-block", transform: "rotate(-1deg)" }}>{L.title3}</span>
              <Sparkle size={30} color="var(--orange)" style={{ display: "inline-block", marginLeft: 10, verticalAlign: "middle" }} />
            </h1>
            <p style={{ fontSize: "1.2rem", maxWidth: 540, marginBottom: 28 }}>{L.sub}</p>
            <div className="row">
              <a className="btn btn-red btn-big" href="#/booking" onClick={(e) => { e.preventDefault(); go("booking"); }}>
                {L.ctaPrimary} 🎮
              </a>
              <a className="btn btn-big" href="#/games" onClick={(e) => { e.preventDefault(); go("games"); }}>
                {L.ctaSecondary}
              </a>
            </div>
            <div className="row mt-4" style={{ gap: 28 }}>
              <Stat n="2,400+" label={lang === "th" ? "เกมที่เด็กทำ" : "kid-made games"} />
              <Stat n="4" label={lang === "th" ? "แม่แบบเกม" : "game templates"} />
              <Stat n="90" label={lang === "th" ? "นาที = 1 เกม" : "min = 1 game"} />
            </div>
          </div>

          <HeroDemo L={L} lang={lang} />
        </div>
      </div>

      <style>{`
        @media (max-width: 980px) {
          .hero-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

function Stat({ n, label }) {
  return (
    <div>
      <div style={{ fontFamily: "var(--font-display)", fontSize: "1.8rem", lineHeight: 1 }}>{n}</div>
      <div className="hand" style={{ fontSize: "1.05rem", opacity: 0.75 }}>{label}</div>
    </div>
  );
}

// ============ Hero Demo: animated draw → game ============
function HeroDemo({ L, lang }) {
  const [phase, setPhase] = useState(0); // 0=draw, 1=cut, 2=game
  const [tick, setTick] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setPhase(p => (p + 1) % 3);
    }, 3200);
    return () => clearInterval(id);
  }, []);

  // Game animation ticker
  useEffect(() => {
    if (phase !== 2) return;
    let raf;
    const start = performance.now();
    const loop = () => {
      setTick((performance.now() - start) / 1000);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [phase]);

  const labels = [L.heroLabelDraw, L.heroLabelSound, L.heroLabelGame];

  return (
    <div style={{ position: "relative" }}>
      {/* Phase label */}
      <div style={{
        position: "absolute", top: -10, left: "50%", transform: "translateX(-50%) rotate(-3deg)", zIndex: 5,
      }}>
        <div className="pill" style={{ background: ["var(--green)", "var(--orange)", "var(--red)"][phase], color: "#fff", padding: "6px 18px", fontSize: "1.1rem", border: "3px solid var(--ink)", boxShadow: "3px 3px 0 var(--ink)" }}>
          {labels[phase]}
        </div>
      </div>

      <div className="card" style={{
        background: "var(--paper)",
        padding: 28,
        transform: "rotate(1.5deg)",
        position: "relative",
        aspectRatio: "1 / 1",
        display: "flex",
        flexDirection: "column",
      }}>
        <div className="tape" style={{ background: "var(--blue)", opacity: 0.6 }} />
        <DemoStage phase={phase} tick={tick} lang={lang} />

        {/* Phase dots */}
        <div style={{ display: "flex", gap: 8, justifyContent: "center", marginTop: 12 }}>
          {[0, 1, 2].map(i => (
            <div key={i} style={{
              width: i === phase ? 28 : 12, height: 12,
              borderRadius: 99,
              background: i === phase ? "var(--ink)" : "rgba(0,0,0,0.2)",
              transition: "width 0.3s",
            }} />
          ))}
        </div>
      </div>

      {/* Floating doodles around hero card */}
      <div style={{ position: "absolute", top: -20, right: -20, transform: "rotate(15deg)" }} className="bouncey">
        <Sparkle size={36} color="var(--orange)" />
      </div>
      <div className="bouncey" style={{ position: "absolute", bottom: -10, left: -20, transform: "rotate(-12deg)", animationDelay: "0.4s" }}>
        <Star size={50} color="var(--purple)" />
      </div>
    </div>
  );
}

function DemoStage({ phase, tick, lang }) {
  return (
    <div style={{
      flex: 1,
      background: "#fffaca",
      border: "3px dashed var(--ink)",
      borderRadius: 12,
      position: "relative",
      overflow: "hidden",
    }}>
      {/* PHASE 0: drawing strokes appear */}
      {phase === 0 && <DrawPhase key="draw" />}
      {/* PHASE 1: sound waves around the sprite */}
      {phase === 1 && <SoundPhase key="sound" />}
      {/* PHASE 2: tiny game with sprite jumping over obstacles */}
      {phase === 2 && <GamePhase key="game" tick={tick} />}
    </div>
  );
}

function DrawPhase() {
  // animate stroke-dashoffset on each path
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const paths = ref.current.querySelectorAll("path,circle");
    paths.forEach((p) => {
      try {
        const len = p.getTotalLength ? p.getTotalLength() : 300;
        p.style.strokeDasharray = String(len);
        p.style.strokeDashoffset = String(len);
        p.style.transition = "none";
        // force reflow
        // eslint-disable-next-line no-unused-expressions
        p.getBoundingClientRect();
        p.style.transition = `stroke-dashoffset 1.6s ease`;
        p.style.strokeDashoffset = "0";
      } catch (e) {}
    });
  }, []);
  return (
    <svg ref={ref} viewBox="0 0 200 200" style={{ width: "100%", height: "100%", display: "block" }}>
      {/* monster body */}
      <path d="M50 80 Q40 40, 80 30 Q100 20, 120 30 Q160 40, 150 80 L155 150 Q155 175, 130 175 Q115 185, 100 175 Q85 185, 70 175 Q45 175, 45 150 Z"
        fill="var(--red)" stroke="var(--ink)" strokeWidth="5" strokeLinejoin="round" />
      {/* eyes */}
      <circle cx="85" cy="85" r="12" fill="white" stroke="var(--ink)" strokeWidth="3" />
      <circle cx="115" cy="85" r="12" fill="white" stroke="var(--ink)" strokeWidth="3" />
      <circle cx="85" cy="88" r="5" fill="var(--ink)" stroke="var(--ink)" strokeWidth="1" />
      <circle cx="115" cy="88" r="5" fill="var(--ink)" stroke="var(--ink)" strokeWidth="1" />
      {/* mouth */}
      <path d="M82 120 Q100 135, 118 120" fill="none" stroke="var(--ink)" strokeWidth="4" strokeLinecap="round" />
      {/* horns */}
      <path d="M58 38 L52 22 M142 38 L148 22" fill="none" stroke="var(--ink)" strokeWidth="4" strokeLinecap="round" />
    </svg>
  );
}

function SoundPhase() {
  return (
    <div style={{ position: "relative", width: "100%", height: "100%" }}>
      <svg viewBox="0 0 200 200" style={{ width: "100%", height: "100%", display: "block" }}>
        <g filter="url(#wobble-soft)">
          {/* same monster, now sitting */}
          <path d="M50 80 Q40 40, 80 30 Q100 20, 120 30 Q160 40, 150 80 L155 150 Q155 175, 130 175 Q115 185, 100 175 Q85 185, 70 175 Q45 175, 45 150 Z"
            fill="var(--red)" stroke="var(--ink)" strokeWidth="5" strokeLinejoin="round" />
          <circle cx="85" cy="85" r="12" fill="white" stroke="var(--ink)" strokeWidth="3" />
          <circle cx="115" cy="85" r="12" fill="white" stroke="var(--ink)" strokeWidth="3" />
          <circle cx="85" cy="88" r="5" fill="var(--ink)" />
          <circle cx="115" cy="88" r="5" fill="var(--ink)" />
          {/* open mouth (singing) */}
          <ellipse cx="100" cy="125" rx="14" ry="10" fill="var(--ink)" stroke="var(--ink)" strokeWidth="3" />
          <path d="M58 38 L52 22 M142 38 L148 22" fill="none" stroke="var(--ink)" strokeWidth="4" strokeLinecap="round" />
        </g>
      </svg>
      {/* Sound bars */}
      <div style={{ position: "absolute", top: 30, right: 10, display: "flex", gap: 6, alignItems: "flex-end", height: 50 }}>
        {[0,1,2,3,4].map(i => (
          <div key={i} style={{
            width: 8,
            height: "100%",
            background: "var(--blue)",
            border: "2px solid var(--ink)",
            borderRadius: 2,
            animation: `soundBar 0.7s ${i*0.1}s ease-in-out infinite alternate`,
          }} />
        ))}
      </div>
      {/* Sound ripples */}
      {[0,1,2].map(i => (
        <div key={i} style={{
          position: "absolute",
          top: "50%", left: "50%",
          width: 60, height: 60,
          marginTop: -30, marginLeft: -30,
          border: "3px solid var(--ink)",
          borderRadius: "50%",
          animation: `ripple 2s ${i*0.4}s ease-out infinite`,
          opacity: 0,
        }} />
      ))}
      <style>{`
        @keyframes soundBar { from { height: 10%; } to { height: 100%; } }
        @keyframes ripple {
          0% { transform: scale(0.5); opacity: 0.6; }
          100% { transform: scale(2.2); opacity: 0; }
        }
      `}</style>
      {/* Little note doodles */}
      <div style={{ position: "absolute", top: 18, left: 18, fontFamily: "var(--font-display)", fontSize: 22 }}>♪</div>
      <div style={{ position: "absolute", bottom: 24, left: 10, fontFamily: "var(--font-display)", fontSize: 18 }}>♫</div>
    </div>
  );
}

function GamePhase({ tick }) {
  // Hero jumps over obstacles in a tiny side-scroller
  const jumpY = Math.max(0, Math.sin(tick * 3.2) * 38);
  const scroll = (tick * 60) % 200;
  return (
    <div style={{ position: "relative", width: "100%", height: "100%" }}>
      {/* Sky / clouds */}
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, #BEE7FF 0%, #FFFAC5 70%)" }} />
      <div style={{ position: "absolute", top: 18, left: 20 + Math.sin(tick * 0.5) * 10 }}>
        <Cloud size={50} />
      </div>
      <div style={{ position: "absolute", top: 32, right: 30 }}>
        <Cloud size={36} />
      </div>
      {/* Ground */}
      <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 40, background: "var(--green)", borderTop: "3px solid var(--ink)" }} />
      {/* Score */}
      <div className="pill" style={{ position: "absolute", top: 8, right: 8, background: "var(--ink)", color: "var(--paper)", fontFamily: "var(--font-pixel)", fontSize: 11, padding: "4px 8px" }}>
        {String(Math.floor(tick * 100)).padStart(5, "0")}
      </div>
      {/* Obstacles (cacti made of red blobs) - scroll left */}
      {[0,1,2].map(i => {
        const x = ((i * 200 - scroll * 1.5) % 280 + 280) % 280 - 30;
        return (
          <div key={i} style={{ position: "absolute", bottom: 40, left: x }}>
            <svg width="30" height="40" viewBox="0 0 30 40">
              <path d="M12 4 Q4 4, 4 14 L4 36 L26 36 L26 14 Q26 4, 18 4 Z" fill="var(--purple)" stroke="var(--ink)" strokeWidth="3" />
            </svg>
          </div>
        );
      })}
      {/* Hero */}
      <div style={{
        position: "absolute",
        left: 40,
        bottom: 40 + jumpY,
        transition: "none",
      }}>
        <svg width="44" height="50" viewBox="0 0 100 100">
          <g filter="url(#wobble-soft)">
            <path d="M50 80 Q40 40, 80 30 Q100 20, 120 30 Q160 40, 150 80 L155 150 Q155 175, 130 175 Q115 185, 100 175 Q85 185, 70 175 Q45 175, 45 150 Z"
              transform="scale(0.5)" fill="var(--red)" stroke="var(--ink)" strokeWidth="6" strokeLinejoin="round" />
            <circle cx="42" cy="42" r="6" fill="white" stroke="var(--ink)" strokeWidth="2" />
            <circle cx="58" cy="42" r="6" fill="white" stroke="var(--ink)" strokeWidth="2" />
            <circle cx="42" cy="44" r="2.5" fill="var(--ink)" />
            <circle cx="58" cy="44" r="2.5" fill="var(--ink)" />
          </g>
        </svg>
      </div>
      {/* "POW" speech bubble when jumping high */}
      {jumpY > 30 && (
        <div style={{ position: "absolute", left: 80, bottom: 100, transform: "rotate(-8deg)" }}>
          <div className="pill" style={{ background: "var(--orange)", padding: "4px 12px", fontFamily: "var(--font-display)", fontSize: 14, border: "3px solid var(--ink)" }}>POW!</div>
        </div>
      )}
    </div>
  );
}

// ============ How It Works ============
function HowItWorks({ L, lang }) {
  const steps = [
    { t: L.step1Title, b: L.step1Body, color: "var(--red)",    n: "01", icon: "✏️" },
    { t: L.step2Title, b: L.step2Body, color: "var(--orange)", n: "02", icon: "✂️" },
    { t: L.step3Title, b: L.step3Body, color: "var(--green)",  n: "03", icon: "🎮" },
    { t: L.step4Title, b: L.step4Body, color: "var(--blue)",   n: "04", icon: "🎤" },
    { t: L.step5Title, b: L.step5Body, color: "var(--purple)", n: "05", icon: "✨" },
    { t: L.step6Title, b: L.step6Body, color: "var(--ink)",    n: "06", icon: "📦" },
  ];
  return (
    <section className="paper-bg">
      <div className="container">
        <div style={{ textAlign: "center", marginBottom: 50, position: "relative" }}>
          <div className="eyebrow">{L.howEyebrow}</div>
          <h2 style={{ marginTop: 18 }}>{L.howTitle}</h2>
          <Squiggle width={180} color="var(--red)" style={{ marginTop: 4 }} />
        </div>
        <div className="grid grid-3">
          {steps.map((s, i) => (
            <div key={i} className="card" style={{ transform: `rotate(${i % 2 === 0 ? -1.2 : 1}deg)`, background: s.color, color: s.color === "var(--ink)" ? "var(--paper)" : (s.color === "var(--orange)" || s.color === "var(--green)") ? "var(--ink)" : "var(--paper)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 }}>
                <div className="hand" style={{ fontSize: "1.8rem", fontWeight: 700 }}>{s.n}</div>
                <div style={{ fontSize: "2.4rem", lineHeight: 1 }}>{s.icon}</div>
              </div>
              <h3 style={{ marginBottom: 8, color: "inherit" }}>{s.t}</h3>
              <p style={{ margin: 0, opacity: 0.95 }}>{s.b}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============ Templates Strip ============
function TemplatesStrip({ lang, go }) {
  const L = window.I18N[lang].home;
  const tpls = window.TEMPLATES;
  return (
    <section>
      <div className="container">
        <div style={{ textAlign: "center", marginBottom: 40 }}>
          <div className="eyebrow">{L.templatesEyebrow}</div>
          <h2 style={{ marginTop: 18 }}>{L.templatesTitle}</h2>
        </div>
        <div className="grid grid-4">
          {tpls.map((t, i) => (
            <a key={t.id} href="#/pricing" onClick={(e) => { e.preventDefault(); go("pricing"); }} className="card wiggle-hover" style={{
              background: t.color, color: "#fff",
              transform: `rotate(${[-2, 1.5, -1, 2.5][i]}deg)`,
              textDecoration: "none",
              cursor: "pointer",
              minHeight: 180,
              display: "flex",
              flexDirection: "column",
              justifyContent: "space-between",
            }}>
              <div style={{ fontSize: "3rem", lineHeight: 1 }}>{t.emoji}</div>
              <div>
                <div className="display" style={{ fontSize: "1.3rem", marginTop: 12 }}>{t[lang].name}</div>
                <div className="hand" style={{ fontSize: "1.1rem", opacity: 0.95 }}>{t[lang].tag}</div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============ Featured Games ============
function FeaturedGames({ L, lang, go }) {
  const games = (window.GAMES || []).slice(0, 4);
  return (
    <section style={{ background: "var(--paper)", borderTop: "3px solid var(--ink)", borderBottom: "3px solid var(--ink)" }}>
      <div className="container">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 32, flexWrap: "wrap", gap: 20 }}>
          <div>
            <div className="eyebrow">{L.featuredEyebrow}</div>
            <h2 style={{ marginTop: 18, marginBottom: 0 }}>{L.featuredTitle}</h2>
          </div>
          <a className="btn" href="#/games" onClick={(e) => { e.preventDefault(); go("games"); }}>{L.featuredCta} →</a>
        </div>
        <div className="grid grid-4">
          {games.map((g, i) => <GameCardMini key={g.id} game={g} idx={i} lang={lang} go={go} />)}
        </div>
      </div>
    </section>
  );
}

function GameCardMini({ game, idx, lang, go }) {
  return (
    <div className="card wiggle-hover" style={{ padding: 0, overflow: "hidden", transform: `rotate(${[-1.5, 1, -0.5, 1.5][idx % 4]}deg)`, cursor: "pointer" }} onClick={() => go("games")}>
      <div style={{ background: game.bg, padding: 24, position: "relative", aspectRatio: "1.1 / 1", display: "grid", placeItems: "center" }}>
        <KidDoodle kind={game.shape} color={game.heroColor} size={120} />
        <div className="pill" style={{ position: "absolute", top: 10, left: 10, background: "var(--ink)", color: "var(--paper)", fontFamily: "var(--font-pixel)", fontSize: 9 }}>{game.templateLabel}</div>
      </div>
      <div style={{ padding: 16 }}>
        <div className="display" style={{ fontSize: "1.05rem" }}>{game.title}</div>
        <div className="hand" style={{ fontSize: "1rem", opacity: 0.7 }}>{lang === "th" ? "โดย" : "by"} {game.author}, {game.age}</div>
      </div>
    </div>
  );
}

// ============ Cafe Teaser ============
function CafeTeaser({ L, lang, go }) {
  return (
    <section>
      <div className="container">
        <div className="card" style={{ background: "var(--blue)", color: "var(--paper)", padding: 0, overflow: "hidden", transform: "rotate(-0.5deg)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 0 }} className="cafe-teaser-grid">
            <div style={{ padding: "50px 50px" }}>
              <div className="eyebrow" style={{ background: "var(--paper)", color: "var(--ink)" }}>{L.cafeEyebrow}</div>
              <h2 style={{ marginTop: 20, color: "var(--paper)" }}>{L.cafeTitle}</h2>
              <p style={{ fontSize: "1.15rem", maxWidth: 480 }}>{L.cafeBody}</p>
              <a className="btn btn-ink" href="#/cafe" onClick={(e) => { e.preventDefault(); go("cafe"); }}>{L.cafeCta} ☕</a>
            </div>
            <div style={{ background: "var(--paper)", padding: 32, position: "relative", minHeight: 280, display: "grid", placeItems: "center" }}>
              {/* Coffee cup doodle */}
              <svg width="220" height="220" viewBox="0 0 220 220" aria-hidden="true">
                <g filter="url(#wobble-soft)">
                  {/* steam */}
                  <path d="M80 30 Q70 50, 80 70 Q90 50, 80 30 Z M110 20 Q100 40, 110 60 Q120 40, 110 20 Z M140 30 Q130 50, 140 70 Q150 50, 140 30 Z"
                    fill="none" stroke="var(--ink)" strokeWidth="3" strokeLinecap="round" />
                  {/* cup */}
                  <path d="M50 90 L60 180 Q60 200, 80 200 L140 200 Q160 200, 160 180 L170 90 Z" fill="var(--red)" stroke="var(--ink)" strokeWidth="5" strokeLinejoin="round" />
                  <ellipse cx="110" cy="90" rx="60" ry="10" fill="var(--ink)" />
                  <ellipse cx="110" cy="92" rx="56" ry="7" fill="#3a1a0a" />
                  {/* handle */}
                  <path d="M170 110 Q200 115, 200 140 Q200 165, 170 165" fill="none" stroke="var(--ink)" strokeWidth="5" />
                  {/* heart on cup */}
                  <path d="M100 145 Q88 135, 88 150 Q88 165, 110 175 Q132 165, 132 150 Q132 135, 120 145 Q110 138, 100 145 Z" fill="var(--paper)" stroke="var(--ink)" strokeWidth="3" strokeLinejoin="round" />
                </g>
              </svg>
              <div style={{ position: "absolute", top: 20, right: 20 }}><Sparkle size={32} color="var(--orange)" /></div>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          .cafe-teaser-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

// ============ Big CTA ============
function BigCTA({ L, go, lang }) {
  return (
    <section className="confetti-bg">
      <div className="container-narrow center">
        <Burst size={70} style={{ display: "inline-block" }} />
        <h2 style={{ marginTop: 16 }}>{L.ctaBigTitle}</h2>
        <p style={{ fontSize: "1.2rem", marginBottom: 28 }}>{L.ctaBigBody}</p>
        <a className="btn btn-red btn-big" href="#/booking" onClick={(e) => { e.preventDefault(); go("booking"); }}>{L.ctaPrimary} 🚀</a>
      </div>
    </section>
  );
}

window.HomePage = HomePage;
