// =============================================================
// HOME SCREEN — main menu / hub
// =============================================================
const { useState: useStateHome, useEffect: useEffectHome } = React;

function Home({ state, setState, onOpenPacks, onOpenCollection, onOpenBattles }) {
  const stats = GameEngine.collectionStats(state);
  const [countdown, setCountdown] = useStateHome("");

  useEffectHome(() => {
    function tick() {
      const ms = GameEngine.msUntilRefill(state);
      setCountdown(ms > 0 ? GameEngine.formatCountdown(ms) : "Reinicio disponible");
    }
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, [state.lastClaimTs]);

  // Visual: featured Pokémon (random rare from collection or fallback)
  const featured = (() => {
    const owned = Object.keys(state.collection).map(id => DEX_BY_ID[+id]).filter(Boolean);
    const fancies = owned.filter(p => p.rarity === "legendary" || p.rarity === "holo");
    if (fancies.length) return fancies[Math.floor(Math.random()*fancies.length)];
    if (owned.length) return owned[0];
    return DEX_BY_ID[6]; // Charizard fallback
  })();

  return (
    <div style={{minHeight:"100vh", background:"var(--bg-base)", color:"var(--fg-2)", position:"relative", overflow:"hidden"}}>
      {/* Background grid */}
      <div style={{
        position:"fixed", inset:0, pointerEvents:"none",
        backgroundImage: `
          radial-gradient(ellipse at 20% 0%, rgba(0,240,255,0.08), transparent 50%),
          radial-gradient(ellipse at 80% 100%, rgba(249,85,135,0.08), transparent 50%),
          radial-gradient(circle, var(--grid-dot) 1px, transparent 1px)
        `,
        backgroundSize: "auto, auto, 32px 32px",
      }}/>

      <div data-r="hub-shell" style={{position:"relative", maxWidth: 1400, margin:"0 auto", padding:"32px 40px"}}>
        {/* HEADER */}
        <header data-r="hub-header" style={{display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:32}}>
          <div>
            <div className="eyebrow" style={{marginBottom:8}}>● SISTEMA EN LÍNEA · ENTRENADOR //{state.trainerName}</div>
            <img
              data-r="hub-title-img"
              src="assets/title.png"
              alt="Cartas Pokemon · Amongus"
              style={{
                display:"block",
                maxWidth: 640, width:"100%", height:"auto",
                filter: "drop-shadow(0 0 32px rgba(0,240,255,0.35))",
                marginBottom: 6,
              }}
            />
            <div data-r="hub-subtitle" style={{
              fontFamily:"var(--font-sans)", fontWeight:300,
              fontSize: 28, color:"var(--accent-cyan)",
              letterSpacing:"0.3em", marginTop:4,
              textShadow:"0 0 18px var(--accent-cyan)",
            }}>POKÉMON · ADVANCE</div>
          </div>

          {/* Stats panel */}
          <div data-r="hub-stats" style={{
            display:"flex", gap:12, alignItems:"stretch",
          }}>
            <StatTile label="Pokédex" value={`${stats.owned}/${stats.total}`} sub={`${stats.pct}% completo`} accent="cyan"/>
            <StatTile label="Batallas" value={state.battlesWon} sub={`${state.badges.length} medallas`} accent="lime"/>
            <StatTile label="Pokécoins" value={state.coins} sub="moneda local" accent="orange" mono/>
          </div>
        </header>

        {/* MAIN GRID */}
        <div data-r="hub-main" style={{display:"grid", gridTemplateColumns: "1.4fr 1fr", gap:24, marginBottom: 28}}>
          {/* Daily packs hero */}
          <div data-r="hub-pack-card" style={{
            position:"relative",
            background: "linear-gradient(135deg, #161B22 0%, #0D1117 100%)",
            border: "1px solid var(--border-hairline)",
            borderRadius: 4,
            padding: 28,
            overflow:"hidden",
            boxShadow: "var(--elev-offset-1)",
          }}>
            <div style={{
              position:"absolute", inset:0,
              background: "radial-gradient(circle at 80% 50%, rgba(0,240,255,0.10), transparent 60%)",
              pointerEvents:"none",
            }}/>
            <div style={{position:"relative", display:"flex", justifyContent:"space-between", gap:24}} data-r="hub-pack-row">
              <div style={{flex:1, minWidth:0}}>
                <div className="eyebrow" style={{color:"var(--accent-cyan)"}}>01 / SOBRES DIARIOS</div>
                <h2 data-r="hub-pack-title" style={{
                  fontFamily:"var(--font-sans)", fontWeight:800, fontSize:38,
                  margin:"8px 0", color:"#fff", letterSpacing:"-0.01em", lineHeight:1.05,
                }}>Abre tus sobres del ciclo</h2>
                <p style={{color:"var(--fg-3)", maxWidth:480, marginBottom:24, lineHeight:1.5}}>
                  Cada <strong style={{color:"var(--fg-1)"}}>10 horas</strong> recibes <strong style={{color:"var(--fg-1)"}}>6 sobres</strong> con 5 cartas:
                  3 comunes, 1 inusual y 1 con chance de holo o legendaria. Colecciónalas todas.
                </p>

                {/* Pack pips */}
                <div data-r="hub-pack-pips" style={{display:"flex", gap:8, marginBottom:24}}>
                  {Array.from({length: GameEngine.PACKS_PER_DAY}).map((_,i) => {
                    const filled = i < state.packsAvailable;
                    return (
                      <div key={i} style={{
                        width: 56, height: 80,
                        borderRadius: 3,
                        background: filled
                          ? "linear-gradient(180deg, #00F0FF, #008C96)"
                          : "linear-gradient(180deg, #161B22, #0a0d12)",
                        border: filled ? "1px solid #00F0FF" : "1px solid var(--border-hairline)",
                        boxShadow: filled ? "0 0 12px var(--accent-cyan-glow), inset 0 0 0 1px rgba(255,255,255,0.1)" : "inset 0 0 0 1px rgba(0,0,0,0.5)",
                        display:"flex", alignItems:"center", justifyContent:"center",
                        position:"relative",
                        fontFamily:"var(--font-mono)", fontSize:10,
                        color: filled ? "#0a0d12" : "var(--fg-5)",
                        fontWeight:700, letterSpacing:"0.1em",
                      }}>
                        {filled ? "OPEN" : "USED"}
                      </div>
                    );
                  })}
                </div>

                <div data-r="hub-pack-cta" style={{display:"flex", gap:12, alignItems:"center"}}>
                  <button
                    onClick={onOpenPacks}
                    disabled={state.packsAvailable === 0}
                    style={btnPrimary(state.packsAvailable === 0)}
                  >
                    {state.packsAvailable > 0 ? `▶ ABRIR SOBRE (${state.packsAvailable})` : "○ ESPERA RECARGA"}
                  </button>
                  <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--fg-3)"}}>
                    <div style={{color:"var(--fg-4)", fontSize:10, letterSpacing:"0.15em"}}>PRÓXIMA RECARGA</div>
                    <div style={{color:"var(--accent-cyan)", fontSize:16, fontWeight:700, letterSpacing:"0.1em"}}>{countdown}</div>
                  </div>
                </div>
              </div>

              {/* Pack 3D preview */}
              <div data-r="hub-pack-visual"><PackVisual /></div>
            </div>
          </div>

          {/* Featured card */}
          <div data-r="hub-featured" style={{
            background: "linear-gradient(135deg, #161B22 0%, #0D1117 100%)",
            border: "1px solid var(--border-hairline)",
            borderRadius: 4,
            padding: 24,
            display:"flex", flexDirection:"column", gap:16, alignItems:"center",
            position:"relative",
            boxShadow: "var(--elev-offset-1)",
          }}>
            <div style={{alignSelf:"flex-start", width:"100%"}}>
              <div className="eyebrow" style={{color:"var(--accent-orange)"}}>02 / DESTACADA HOY</div>
              <div style={{color:"var(--fg-3)", fontSize:12, marginTop:4}}>
                {Object.keys(state.collection).length === 0
                  ? "Aún sin colección — abre tu primer sobre"
                  : `Tu favorita: ${featured.name}`}
              </div>
            </div>
            <PokemonCard pokemon={featured} size="md" />
            <div style={{
              fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-3)",
              textAlign:"center", lineHeight:1.5, padding:"0 12px",
              fontStyle:"italic",
            }}>"{featured.flavor}"</div>
          </div>
        </div>

        {/* ACTION TILES */}
        <div data-r="hub-actions" style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:24}}>
          <ActionTile
            number="03"
            color="cyan"
            title="POKÉDEX"
            subtitle={`${stats.owned} capturados de ${stats.total} · ${stats.pct}%`}
            description="Revisa tu colección, ordena por rareza, examina cada carta en detalle."
            onClick={onOpenCollection}
            preview={
              <CollectionMini collection={state.collection}/>
            }
          />
          <ActionTile
            number="04"
            color="orange"
            title="ARENA NPC"
            subtitle={`${state.battlesWon} victorias · ${state.badges.length}/${TRAINERS.length} medallas`}
            description="Combate por turnos contra entrenadores. Gana medallas y monedas."
            onClick={onOpenBattles}
            preview={
              <BadgeRow badges={state.badges}/>
            }
          />
        </div>

        {/* FOOTER */}
        <footer data-r="hub-footer" style={{
          marginTop:48, paddingTop:24,
          borderTop:"1px solid var(--border-hairline)",
          display:"flex", justifyContent:"space-between",
          fontFamily:"var(--font-mono)", fontSize:10,
          color:"var(--fg-4)", letterSpacing:"0.15em",
        }}>
          <span>CARTAS POKEMON · v1.0.0 · BUILD 2026.05</span>
          <span>{POKEDEX.length} POKÉMON · GEN I + GEN II · {TRAINERS.length} ENTRENADORES</span>
          <span>FANGAME © {new Date().getFullYear()}</span>
        </footer>
      </div>
    </div>
  );
}

