// ============================================
// SHOP PRICING — admin define preço + moeda de cada item da loja
// ============================================
// Edita shop_catalog (fonte de verdade do shop_buy) via admin_set_shop_item.
// Moeda por item: Grátis | Moeda do jogo (coins) | Moeda paga (mastercoins/rosa).
// Helper: src/menu/shop-catalog-sync.js (__msUseShopCatalog / __msSetShopItem).

// Valores iniciais da linha: do shop_catalog (DB) se houver; senão deriva do
// data.js (price + flag chips) pra mostrar o preço efetivo atual.
function shopRowInit(item, entry) {
    if (entry) {
        return {
            currency: entry.price_chips > 0 ? "chips" : (entry.price_coins > 0 ? "coins" : "free"),
            price: entry.price_chips > 0 ? entry.price_chips : entry.price_coins,
            level: entry.min_level || 1,
            active: entry.active !== false,
        };
    }
    const chips = !!item.chips;
    const price = item.price || 0;
    return {
        currency: chips && price > 0 ? "chips" : (price > 0 ? "coins" : "free"),
        price: price,
        level: 1,
        active: true,
    };
}

function ShopPriceRow({ type, item, entry }) {
    const init = React.useMemo(() => shopRowInit(item, entry), [entry, item.id]);
    const [currency, setCurrency] = React.useState(init.currency);
    const [price, setPrice] = React.useState(init.price);
    const [level, setLevel] = React.useState(init.level);
    const [active, setActive] = React.useState(init.active);
    const [busy, setBusy] = React.useState(false);
    const [flash, setFlash] = React.useState(null);

    // Se o catálogo do DB chegar/mudar, re-sincroniza os campos (sem sobrescrever
    // enquanto o admin digita — só quando o entry de fato muda).
    React.useEffect(() => {
        setCurrency(init.currency); setPrice(init.price);
        setLevel(init.level); setActive(init.active);
    }, [entry]);

    const dirty = currency !== init.currency || Number(price) !== Number(init.price)
        || Number(level) !== Number(init.level) || active !== init.active;

    const save = async () => {
        setBusy(true); setFlash(null);
        const opts = {
            price_coins: currency === "coins" ? (parseInt(price, 10) || 0) : 0,
            price_chips: currency === "chips" ? (parseInt(price, 10) || 0) : 0,
            min_level: parseInt(level, 10) || 1,
            active,
        };
        const res = window.__msSetShopItem
            ? await window.__msSetShopItem(type, item.id, opts)
            : { ok: false, error: window.t("loja indisponível") };
        setBusy(false);
        if (res.ok) { setFlash("ok"); setTimeout(() => setFlash(null), 1500); }
        else { setFlash(res.error || window.t("erro")); setTimeout(() => setFlash(null), 5000); }
    };

    const curBtn = (val, label, color) => (
        <button onClick={() => setCurrency(val)}
            style={{
                padding: "6px 10px", borderRadius: 8, fontSize: 12, fontWeight: 700, cursor: "pointer",
                border: "1px solid " + (currency === val ? color : "rgba(255,255,255,0.14)"),
                background: currency === val ? color + "22" : "transparent",
                color: currency === val ? color : "rgba(243,236,216,0.6)",
            }}>{label}</button>
    );

    return (
        <div style={{
            display: "grid", gridTemplateColumns: "1.4fr auto auto auto auto auto", gap: 10, alignItems: "center",
            padding: "10px 12px", borderRadius: 10, background: active ? "rgba(255,255,255,0.03)" : "rgba(120,40,40,0.10)",
            border: "1px solid rgba(255,255,255,0.06)",
        }}>
            <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink-100)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{item.name || item.id}</div>
                <div style={{ fontSize: 10, color: "rgba(243,236,216,0.4)" }}>{item.id}{item.tier ? " · " + item.tier : ""}</div>
            </div>
            <div style={{ display: "flex", gap: 6 }}>
                {curBtn("free", window.t("Grátis"), "#7fae6a")}
                {curBtn("coins", window.t("Moeda"), "#e0a83a")}
                {curBtn("chips", window.t("Rosa"), "#ec5b9e")}
            </div>
            <input className="input" type="number" min="0" value={currency === "free" ? 0 : price}
                disabled={currency === "free"} onChange={(e) => setPrice(e.target.value)}
                style={{ width: 96, padding: "8px 10px", opacity: currency === "free" ? 0.4 : 1 }}/>
            <label style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 11, color: "rgba(243,236,216,0.6)" }}>
                {window.t("Nível")}
                <input className="input" type="number" min="1" value={level} onChange={(e) => setLevel(e.target.value)}
                    style={{ width: 56, padding: "8px 8px" }}/>
            </label>
            <button onClick={() => setActive(!active)} title={window.t("Disponível na loja")}
                style={{
                    padding: "6px 10px", borderRadius: 8, fontSize: 12, fontWeight: 700, cursor: "pointer",
                    border: "1px solid " + (active ? "rgba(127,174,106,0.5)" : "rgba(216,69,58,0.5)"),
                    background: "transparent", color: active ? "#7fae6a" : "#d8453a",
                }}>{active ? window.t("Ativo") : window.t("Oculto")}</button>
            <button onClick={save} disabled={busy || !dirty}
                style={{
                    padding: "8px 14px", borderRadius: 8, fontSize: 12, fontWeight: 800, cursor: (busy || !dirty) ? "default" : "pointer",
                    border: "none", background: flash === "ok" ? "#2f7a3a" : (dirty ? "linear-gradient(180deg,#f5c451,#e0a83a)" : "rgba(255,255,255,0.08)"),
                    color: flash === "ok" ? "#fff" : (dirty ? "#2a1d05" : "rgba(243,236,216,0.4)"), minWidth: 78,
                }}>
                {busy ? "…" : flash === "ok" ? window.t("Salvo ✓") : window.t("Salvar")}
            </button>
            {flash && flash !== "ok" && (
                <div style={{ gridColumn: "1 / -1", fontSize: 11, color: "#ff8a7a" }}>{flash}</div>
            )}
        </div>
    );
}

