// =============================================================
// MAIN APP — POKEMON ADVANCE
// =============================================================
const { useState: useAppState, useEffect: useAppEffect } = React;

function App() {
  const [state, setStateRaw] = useAppState(() => {
    const s = GameEngine.loadState();
    GameEngine.refillIfNeeded(s);
    return s;
  });
  const [view, setView] = useAppState("home"); // home | packs | collection | battles | onboarding
  const [showSplash, setShowSplash] = useAppState(true);

  // Persist on every change
  useAppEffect(() => {
    GameEngine.saveState(state);
  }, [state]);

  // Auto-refill check on visibility
  useAppEffect(() => {
    function onVis() {
      const s = { ...state };
      if (GameEngine.refillIfNeeded(s)) setStateRaw(s);
    }
    document.addEventListener("visibilitychange", onVis);
    return () => document.removeEventListener("visibilitychange", onVis);
  }, [state]);

  function setState(updater) {
    setStateRaw(prev => typeof updater === "function" ? updater(prev) : updater);
  }

  useAppEffect(() => {
    const t = setTimeout(() => setShowSplash(false), 1900);
    return () => clearTimeout(t);
  }, []);

  if (showSplash) return <Splash/>;
  if (!state.welcomed) return <Onboarding state={state} setState={setState} onDone={() => setState(s => ({...s, welcomed:true}))}/>;

  if (view === "packs")      return <PackOpening state={state} setState={setState} onDone={() => setView("home")}/>;
  if (view === "collection") return <Collection state={state} onBack={() => setView("home")}/>;
  if (view === "battles")    return <Battles state={state} setState={setState} onBack={() => setView("home")}/>;
  return <Home
    state={state} setState={setState}
    onOpenPacks={() => setView("packs")}
    onOpenCollection={() => setView("collection")}
    onOpenBattles={() => setView("battles")}
  />;
}

function Splash() {
  return (
    <div style={{
      minHeight:"100vh",
      background: "radial-gradient(ellipse at center, rgba(0,240,255,0.18) 0%, var(--bg-void) 70%)",
      display:"flex", alignItems:"center", justifyContent:"center", flexDirection:"column", gap:24,
    }}>
      <style>{`
        @keyframes spinIn { 0%{transform:rotate(-180deg) scale(0); opacity:0} 100%{transform:rotate(0) scale(1); opacity:1} }
        @keyframes pulseGlow { 0%,100%{box-shadow:0 0 40px rgba(0,240,255,0.4)} 50%{box-shadow:0 0 80px rgba(0,240,255,0.8)} }
        @keyframes fadeUp { 0%{opacity:0; transform:translateY(20px)} 100%{opacity:1; transform:translateY(0)} }
      `}</style>
      <div style={{
        width:120, height:120, borderRadius:"50%",
        background:"linear-gradient(180deg, #fff 50%, #FF2D55 50%)",
        border:"4px solid #000", position:"relative",
        animation:"spinIn 700ms cubic-bezier(0.16,1,0.3,1), pulseGlow 2s ease-in-out infinite 700ms",
      }}>
        <div style={{position:"absolute", top:"50%", left:-4, right:-4, height:8, background:"#000", transform:"translateY(-50%)"}}/>
        <div style={{position:"absolute", top:"50%", left:"50%", transform:"translate(-50%,-50%)", width:32, height:32, borderRadius:"50%", background:"#fff", border:"6px solid #000"}}/>
      </div>
      <div style={{textAlign:"center", animation:"fadeUp 600ms ease-out 700ms backwards"}}>
        <img
          data-r="splash-img"
          src="assets/title.png"
          alt="Cartas Pokemon · Amongus"
          style={{
            display:"block", margin:"0 auto 16px",
            maxWidth: 720, width:"min(80vw, 720px)", height:"auto",
            filter: "drop-shadow(0 0 40px rgba(0,240,255,0.5))",
          }}
        />
        <div data-r="splash-title" style={{fontFamily:"var(--font-sans)", fontWeight:900, fontSize:48, color:"#fff", letterSpacing:"-0.02em", textShadow:"0 0 30px rgba(0,240,255,0.5)"}}>POKÉMON ADVANCE</div>
        <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--fg-3)", letterSpacing:"0.2em", marginTop:8}}>CARGANDO ENTRENADOR...</div>
      </div>
    </div>
  );
}