// ---------- Reusable bits ----------------
function StatTile({ label, value, sub, accent, mono }) {
  const accentColor = { cyan: "var(--accent-cyan)", lime:"var(--accent-lime)", orange:"var(--accent-orange)"}[accent];
  return (
    <div style={{
      background:"var(--bg-surface)",
      border:"1px solid var(--border-hairline)",
      borderRadius: 2,
      padding:"12px 18px",
      minWidth: 140,
      borderLeft: `2px solid ${accentColor}`,
    }}>
      <div className="eyebrow" style={{fontSize:9}}>{label}</div>
      <div style={{
        fontFamily: mono ? "var(--font-mono)" : "var(--font-sans)",
        fontWeight: 800, fontSize: 28, color:"#fff", lineHeight:1, margin:"4px 0",
      }}>{value}</div>
      <div style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--fg-3)"}}>{sub}</div>
    </div>
  );
}

function ActionTile({ number, color, title, subtitle, description, onClick, preview }) {
  const [hover, setHover] = useStateHome(false);
  const c = { cyan:"var(--accent-cyan)", orange:"var(--accent-orange)", lime:"var(--accent-lime)" }[color];
  const g = { cyan:"var(--accent-cyan-glow)", orange:"var(--accent-orange-glow)", lime:"var(--accent-lime-glow)" }[color];
  return (
    <div
      data-r="hub-action"
      onClick={onClick}
      onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
      style={{
        position:"relative",
        background: "linear-gradient(135deg, #161B22 0%, #0D1117 100%)",
        border: `1px solid ${hover ? c : "var(--border-hairline)"}`,
        borderRadius: 4,
        padding: 24,
        cursor:"pointer",
        transition: "all 220ms cubic-bezier(0.16,1,0.3,1)",
        transform: hover ? "translateY(-2px)" : "none",
        boxShadow: hover ? `0 0 24px ${g}, var(--elev-offset-1)` : "var(--elev-offset-1)",
        overflow:"hidden",
        minHeight: 180,
      }}>
      <div style={{position:"absolute", top:0, left:0, right:0, height:1, background:`linear-gradient(90deg, transparent, ${c}, transparent)`, opacity: hover ? 1 : 0.3}}/>
      <div data-r="hub-action-inner" style={{display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:24, position:"relative"}}>
        <div style={{flex:1, minWidth:0}}>
          <div className="eyebrow" style={{color:c}}>{number} / {title}</div>
          <h3 style={{fontFamily:"var(--font-sans)", fontWeight:700, fontSize:24, color:"#fff", margin:"6px 0"}}>{subtitle}</h3>
          <p style={{color:"var(--fg-3)", fontSize:13, lineHeight:1.5, maxWidth: 360}}>{description}</p>
          <div style={{
            marginTop: 18,
            fontFamily:"var(--font-mono)", fontSize:11, color: c,
            letterSpacing:"0.15em", display:"flex", alignItems:"center", gap:6,
          }}>
            ENTRAR → {hover ? "▸▸▸" : "▸"}
          </div>
        </div>
        <div data-r="hub-action-preview" style={{flexShrink:0}}>{preview}</div>
      </div>
    </div>
  );
}