function ShopPricingScreen({ navigate }) {
    const PLAYER = window.MastershotAuth.getPlayer();
    const catalog = window.__msUseShopCatalog ? window.__msUseShopCatalog() : (window.__msShopCatalog || {});
    const D = window.MastershotData || {};
    const groups = [
        { type: "table", label: window.t("Mesas"),     items: D.TABLES || [] },
        { type: "cue",   label: window.t("Tacos"),     items: D.CUES || [] },
        { type: "env",   label: window.t("Ambientes"), items: D.ENVIRONMENTS || [] },
    ];

    if (!PLAYER || !PLAYER.isAdmin) {
        return (
            <div className="screen active" style={{ opacity: 1 }}>
                <AmbientBackdrop/><TopBar navigate={navigate}/>
                <div style={{ paddingTop: 160, textAlign: "center", color: "var(--ink-300)" }}>
                    {window.t("Área exclusiva para administradores.")}
                </div>
            </div>
        );
    }

    return (
        <div className="screen active" style={{ opacity: 1 }}>
            <AmbientBackdrop/>
            <TopBar navigate={navigate}/>
            <div style={{ position: "absolute", top: 88, left: 48, zIndex: 20 }}>
                <button className="back-btn" onClick={() => navigate("admin")}>
                    <span dangerouslySetInnerHTML={{ __html: window.Icon.back(14) }}/><span>{window.t("Admin")}</span>
                </button>
            </div>
            <div style={{
                position: "relative", zIndex: 5, paddingTop: 110, paddingBottom: 40, paddingLeft: 48, paddingRight: 48,
                maxWidth: 1100, margin: "0 auto", height: "100%", overflowY: "auto",
            }}>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 34, color: "var(--ink-100)", letterSpacing: "0.04em", fontWeight: 600, marginBottom: 6 }}>
                    {window.t("Loja & Preços")}
                </div>
                <div style={{ fontSize: 13, color: "rgba(243,236,216,0.55)", marginBottom: 24 }}>
                    {window.t("Defina o preço e a moeda de cada item.")} <b style={{ color: "#e0a83a" }}>{window.t("Moeda")}</b> = {window.t("moeda do jogo (coins)")};
                    <b style={{ color: "#ec5b9e" }}> {window.t("Rosa")}</b> = {window.t("moeda paga (mastercoins). As mudanças valem na hora pra todos.")}
                </div>

                {groups.map((g) => (
                    <div key={g.type} style={{ marginBottom: 28 }}>
                        <div style={{ fontSize: 12, color: "var(--gold-500)", letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700, marginBottom: 10 }}>
                            {g.label} ({g.items.length})
                        </div>
                        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                            {g.items.map((item) => (
                                <ShopPriceRow key={item.id} type={g.type} item={item}
                                    entry={catalog[g.type + ":" + item.id] || null}/>
                            ))}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}

window.ShopPricingScreen = ShopPricingScreen;
