// =============================================================
// COLLECTION / POKÉDEX — full grid with filters & detail
// =============================================================
const { useState: useColState, useMemo: useColMemo } = React;

function Collection({ state, onBack }) {
  const [filterType, setFilterType] = useColState("all");
  const [filterRarity, setFilterRarity] = useColState("all");
  const [filterGen, setFilterGen] = useColState("all");
  const [showOnlyOwned, setShowOnlyOwned] = useColState(false);
  const [sortBy, setSortBy] = useColState("dex");
  const [search, setSearch] = useColState("");
  const [searchFocused, setSearchFocused] = useColState(false);
  const [selected, setSelected] = useColState(null);

  // Live suggestions for the hero search
  const suggestions = useColMemo(() => {
    if (!search.trim()) return [];
    const q = search.toLowerCase();
    return POKEDEX
      .filter(p => p.name.toLowerCase().includes(q) || String(p.id).includes(q))
      .slice(0, 8);
  }, [search]);
  const stats = GameEngine.collectionStats(state);

  const filtered = useColMemo(() => {
    let list = [...POKEDEX];
    if (filterType !== "all") list = list.filter(p => p.types.includes(filterType));
    if (filterRarity !== "all") list = list.filter(p => p.rarity === filterRarity);
    if (filterGen !== "all") list = list.filter(p => filterGen === "1" ? p.id <= 151 : p.id > 151);
    if (showOnlyOwned) list = list.filter(p => state.collection[p.id]);
    if (search) {
      const q = search.toLowerCase();
      list = list.filter(p => p.name.toLowerCase().includes(q) || String(p.id).includes(q));
    }
    if (sortBy === "hp") list.sort((a,b) => b.hp - a.hp);
    else if (sortBy === "rarity") {
      const order = ["legendary","holo","rare","uncommon","common"];
      list.sort((a,b) => order.indexOf(a.rarity) - order.indexOf(b.rarity));
    }
    else list.sort((a,b) => a.id - b.id);
    return list;
  }, [filterType, filterRarity, filterGen, showOnlyOwned, sortBy, search, state.collection]);

  return (
    <div style={{minHeight:"100vh", background:"var(--bg-base)", color:"var(--fg-2)"}}>
      {/* TOP BAR */}
      <div data-r="topbar" style={{display:"flex", justifyContent:"space-between", alignItems:"center", padding:"20px 40px", borderBottom:"1px solid var(--border-hairline)", background:"var(--bg-surface)"}}>
        <button onClick={onBack} style={btnGhost()}>← VOLVER</button>
        <div style={{textAlign:"center"}}>
          <div className="eyebrow" style={{color:"var(--accent-cyan)"}}>POKÉDEX · BASE DE DATOS</div>
          <div data-r="topbar-title" style={{fontFamily:"var(--font-sans)", fontWeight:700, fontSize:18, color:"#fff"}}>
            {stats.owned} / {stats.total} REGISTRADOS · {stats.pct}%
          </div>
        </div>
        <div data-r="topbar-rarities" style={{display:"flex", gap:6, alignItems:"center", fontFamily:"var(--font-mono)", fontSize:11}}>
          {Object.entries(stats.byRarity).map(([k,v]) => (
            <div key={k} style={{
              padding:"4px 8px",
              border:`1px solid ${RARITY[k].color}66`,
              borderRadius:2,
              color: v.owned > 0 ? RARITY[k].color : "var(--fg-4)",
              letterSpacing:"0.05em",
            }}>
              {RARITY[k].symbol} {v.owned}/{v.total}
            </div>
          ))}
        </div>
      </div>

      {/* FILTER BAR */}
      <div data-r="filterbar" style={{
        display:"flex", gap:16, padding:"16px 40px",
        borderBottom:"1px solid var(--border-hairline)",
        background:"var(--bg-base)",
        flexWrap:"wrap", alignItems:"center",
      }}>
        <FilterGroup label="TIPO">
          <FilterChip active={filterType==="all"} onClick={()=>setFilterType("all")} color="cyan">TODOS</FilterChip>
          {Object.entries(TYPE_INFO).map(([k,info]) => (
            <FilterChip key={k} active={filterType===k} onClick={()=>setFilterType(filterType===k?"all":k)} typeKey={k}>
              <EnergyChip type={k} size={12}/> {info.name}
            </FilterChip>
          ))}
        </FilterGroup>

        <div data-r="filterbar-sep" style={{height:24, width:1, background:"var(--border-hairline)"}}/>

        <FilterGroup label="RAREZA">
          <FilterChip active={filterRarity==="all"} onClick={()=>setFilterRarity("all")} color="cyan">TODAS</FilterChip>
          {Object.entries(RARITY).map(([k,r]) => (
            <FilterChip key={k} active={filterRarity===k} onClick={()=>setFilterRarity(filterRarity===k?"all":k)} customColor={r.color}>
              {r.symbol} {r.name}
            </FilterChip>
          ))}
        </FilterGroup>

        <div data-r="filterbar-sep" style={{height:24, width:1, background:"var(--border-hairline)"}}/>

        <FilterGroup label="GEN">
          <FilterChip active={filterGen==="all"} onClick={()=>setFilterGen("all")} color="cyan">I+II</FilterChip>
          <FilterChip active={filterGen==="1"} onClick={()=>setFilterGen("1")} color="cyan">GEN I</FilterChip>
          <FilterChip active={filterGen==="2"} onClick={()=>setFilterGen("2")} color="cyan">GEN II</FilterChip>
        </FilterGroup>

        <div data-r="filterbar-sep" style={{height:24, width:1, background:"var(--border-hairline)"}}/>

        <FilterChip active={showOnlyOwned} onClick={()=>setShowOnlyOwned(!showOnlyOwned)} color="lime">
          {showOnlyOwned ? "✓" : "○"} SOLO MIS CARTAS
        </FilterChip>

        <div style={{flex:1}}/>

        <select value={sortBy} onChange={e=>setSortBy(e.target.value)} style={{
          fontFamily:"var(--font-mono)", fontSize:12,
          padding:"6px 10px",
          background:"var(--bg-inset)",
          border:"1px solid var(--border-hairline)",
          color:"var(--fg-1)", borderRadius:2,
        }}>
          <option value="dex">Orden Pokédex</option>
          <option value="hp">Por PS ↓</option>
          <option value="rarity">Por rareza ↓</option>
        </select>
      </div>

      {/* HERO SEARCH */}
      <div data-r="hero-search" style={{padding:"24px 40px 0", position:"relative", zIndex: 20}}>
        <div style={{position:"relative", maxWidth: 760}}>
          <div style={{
            position:"absolute", left:18, top:"50%", transform:"translateY(-50%)",
            color: search ? "var(--accent-cyan)" : "var(--fg-4)",
            fontFamily:"var(--font-mono)", fontSize: 18, fontWeight: 700,
            pointerEvents:"none",
            transition:"color 150ms",
          }}>⌕</div>
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            onFocus={()=>setSearchFocused(true)}
            onBlur={()=>setTimeout(()=>setSearchFocused(false), 180)}
            placeholder="Buscar carta por nombre o número de Pokédex..."
            style={{
              fontFamily:"var(--font-sans)", fontSize: 18, fontWeight: 500,
              padding:"16px 48px 16px 48px", width: "100%",
              background: search ? "var(--bg-surface)" : "var(--bg-inset)",
              border:`1px solid ${search ? "var(--accent-cyan)" : "var(--border-solid)"}`,
              color:"#fff", borderRadius:2,
              outline:"none",
              letterSpacing: "0.01em",
              boxShadow: search ? "0 0 16px var(--accent-cyan-glow), inset 0 0 0 1px rgba(0,240,255,0.1)" : "none",
              transition: "all 180ms",
            }}
          />
          {search && (
            <button
              onClick={()=>setSearch("")}
              style={{
                position:"absolute", right: 12, top:"50%", transform:"translateY(-50%)",
                background:"transparent", border:"1px solid var(--border-solid)",
                color:"var(--fg-2)", fontFamily:"var(--font-mono)", fontSize: 14, fontWeight: 700,
                width: 28, height: 28, cursor:"pointer", borderRadius: 2,
                display:"flex", alignItems:"center", justifyContent:"center",
              }}>×</button>
          )}

          {/* Live suggestions dropdown */}
          {searchFocused && suggestions.length > 0 && (
            <div style={{
              position:"absolute", top:"calc(100% + 4px)", left:0, right:0,
              background:"var(--bg-surface)",
              border:"1px solid var(--accent-cyan)",
              borderRadius: 2,
              boxShadow: "0 12px 36px rgba(0,0,0,0.6), 0 0 24px var(--accent-cyan-glow)",
              maxHeight: 380, overflowY:"auto", zIndex: 30,
            }}>
              {suggestions.map(p => {
                const owned = state.collection[p.id] || 0;
                const info = TYPE_INFO[p.types[0]];
                return (
                  <button
                    key={p.id}
                    onMouseDown={(e)=>{ e.preventDefault(); setSelected(p); }}
                    style={{
                      display:"flex", alignItems:"center", gap: 14,
                      width:"100%", padding:"10px 14px",
                      background:"transparent",
                      border:"none", borderBottom:"1px solid var(--border-hairline)",
                      cursor:"pointer", textAlign:"left",
                      transition:"background 120ms",
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--bg-surface-2)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                    <div style={{
                      width: 44, height: 44, flexShrink: 0,
                      background: `linear-gradient(135deg, ${info.gradient[0]}33, ${info.gradient[1]}33)`,
                      border:`1px solid ${info.color}66`,
                      borderRadius: 2,
                      display:"flex", alignItems:"center", justifyContent:"center",
                      overflow:"hidden",
                      filter: owned === 0 ? "grayscale(1) brightness(0.6)" : "none",
                    }}>
                      <img src={SPRITE(p.id)} alt={p.name} style={{width:"100%", height:"100%", objectFit:"contain"}}/>
                    </div>
                    <div style={{flex: 1, minWidth: 0}}>
                      <div style={{display:"flex", alignItems:"baseline", gap: 8}}>
                        <span style={{fontFamily:"var(--font-mono)", fontSize: 11, color:"var(--fg-4)", letterSpacing:"0.1em"}}>#{String(p.id).padStart(3,"0")}</span>
                        <span style={{fontFamily:"var(--font-sans)", fontWeight: 700, fontSize: 16, color:"#fff"}}>{p.name}</span>
                      </div>
                      <div style={{fontFamily:"var(--font-mono)", fontSize: 10, color:"var(--fg-3)", letterSpacing:"0.1em", marginTop: 2}}>
                        {p.types.map(t=>TYPE_INFO[t].name.toUpperCase()).join(" / ")} · PS {p.hp}
                      </div>
                    </div>
                    <div style={{display:"flex", flexDirection:"column", alignItems:"flex-end", gap: 2}}>
                      <span style={{
                        fontFamily:"var(--font-mono)", fontSize: 10, fontWeight: 700,
                        color: RARITY[p.rarity].color, letterSpacing:"0.1em",
                      }}>{RARITY[p.rarity].symbol} {RARITY[p.rarity].name.toUpperCase()}</span>
                      <span style={{
                        fontFamily:"var(--font-mono)", fontSize: 10,
                        color: owned > 0 ? "var(--accent-lime)" : "var(--fg-5)",
                      }}>{owned > 0 ? `× ${owned} EN COLECCIÓN` : "NO CAPTURADO"}</span>
                    </div>
                  </button>
                );
              })}
            </div>
          )}
          {searchFocused && search.trim() && suggestions.length === 0 && (
            <div style={{
              position:"absolute", top:"calc(100% + 4px)", left:0, right:0,
              padding:"14px 18px",
              background:"var(--bg-surface)",
              border:"1px solid var(--border-hairline)",
              fontFamily:"var(--font-mono)", fontSize: 12, color:"var(--fg-4)",
              letterSpacing:"0.1em",
              zIndex: 30,
            }}>∅ NINGUNA CARTA COINCIDE CON "{search}"</div>
          )}
        </div>
      </div>

      {/* GRID */}
      <div data-r="card-grid" style={{padding:"24px 40px 32px"}}>
        <div style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-3)", marginBottom:20, letterSpacing:"0.1em"}}>
          MOSTRANDO {filtered.length} ENTRADAS · {filtered.filter(p => state.collection[p.id]).length} EN POSESIÓN
        </div>
        <div style={{display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(170px, 1fr))", gap:16}}>
          {filtered.map(p => {
            const count = state.collection[p.id] || 0;
            return (
              <div key={p.id} style={{display:"flex", justifyContent:"center"}}>
                <PokemonCard
                  pokemon={p}
                  size="sm"
                  count={count}
                  dim={count === 0}
                  onClick={() => setSelected(p)}
                />
              </div>
            );
          })}
          {filtered.length === 0 && (
            <div style={{
              gridColumn:"1/-1", padding:60, textAlign:"center",
              color:"var(--fg-4)", fontFamily:"var(--font-mono)", fontSize:14,
              border:"1px dashed var(--border-hairline)",
            }}>
              ∅ NO HAY RESULTADOS · ajusta los filtros
            </div>
          )}
        </div>
      </div>

      {/* DETAIL MODAL */}
      {selected && (
        <DetailModal
          pokemon={selected}
          count={state.collection[selected.id] || 0}
          onClose={()=>setSelected(null)}
        />
      )}
    </div>
  );
}

function FilterGroup({ label, children }) {
  return (
    <div style={{display:"flex", flexDirection:"column", gap:6}}>
      <span style={{fontFamily:"var(--font-mono)", fontSize:9, color:"var(--fg-4)", letterSpacing:"0.2em"}}>{label}</span>
      <div style={{display:"flex", gap:4, flexWrap:"wrap"}}>{children}</div>
    </div>
  );
}

function FilterChip({ active, onClick, children, color, typeKey, customColor }) {
  const c = customColor || (typeKey ? TYPE_INFO[typeKey].color : (color === "cyan" ? "var(--accent-cyan)" : color === "lime" ? "var(--accent-lime)" : "var(--accent-orange)"));
  return (
    <button onClick={onClick} style={{
      display:"inline-flex", alignItems:"center", gap:6,
      fontFamily:"var(--font-mono)", fontSize:10, fontWeight:600,
      letterSpacing:"0.1em", textTransform:"uppercase",
      padding:"5px 10px", borderRadius:2,
      cursor:"pointer",
      background: active ? c : "var(--bg-inset)",
      border: `1px solid ${active ? c : "var(--border-hairline)"}`,
      color: active ? "#0a0d12" : "var(--fg-2)",
      transition:"all 150ms",
    }}>{children}</button>
  );
}

function DetailModal({ pokemon, count, onClose }) {
  const info = TYPE_INFO[pokemon.types[0]];
  return (
    <div onClick={onClose} style={{
      position:"fixed", inset:0, zIndex: 100,
      background:"rgba(0,0,0,0.85)",
      backdropFilter:"blur(4px)",
      display:"flex", alignItems:"center", justifyContent:"center",
      padding: 40,
    }}>
      <div onClick={e=>e.stopPropagation()} data-r="detail-modal" style={{
        background:"var(--bg-base)",
        border:`1px solid ${info.color}`,
        borderRadius: 4,
        padding: 32,
        maxWidth: 900,
        width:"100%",
        display:"grid", gridTemplateColumns:"auto 1fr", gap:32,
        position:"relative",
        boxShadow: `0 0 60px ${info.glow}, var(--elev-offset-2)`,
      }}>
        <button onClick={onClose} style={{
          position:"absolute", top:12, right:12,
          background:"transparent", border:"1px solid var(--border-solid)",
          color:"var(--fg-2)", fontFamily:"var(--font-mono)", fontSize:14,
          width:32, height:32, cursor:"pointer", borderRadius:2,
        }}>×</button>

        <PokemonCard pokemon={pokemon} size="lg" glow={pokemon.rarity==="holo"||pokemon.rarity==="legendary"}/>

        <div style={{display:"flex", flexDirection:"column", gap:18}}>
          <div>
            <div className="eyebrow" style={{color: info.color}}>
              #{String(pokemon.id).padStart(3,"0")} · {pokemon.types.map(t=>TYPE_INFO[t].name.toUpperCase()).join(" / ")} · GEN {pokemon.id <= 151 ? "I" : "II"}
            </div>
            <h2 style={{fontFamily:"var(--font-sans)", fontWeight:800, fontSize:48, color:"#fff", margin:"4px 0", letterSpacing:"-0.02em"}}>{pokemon.name}</h2>
            <div style={{fontFamily:"var(--font-mono)", fontSize:13, color:"var(--fg-3)", fontStyle:"italic", lineHeight:1.5}}>"{pokemon.flavor}"</div>
          </div>

          <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:12}}>
            <StatBox label="PS" value={pokemon.hp} accent={info.color}/>
            <StatBox label="EN POSESIÓN" value={`×${count}`} accent={count > 0 ? "var(--accent-lime)" : "var(--fg-4)"}/>
            <StatBox label="RAREZA" value={RARITY[pokemon.rarity].symbol} sub={RARITY[pokemon.rarity].name} accent={RARITY[pokemon.rarity].color}/>
            <StatBox label="RETIRADA" value={pokemon.retreat || "—"} sub="energías" accent="var(--fg-2)"/>
          </div>

          <div>
            <div className="eyebrow" style={{marginBottom: 10}}>ATAQUES</div>
            <div style={{display:"flex", flexDirection:"column", gap:8}}>
              {pokemon.attacks.map((atk, i) => (
                <div key={i} style={{
                  display:"flex", alignItems:"center", gap:12,
                  padding:"10px 14px",
                  background:"var(--bg-surface)",
                  border:"1px solid var(--border-hairline)",
                  borderRadius: 2,
                }}>
                  <div style={{display:"flex", gap:3}}>
                    {atk.cost.map((c,j) => <EnergyChip key={j} type={c} size={20}/>)}
                  </div>
                  <div style={{flex:1}}>
                    <div style={{fontFamily:"var(--font-sans)", fontWeight:600, fontSize:15, color:"#fff"}}>{atk.name}</div>
                    {atk.note && <div style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-3)", marginTop:2}}>{atk.note}</div>}
                  </div>
                  <div style={{fontFamily:"var(--font-sans)", fontWeight:800, fontSize:22, color:"#fff"}}>
                    {atk.dmg > 0 ? atk.dmg : "—"}
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div style={{display:"flex", gap:16, paddingTop:12, borderTop:"1px dashed var(--border-hairline)"}}>
            <div style={{display:"flex", alignItems:"center", gap:6}}>
              <span style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-4)", letterSpacing:"0.1em"}}>DEBILIDAD ×2</span>
              <EnergyChip type={pokemon.weak} size={18}/>
              <span style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-2)"}}>{TYPE_INFO[pokemon.weak].name}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function StatBox({ label, value, sub, accent }) {
  return (
    <div style={{
      background:"var(--bg-surface)",
      border:"1px solid var(--border-hairline)",
      borderLeft: `2px solid ${accent}`,
      borderRadius: 2,
      padding:"10px 12px",
    }}>
      <div style={{fontFamily:"var(--font-mono)", fontSize:9, color:"var(--fg-4)", letterSpacing:"0.15em"}}>{label}</div>
      <div style={{fontFamily:"var(--font-sans)", fontWeight:800, fontSize:22, color:"#fff", lineHeight:1.1}}>{value}</div>
      {sub && <div style={{fontFamily:"var(--font-mono)", fontSize:9, color:"var(--fg-3)"}}>{sub}</div>}
    </div>
  );
}

window.Collection = Collection;
