// ============================================
// INVENTORY — coleção do jogador (tacos owned + bloqueados) com seleção
// ============================================
// Selecionar um taco salva em localStorage; launchGame em menu.html lê
// e passa como ?cue= pro game. main.js detecta padrão NN_ e renderiza
// com buildSkinnedCue (skin via PNG horizontal em src/cues/).

const SELECTED_CUE_KEY = "mastershot.selectedCueId";

function getSelectedCueId() {
    try { return localStorage.getItem(SELECTED_CUE_KEY) || "oak"; } catch { return "oak"; }
}
function setSelectedCueId(id) {
    try { localStorage.setItem(SELECTED_CUE_KEY, id); } catch {}
}

// Avatar equipado — mesmo padrão do taco (só localStorage; launchGame lê).
const SELECTED_AVATAR_KEY = "mastershot.selectedAvatarId";
function getSelectedAvatarId() {
    try { return localStorage.getItem(SELECTED_AVATAR_KEY) || "m01_classic"; } catch { return "m01_classic"; }
}
function setSelectedAvatarId(id) {
    try { localStorage.setItem(SELECTED_AVATAR_KEY, id); } catch {}
}

function InventoryScreen({ navigate }) {
    const PLAYER = window.MastershotAuth.getPlayer();
    const [section, setSection] = React.useState("cues");   // cues | avatars
    const sectionTabs = (
        <div className="inv-filters" style={{ display: "flex", gap: 8, marginBottom: 14 }}>
            {[["cues", window.t("Tacos")], ["avatars", window.t("Avatares")]].map(([k, l]) => (
                <button key={k} className={`tab ${section === k ? "active" : ""}`} onClick={() => setSection(k)}>{l}</button>
            ))}
        </div>
    );
    if (section === "avatars") {
        return <AvatarInventoryView navigate={navigate} PLAYER={PLAYER} sectionTabs={sectionTabs}/>;
    }
    const { CUES } = window.MastershotData;
    // Ownership REAL do servidor (get_owned_items inclui starters, compras
    // e tacos destravados pelo nível real). Cache em window.__msOwned —
    // helpers definidos em arcade.jsx (carregado antes deste arquivo).
    // Sem dados (loading/offline): mantém os flags do data.js como hoje.
    const ownedGate = window.__msUseOwnedGate ? window.__msUseOwnedGate() : null;
    const serverCueIds = window.__msOwnedSet ? window.__msOwnedSet(ownedGate, "cue") : null;
    // Admin tem TODOS os tacos liberados (override owned).
    const cuesView = PLAYER.isAdmin
        ? CUES.map(c => ({ ...c, owned: true }))
        : serverCueIds
            ? CUES.map(c => ({ ...c, owned: serverCueIds.has(c.id) }))
            : CUES;
    const [selected, setSelected] = React.useState(getSelectedCueId);
    const [filter, setFilter] = React.useState("owned");   // owned | all | locked

    // Taco equipado (localStorage) que não é owned no servidor → cai pro
    // primeiro taco owned (starter garantido pela API) e persiste.
    React.useEffect(() => {
        if (!serverCueIds || PLAYER.isAdmin) return;
        if (!serverCueIds.has(selected)) {
            const first = CUES.find(c => serverCueIds.has(c.id)) || CUES[0];
            setSelectedCueId(first.id);
            setSelected(first.id);
        }
    }, [ownedGate, selected]);

    function equip(cue) {
        if (!cue.owned) return;
        setSelectedCueId(cue.id);
        setSelected(cue.id);
    }

    const owned   = cuesView.filter(c => c.owned);
    const locked  = cuesView.filter(c => !c.owned);
    const visible = filter === "owned" ? owned : filter === "locked" ? locked : cuesView;

    const equippedCue = cuesView.find(c => c.id === selected) || cuesView[0];

    return (
        <div className="screen active" style={{ opacity: 1 }}>
            <AmbientBackdrop/>
            <Particles count={6}/>
            <TopBar navigate={navigate}/>

            <div style={{ position: "absolute", top: 88, left: 48, zIndex: 20 }}>
                <button className="back-btn" onClick={() => navigate("menu")}>
                    <span dangerouslySetInnerHTML={{ __html: window.Icon.back(14) }}/><span>{window.t("Menu")}</span>
                </button>
            </div>

            <div style={{
                position: "relative", zIndex: 5,
                paddingTop: 110, paddingBottom: 32, paddingLeft: 48, paddingRight: 48,
                maxWidth: 1400, margin: "0 auto",
                height: "100%", display: "flex", flexDirection: "column", gap: 18,
            }}>
                {/* Header com taco equipado */}
                <div className="panel inv-header" style={{ padding: 24, display: "flex", gap: 28, alignItems: "center" }}>
                    <div className="inv-skinbox" style={{
                        flex: "0 0 360px",
                        background: "var(--ink-900)",
                        border: "1px solid var(--ink-700)",
                        borderRadius: "var(--r-md)",
                        padding: 16,
                        display: "flex", alignItems: "center", justifyContent: "center",
                    }}>
                        {equippedCue?.skin
                            ? <img src={equippedCue.skin} alt={equippedCue.name}
                                style={{ width: "100%", maxHeight: 80, objectFit: "contain", display: "block" }}/>
                            : <div style={{ color: "var(--ink-400)", fontSize: 12 }}>{window.t("Taco 3D legacy")}</div>}
                    </div>
                    <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 10, color: "var(--gold-500)", letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 600, marginBottom: 4 }}>
                            {window.t("Equipado")}
                        </div>
                        <div className="inv-equipped-name" style={{ fontFamily: "var(--font-display)", fontSize: 32, color: "var(--ink-100)", fontWeight: 600, marginBottom: 6 }}>
                            {equippedCue?.name || "—"}
                        </div>
                        <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
                            <span className="chip chip-gold">{equippedCue?.tier || "—"}</span>
                            <span className="chip">{equippedCue?.id}</span>
                        </div>
                        <div className="inv-equipped-stats" style={{ display: "flex", gap: 18 }}>
                            <StatTriple label={window.t("Força")}    value={equippedCue?.power}/>
                            <StatTriple label={window.t("Precisão")} value={equippedCue?.accuracy}/>
                            <StatTriple label={window.t("Efeito")}   value={equippedCue?.spin}/>
                        </div>
                    </div>
                    <div className="inv-collection" style={{ textAlign: "right" }}>
                        <div style={{ fontSize: 10, color: "var(--ink-400)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 4 }}>{window.t("Coleção")}</div>
                        <div style={{ fontFamily: "var(--font-display)", fontSize: 24, color: "var(--gold-300)", fontWeight: 700 }}>
                            {owned.length} / {CUES.length}
                        </div>
                    </div>
                </div>

                {sectionTabs}

                {/* Filtros */}
                <div className="inv-filters" style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    {[
                        ["owned",  window.t("Meus tacos ({n})", { n: owned.length })],
                        ["locked", window.t("Bloqueados ({n})", { n: locked.length })],
                        ["all",    window.t("Todos ({n})", { n: CUES.length })],
                    ].map(([k, l]) => (
                        <button key={k} className={`tab ${filter===k?"active":""}`} onClick={() => setFilter(k)}>{l}</button>
                    ))}
                    {ownedGate === "loading" && (
                        <span style={{ fontSize: 10, color: "var(--ink-500)", letterSpacing: "0.06em" }}>
                            {window.t("sincronizando coleção…")}
                        </span>
                    )}
                </div>

                {/* Grid de tacos */}
                <div className="inv-scroll" style={{ flex: 1, minHeight: 0, overflowY: "auto", paddingRight: 8 }}>
                    <div className="inv-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
                        {visible.map(c => (
                            <InventoryCueCard
                                key={c.id}
                                cue={c}
                                equipped={selected === c.id}
                                playerLevel={PLAYER.level}
                                onEquip={() => equip(c)}
                                onShop={() => navigate("shop")}
                            />
                        ))}
                    </div>
                    {visible.length === 0 && (
                        <div className="panel" style={{ padding: 32, textAlign: "center", color: "var(--ink-400)" }}>
                            {window.t("Nenhum taco neste filtro.")}
                        </div>
                    )}
                </div>
            </div>

            <style>{`
                @media (max-width: 768px) {
                    .inv-header { flex-wrap: wrap !important; gap: 16px !important; padding: 16px !important; }
                    .inv-skinbox { flex: 1 1 100% !important; }
                    .inv-equipped-name { font-size: clamp(20px, 6vw, 26px) !important; }
                    .inv-filters { flex-wrap: wrap !important; }
                    .inv-scroll { overflow: visible !important; padding-right: 0 !important; }
                    .inv-grid { grid-template-columns: repeat(2, 1fr) !important; }
                }
                @media (max-width: 480px) {
                    .inv-header { flex-direction: column !important; align-items: stretch !important; gap: 12px !important; }
                    .inv-collection { text-align: left !important; }
                    .inv-equipped-stats { flex-wrap: wrap !important; gap: 12px !important; }
                    .inv-grid { gap: 10px !important; }
                    .inv-grid > .panel { padding: 10px !important; }
                }
            `}</style>
        </div>
    );
}