function CollectionMini({ collection }) {
  const owned = Object.keys(collection).slice(0, 9).map(id => DEX_BY_ID[+id]).filter(Boolean);
  while (owned.length < 9) owned.push(null);
  return (
    <div style={{display:"grid", gridTemplateColumns:"repeat(3, 36px)", gap:4}}>
      {owned.map((p,i) => (
        <div key={i} style={{
          width:36, height:36,
          borderRadius:2,
          background: p ? `linear-gradient(135deg, ${TYPE_INFO[p.types[0]].gradient[0]}33, ${TYPE_INFO[p.types[0]].gradient[1]}33)` : "var(--bg-inset)",
          border: `1px solid ${p ? TYPE_INFO[p.types[0]].color + "66" : "var(--border-hairline)"}`,
          display:"flex", alignItems:"center", justifyContent:"center",
          overflow:"hidden",
        }}>
          {p ? <img src={SPRITE(p.id)} alt={p.name} style={{width:"100%", height:"100%", objectFit:"contain"}}/> :
            <span style={{color:"var(--fg-5)", fontSize:14}}>?</span>}
        </div>
      ))}
    </div>
  );
}

function BadgeRow({ badges }) {
  return (
    <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:6, maxWidth: 160}}>
      {TRAINERS.slice(0,8).map((t,i) => {
        const earned = badges.includes(t.id);
        return (
          <div key={i} style={{
            width:36, height:36,
            borderRadius:"50%",
            background: earned ? "linear-gradient(135deg, var(--accent-orange), var(--accent-yellow))" : "var(--bg-inset)",
            border: earned ? "1px solid var(--accent-orange)" : "1px solid var(--border-hairline)",
            display:"flex", alignItems:"center", justifyContent:"center",
            fontSize:14,
            boxShadow: earned ? "0 0 8px var(--accent-orange-glow), inset 0 0 0 2px rgba(0,0,0,0.3)" : "none",
            opacity: earned ? 1 : 0.5,
          }}>{t.avatar}</div>
        );
      })}
    </div>
  );
}