function Onboarding({ state, setState, onDone }) {
  const [step, setStep] = useAppState(0);
  const [name, setName] = useAppState(state.trainerName && state.trainerName !== "FRANCO" ? state.trainerName : "");

  const steps = [
    {
      eyebrow:"BIENVENIDO",
      title:"Hola entrenador",
      body:"Bienvenido a CARTAS POKEMON, un juego donde cada 10 horas puedes abrir 6 sobres, coleccionar cartas de las primeras generaciones, y combatir contra entrenadores NPC para ganar medallas.",
      cta:"COMENZAR",
    },
    {
      eyebrow:"REGISTRO",
      title:"¿Cuál es tu nombre?",
      body:"Este nombre aparecerá en tu Pokédex y en las batallas.",
      cta:"CONFIRMAR",
      input:true,
    },
    {
      eyebrow:"REGALO DE INICIO",
      title:"Recibe tu sobre inaugural",
      body:"Empieza con un sobre regalo. Cada 10 horas tendrás 6 sobres frescos esperando.",
      cta:"¡VAMOS!",
    },
  ];

  function next() {
    if (step === 1) setState(s => ({...s, trainerName: (name || "ENTRENADOR").toUpperCase().slice(0,12)}));
    if (step < steps.length - 1) setStep(step + 1);
    else {
      // Grant gift starter cards
      setState(s => {
        const next = {...s};
        const gift = [
          DEX_BY_ID[4],  // Charmander
          DEX_BY_ID[7],  // Squirtle
          DEX_BY_ID[1],  // Bulbasaur
          DEX_BY_ID[25], // Pikachu
          DEX_BY_ID[133],// Eevee
        ];
        GameEngine.addCardsToCollection(next, gift);
        return next;
      });
      onDone();
    }
  }

  const s = steps[step];
  return (
    <div data-r="onboarding" style={{
      minHeight:"100vh",
      background: "radial-gradient(ellipse at center, rgba(0,240,255,0.10) 0%, var(--bg-base) 70%)",
      display:"flex", alignItems:"center", justifyContent:"center", padding: 40,
    }}>
      <div style={{maxWidth:560, width:"100%", textAlign:"center"}}>
        <div className="eyebrow" style={{color:"var(--accent-cyan)", fontSize:13, letterSpacing:"0.3em"}}>{s.eyebrow}</div>
        <h1 style={{fontFamily:"var(--font-sans)", fontWeight:900, fontSize:56, color:"#fff", margin:"16px 0 20px", letterSpacing:"-0.02em", lineHeight:1}}>
          {s.title}
        </h1>
        <p style={{color:"var(--fg-2)", fontSize:16, lineHeight:1.6, marginBottom:32}}>{s.body}</p>

        {s.input && (
          <input
            value={name}
            onChange={e => setName(e.target.value)}
            maxLength={12}
            placeholder="Tu nombre..."
            autoFocus
            style={{
              fontFamily:"var(--font-sans)", fontSize:24, fontWeight:700,
              textAlign:"center", letterSpacing:"0.1em",
              background:"var(--bg-inset)",
              border:"1px solid var(--accent-cyan)",
              color:"#fff", padding:"14px 20px",
              borderRadius:2, width:"100%", maxWidth:300,
              marginBottom:24, outline:"none",
              boxShadow:"0 0 12px var(--accent-cyan-glow)",
              textTransform:"uppercase",
            }}
          />
        )}

        <button onClick={next} style={{...btnPrimary(false), fontSize:16, padding:"16px 36px"}}>{s.cta} ▸</button>

        <div style={{display:"flex", gap:6, justifyContent:"center", marginTop:36}}>
          {steps.map((_,i) => (
            <div key={i} style={{
              width:24, height:3,
              background: i <= step ? "var(--accent-cyan)" : "var(--border-solid)",
              transition:"all 200ms",
            }}/>
          ))}
        </div>
      </div>
    </div>
  );
}

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