// ===== Inventário de AVATARES (mesma casca da tela de tacos) =====
function AvatarInventoryView({ navigate, PLAYER, sectionTabs }) {
    const [avatars, setAvatars] = React.useState(() => window.MastershotData.AVATARS || []);
    React.useEffect(() => {
        const h = () => setAvatars([...(window.MastershotData.AVATARS || [])]);
        window.addEventListener("mastershot:avatars-ready", h);
        return () => window.removeEventListener("mastershot:avatars-ready", h);
    }, []);

    const ownedGate = window.__msUseOwnedGate ? window.__msUseOwnedGate() : null;
    const serverIds = window.__msOwnedSet ? window.__msOwnedSet(ownedGate, "avatar") : null;
    const view = PLAYER.isAdmin
        ? avatars.map(a => ({ ...a, owned: true }))
        : serverIds
            ? avatars.map(a => ({ ...a, owned: a.starter || serverIds.has(a.id) }))
            : avatars;

    const [selected, setSelected] = React.useState(getSelectedAvatarId);
    const [filter, setFilter] = React.useState("owned");

    React.useEffect(() => {
        if (!view.length) return;
        if (!view.find(a => a.id === selected && a.owned)) {
            const first = view.find(a => a.owned) || view[0];
            if (first) { setSelectedAvatarId(first.id); setSelected(first.id); }
        }
    }, [avatars, ownedGate]);

    function equip(a) { if (!a.owned) return; setSelectedAvatarId(a.id); setSelected(a.id); }

    const owned = view.filter(a => a.owned);
    const locked = view.filter(a => !a.owned);
    const visible = filter === "owned" ? owned : filter === "locked" ? locked : view;
    const equipped = view.find(a => a.id === selected) || view[0];

    return (
        <div className="screen active" style={{ opacity: 1 }}>
            <AmbientBackdrop/><Particles count={6}/><TopBar navigate={navigate}/>
            <div style={{ position: "absolute", top: 88, left: 48, zIndex: 20 }}>
                <button className="back-btn" onClick={() => navigate("menu")}>
                    <span dangerouslySetInnerHTML={{ __html: window.Icon.back(14) }}/><span>{window.t("Menu")}</span>
                </button>
            </div>
            <div style={{ position: "relative", zIndex: 5, paddingTop: 110, paddingBottom: 32, paddingLeft: 48, paddingRight: 48, maxWidth: 1400, margin: "0 auto", height: "100%", display: "flex", flexDirection: "column", gap: 18 }}>
                <div className="panel inv-header" style={{ padding: 24, display: "flex", gap: 28, alignItems: "center" }}>
                    <div className="inv-skinbox" style={{ flex: "0 0 200px", background: "var(--ink-900)", border: "1px solid var(--ink-700)", borderRadius: "var(--r-md)", padding: 12, display: "flex", alignItems: "center", justifyContent: "center", minHeight: 220 }}>
                        {equipped?.thumb
                            ? <img src={equipped.thumb} alt={equipped.name} style={{ maxWidth: "100%", maxHeight: 200, objectFit: "contain", display: "block" }}/>
                            : <div style={{ color: "var(--ink-400)", fontSize: 12 }}>{window.t("Sem preview")}</div>}
                    </div>
                    <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 10, color: "var(--gold-500)", letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 600, marginBottom: 4 }}>{window.t("Avatar equipado")}</div>
                        <div className="inv-equipped-name" style={{ fontFamily: "var(--font-display)", fontSize: 32, color: "var(--ink-100)", fontWeight: 600, marginBottom: 6 }}>{equipped?.name || "—"}</div>
                        <div style={{ display: "flex", gap: 8 }}>
                            <span className="chip chip-gold">{equipped?.tier || "—"}</span>
                            <span className="chip">{equipped?.gender === "m" ? window.t("Masculino") : equipped?.gender === "f" ? window.t("Feminino") : window.t("Unissex")}</span>
                        </div>
                    </div>
                    <div className="inv-collection" style={{ textAlign: "right" }}>
                        <div style={{ fontSize: 10, color: "var(--ink-400)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 4 }}>{window.t("Coleção")}</div>
                        <div style={{ fontFamily: "var(--font-display)", fontSize: 24, color: "var(--gold-300)", fontWeight: 700 }}>{owned.length} / {view.length}</div>
                    </div>
                </div>

                {sectionTabs}

                <div className="inv-filters" style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    {[["owned", window.t("Meus avatares ({n})", { n: owned.length })], ["locked", window.t("Bloqueados ({n})", { n: locked.length })], ["all", window.t("Todos ({n})", { n: view.length })]].map(([k, l]) => (
                        <button key={k} className={`tab ${filter === k ? "active" : ""}`} onClick={() => setFilter(k)}>{l}</button>
                    ))}
                </div>

                <div className="inv-scroll" style={{ flex: 1, minHeight: 0, overflowY: "auto", paddingRight: 8 }}>
                    <div className="inv-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
                        {visible.map(a => (
                            <InventoryAvatarCard key={a.id} avatar={a} equipped={selected === a.id} playerLevel={PLAYER.level} onEquip={() => equip(a)} onShop={() => navigate("shop")}/>
                        ))}
                    </div>
                    {visible.length === 0 && (
                        <div className="panel" style={{ padding: 32, textAlign: "center", color: "var(--ink-400)" }}>
                            {avatars.length === 0 ? window.t("Carregando avatares…") : window.t("Nenhum avatar neste filtro.")}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

function InventoryAvatarCard({ avatar, equipped, playerLevel, onEquip, onShop }) {
    const canUnlock = !avatar.owned && avatar.unlock?.type === "level" && playerLevel >= avatar.unlock.value;
    const buyable = !avatar.owned && (avatar.unlock?.type === "coins" || avatar.unlock?.type === "chips");
    return (
        <div className="panel" style={{ padding: 14, opacity: avatar.owned ? 1 : 0.6, border: equipped ? "2px solid var(--gold-300)" : "1px solid var(--ink-700)", boxShadow: equipped ? "0 0 16px rgba(232,185,73,0.25)" : "none", transition: "all 0.2s", display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ background: "var(--ink-900)", border: "1px solid var(--ink-700)", borderRadius: 4, padding: 6, height: 180, display: "flex", alignItems: "center", justifyContent: "center" }}>
                {avatar.thumb
                    ? <img src={avatar.thumb} alt={avatar.name} style={{ maxWidth: "100%", maxHeight: 168, objectFit: "contain", display: "block", filter: avatar.owned ? "none" : "grayscale(0.7)" }}/>
                    : <span style={{ fontSize: 10, color: "var(--ink-500)" }}>{window.t("sem preview")}</span>}
            </div>
            <div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                    <div style={{ fontFamily: "var(--font-display)", fontSize: 15, color: "var(--ink-100)", fontWeight: 600 }}>{avatar.name}</div>
                    {equipped && <span className="chip chip-gold" style={{ fontSize: 9 }}>{window.t("EQUIPADO")}</span>}
                </div>
                <div style={{ fontSize: 10, color: "var(--gold-500)", letterSpacing: "0.14em", textTransform: "uppercase" }}>{avatar.tier || "—"}</div>
            </div>
            <div style={{ marginTop: 4 }}>
                {avatar.owned && !equipped && (
                    <button className="btn-primary" style={{ width: "100%", fontSize: 11 }} onClick={onEquip}>{window.t("Equipar")}</button>
                )}
                {avatar.owned && equipped && (
                    <button className="btn-secondary" style={{ width: "100%", fontSize: 11, opacity: 0.7 }} disabled>{window.t("✓ Equipado")}</button>
                )}
                {!avatar.owned && (
                    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                        <div style={{ fontSize: 11, color: canUnlock ? "var(--win-bright)" : "var(--ink-400)", textAlign: "center", padding: "2px 0" }}>
                            {avatar.unlock?.type === "level" && (canUnlock ? window.t("🔓 Desbloqueável! (Nv. {n})", { n: avatar.unlock.value }) : window.t("🔒 Requer Nv. {n}", { n: avatar.unlock.value }))}
                            {avatar.unlock?.type === "coins" && `🔒 $ ${avatar.unlock.value?.toLocaleString?.() || avatar.price}`}
                            {avatar.unlock?.type === "chips" && `🔒 💎 ${avatar.unlock.value}`}
                        </div>
                        {buyable && (
                            <button className="btn-ghost" style={{ width: "100%", fontSize: 11, padding: "8px 10px" }} onClick={onShop}>{window.t("Comprar na loja")}</button>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}

function InventoryCueCard({ cue, equipped, playerLevel, onEquip, onShop }) {
    const canUnlock = !cue.owned && cue.unlock?.type === "level" && playerLevel >= cue.unlock.value;
    const buyable = !cue.owned && (cue.unlock?.type === "coins" || cue.unlock?.type === "chips");

    return (
        <div className="panel" style={{
            padding: 14,
            opacity: cue.owned ? 1 : 0.6,
            border: equipped ? "2px solid var(--gold-300)" : "1px solid var(--ink-700)",
            boxShadow: equipped ? "0 0 16px rgba(232,185,73,0.25)" : "none",
            transition: "all 0.2s",
            display: "flex", flexDirection: "column", gap: 10,
        }}>
            {/* Skin preview */}
            <div style={{
                background: "var(--ink-900)", border: "1px solid var(--ink-700)",
                borderRadius: 4, padding: 6, height: 56,
                display: "flex", alignItems: "center", justifyContent: "center",
            }}>
                {cue.skin
                    ? <img src={cue.skin} alt={cue.name} style={{ width: "100%", maxHeight: 44, objectFit: "contain", display: "block", filter: cue.owned ? "none" : "grayscale(0.7)" }}/>
                    : <span style={{ fontSize: 10, color: "var(--ink-500)" }}>{window.t("3D legacy")}</span>}
            </div>

            {/* Nome + tier */}
            <div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                    <div style={{ fontFamily: "var(--font-display)", fontSize: 15, color: "var(--ink-100)", fontWeight: 600 }}>{cue.name}</div>
                    {equipped && <span className="chip chip-gold" style={{ fontSize: 9 }}>{window.t("EQUIPADO")}</span>}
                </div>
                <div style={{ fontSize: 10, color: "var(--gold-500)", letterSpacing: "0.14em", textTransform: "uppercase" }}>{cue.tier || "—"}</div>
            </div>

            {/* Stats */}
            <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                <CueStatBar label={window.t("Força")} value={cue.power}/>
                <CueStatBar label={window.t("Precisão")} value={cue.accuracy}/>
                <CueStatBar label={window.t("Efeito")} value={cue.spin}/>
            </div>

            {/* Action / status */}
            <div style={{ marginTop: 4 }}>
                {cue.owned && !equipped && (
                    <button className="btn-primary" style={{ width: "100%", fontSize: 11 }} onClick={onEquip}>
                        {window.t("Equipar")}
                    </button>
                )}
                {cue.owned && equipped && (
                    <button className="btn-secondary" style={{ width: "100%", fontSize: 11, opacity: 0.7 }} disabled>
                        {window.t("✓ Equipado")}
                    </button>
                )}
                {!cue.owned && (
                    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                        <div style={{
                            fontSize: 11, color: canUnlock ? "var(--win-bright)" : "var(--ink-400)",
                            textAlign: "center", padding: "2px 0",
                        }}>
                            {cue.unlock?.type === "level" && (canUnlock
                                ? window.t("🔓 Desbloqueável! (Nv. {n})", { n: cue.unlock.value })
                                : window.t("🔒 Requer Nv. {n}", { n: cue.unlock.value }))}
                            {cue.unlock?.type === "coins" && `🔒 $ ${cue.unlock.value?.toLocaleString?.() || cue.price}`}
                            {cue.unlock?.type === "chips" && `🔒 💎 ${cue.unlock.value}`}
                        </div>
                        {buyable && (
                            <button className="btn-ghost" style={{ width: "100%", fontSize: 11, padding: "8px 10px" }} onClick={onShop}>
                                {window.t("Comprar na loja")}
                            </button>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}

function CueStatBar({ label, value }) {
    const v = value || 0;
    return (
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 10 }}>
            <span style={{ width: 56, color: "var(--ink-400)", letterSpacing: "0.06em" }}>{label}</span>
            <div style={{ flex: 1, height: 4, background: "var(--ink-800)", borderRadius: 2, overflow: "hidden" }}>
                <div style={{ width: `${v}%`, height: "100%", background: "var(--g-gold)" }}/>
            </div>
            <span style={{ color: "var(--gold-300)", fontFamily: "var(--font-mono)", width: 20, textAlign: "right" }}>{v}</span>
        </div>
    );
}

function StatTriple({ label, value }) {
    return (
        <div>
            <div style={{ fontSize: 10, color: "var(--ink-400)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 2 }}>{label}</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 20, color: "var(--gold-300)", fontWeight: 700 }}>{value || "—"}</div>
        </div>
    );
}

Object.assign(window, { InventoryScreen, getSelectedCueId, setSelectedCueId, getSelectedAvatarId, setSelectedAvatarId });