function PackVisual() {
  return (
    <div style={{
      position:"relative", width:160, height:222,
      transform: "rotate(-6deg)",
      filter: "drop-shadow(8px 8px 0 var(--border-solid)) drop-shadow(0 0 24px rgba(0,240,255,0.35))",
    }}>
      <img
        src="assets/pack.png"
        alt="Sobre Pokémon"
        style={{
          width:"100%", height:"100%", objectFit:"contain",
          display:"block",
        }}
      />
      {/* Holo shine overlay */}
      <div style={{
        position:"absolute", inset:0,
        backgroundImage: "linear-gradient(115deg, transparent 35%, rgba(255,255,255,0.35) 50%, transparent 65%)",
        backgroundSize: "200% 200%",
        animation: "holoShift 4s linear infinite",
        mixBlendMode: "overlay",
        pointerEvents: "none",
        borderRadius: 4,
      }}/>
    </div>
  );
}

function btnPrimary(disabled) {
  return {
    fontFamily:"var(--font-sans)", fontWeight:800,
    fontSize:14, letterSpacing:"0.12em",
    color: disabled ? "var(--fg-4)" : "#0a0d12",
    background: disabled ? "var(--bg-surface)" : "linear-gradient(180deg, #00F0FF 0%, #00BCC9 100%)",
    border: `1px solid ${disabled ? "var(--border-solid)" : "#00F0FF"}`,
    borderRadius: 2,
    padding: "14px 28px",
    cursor: disabled ? "not-allowed" : "pointer",
    boxShadow: disabled ? "none" : "0 0 16px var(--accent-cyan-glow), inset 0 0 0 1px rgba(255,255,255,0.3)",
    transition: "all 180ms",
    textTransform: "uppercase",
  };
}

window.Home = Home;
window.btnPrimary = btnPrimary;
