// ============================================
// COIN ECONOMY (admin) — dashboard de fluxo de moedas
// ============================================
// Consome admin_coin_economy_stats(p_token, p_days). Admin-only no server.
// Mostra: circulação total, wallets ativas, time series de inflow/outflow
// por dia, breakdown por tx_type, top holders.

function CoinEconomyScreen({ navigate }) {
    const [days, setDays]   = React.useState(30);
    const [data, setData]   = React.useState(null);
    const [error, setError] = React.useState(null);

    React.useEffect(() => {
        const Lobby = window.MastershotLobby;
        if (!Lobby?.getCoinEconomyStats) {
            setError(window.t("Backend offline"));
            setData({});
            return;
        }
        setData(null);
        setError(null);
        let cancelled = false;
        Lobby.getCoinEconomyStats(days)
            .then((result) => {
                if (cancelled) return;
                if (result?.ok) setData(result);
                else { setError(result?.reason || window.t("sem dados")); setData({}); }
            })
            .catch((err) => {
                if (cancelled) return;
                console.warn("[coin-economy] falhou:", err.message);
                setError(err.message);
                setData({});
            });
        return () => { cancelled = true; };
    }, [days]);

    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: 32, paddingLeft: 48, paddingRight: 48,
                maxWidth: 1400, margin: "0 auto",
                height: "100%", display: "flex", flexDirection: "column", gap: 16,
            }}>
                {/* Header */}
                <div className="panel ce-header" style={{ padding: 24, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <div>
                        <div style={{ fontFamily: "var(--font-display)", fontSize: 26, color: "var(--gold-300)", fontWeight: 700 }}>
                            {window.t("Economia de Moedas")}
                        </div>
                        <div style={{ fontSize: 12, color: "var(--ink-300)", marginTop: 4 }}>
                            {window.t("Fluxo agregado dos últimos {n} dias. Atualiza ao mudar a janela.", { n: days })}
                        </div>
                    </div>
                    <div className="ce-days" style={{ display: "flex", gap: 6 }}>
                        {[7, 30, 90].map(d => (
                            <button key={d} className={`tab ${days === d ? "active" : ""}`} onClick={() => setDays(d)}>
                                {d}d
                            </button>
                        ))}
                    </div>
                </div>

                {data === null && (
                    <div className="panel" style={{ padding: 40, textAlign: "center", color: "var(--ink-400)" }}>
                        {window.t("Carregando dados…")}
                    </div>
                )}

                {data && error && !data.ok && (
                    <div className="panel" style={{ padding: 24, color: "var(--loss-bright)", fontFamily: "var(--font-mono)", fontSize: 13 }}>
                        {window.t("Erro:")} {error}
                    </div>
                )}

                {data?.ok && (
                    <div className="ce-scroll" style={{ flex: 1, minHeight: 0, overflowY: "auto", paddingRight: 8, display: "flex", flexDirection: "column", gap: 16 }}>
                        {/* Top stats */}
                        <div className="ce-stats" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
                            <BigStat label={window.t("Em Circulação")} value={`$ ${Number(data.circulating || 0).toLocaleString()}`} color="gold"/>
                            <BigStat label={window.t("Wallets Ativas")} value={Number(data.active_wallets || 0).toLocaleString()}/>
                            <BigStat label={window.t("Movimentações")} value={Number((data.daily || []).reduce((s, d) => s + (d.tx_count || 0), 0)).toLocaleString()}/>
                        </div>

                        {/* Time series */}
                        <div className="panel" style={{ padding: 20 }}>
                            <div className="panel-title" style={{ marginBottom: 14 }}>
                                {window.t("Fluxo Diário · {n} dias", { n: days })}
                            </div>
                            <DailyFlowChart daily={data.daily || []}/>
                            <div style={{ display: "flex", gap: 18, marginTop: 12, fontSize: 11, color: "var(--ink-400)" }}>
                                <div><span style={{ display: "inline-block", width: 10, height: 10, background: "var(--win-bright)", marginRight: 6, verticalAlign: "middle" }}/>{window.t("Inflow")}</div>
                                <div><span style={{ display: "inline-block", width: 10, height: 10, background: "var(--loss-bright)", marginRight: 6, verticalAlign: "middle" }}/>{window.t("Outflow")}</div>
                            </div>
                        </div>

                        {/* By type breakdown */}
                        <div className="panel" style={{ padding: 20 }}>
                            <div className="panel-title" style={{ marginBottom: 14 }}>
                                {window.t("Por Tipo de Transação")}
                            </div>
                            <div className="ce-table-scroll">
                            {(data.by_type || []).length === 0 ? (
                                <div style={{ color: "var(--ink-400)", fontSize: 12 }}>{window.t("Sem transações no período.")}</div>
                            ) : (
                                <div className="ce-bytype-head" style={{ display: "grid", gridTemplateColumns: "2fr 1.5fr 1.5fr 1fr", gap: 12, fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-400)", padding: "8px 12px" }}>
                                    <div>{window.t("Tipo")}</div><div style={{ textAlign: "right" }}>{window.t("Inflow")}</div><div style={{ textAlign: "right" }}>{window.t("Outflow")}</div><div style={{ textAlign: "right" }}>{window.t("Nº TX")}</div>
                                </div>
                            )}
                            {(data.by_type || []).map(t => (
                                <div key={t.tx_type} className="ce-bytype-row" style={{
                                    display: "grid",
                                    gridTemplateColumns: "2fr 1.5fr 1.5fr 1fr",
                                    gap: 12, padding: "10px 12px",
                                    borderTop: "1px solid var(--ink-800)",
                                    fontSize: 13, alignItems: "center",
                                }}>
                                    <div style={{ color: "var(--ink-100)", fontFamily: "var(--font-mono)" }}>{t.tx_type}</div>
                                    <div style={{ textAlign: "right", color: "var(--win-bright)", fontFamily: "var(--font-mono)" }}>
                                        +{Number(t.total_in || 0).toLocaleString()}
                                    </div>
                                    <div style={{ textAlign: "right", color: "var(--loss-bright)", fontFamily: "var(--font-mono)" }}>
                                        -{Number(t.total_out || 0).toLocaleString()}
                                    </div>
                                    <div style={{ textAlign: "right", color: "var(--ink-300)", fontFamily: "var(--font-mono)" }}>
                                        {Number(t.count || 0).toLocaleString()}
                                    </div>
                                </div>
                            ))}
                            </div>
                        </div>

                        {/* Top earners */}
                        <div className="panel" style={{ padding: 20 }}>
                            <div className="panel-title" style={{ marginBottom: 14 }}>
                                {window.t("Top Holders")}
                            </div>
                            {(data.top_earners || []).length === 0 ? (
                                <div style={{ color: "var(--ink-400)", fontSize: 12 }}>{window.t("Nenhuma wallet com saldo positivo.")}</div>
                            ) : (
                                (data.top_earners || []).map((u, i) => (
                                    <div key={u.user_id} style={{
                                        display: "grid",
                                        gridTemplateColumns: "40px 1fr auto",
                                        gap: 12, padding: "10px 12px",
                                        borderTop: i > 0 ? "1px solid var(--ink-800)" : "none",
                                        alignItems: "center",
                                    }}>
                                        <div style={{ fontFamily: "var(--font-display)", fontSize: 16, color: "var(--gold-300)", fontWeight: 700 }}>#{i + 1}</div>
                                        <div style={{ fontSize: 13, color: "var(--ink-100)" }}>{u.nick}</div>
                                        <div style={{ fontFamily: "var(--font-mono)", color: "var(--gold-300)", fontSize: 14 }}>
                                            $ {Number(u.coins || 0).toLocaleString()}
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>
                    </div>
                )}
            </div>

            <style>{`
                @media (max-width: 768px) {
                    .ce-scroll { overflow: visible !important; padding-right: 0 !important; }
                    .ce-header { flex-wrap: wrap !important; gap: 12px !important; padding: 16px !important; }
                    .ce-stats { gap: 10px !important; }
                    .ce-stat { padding: 14px !important; }
                    .ce-stat-value { font-size: clamp(18px, 5.5vw, 26px) !important; }
                    .ce-table-scroll {
                        overflow-x: auto;
                        overscroll-behavior-x: contain;
                        -webkit-overflow-scrolling: touch;
                    }
                    .ce-bytype-head, .ce-bytype-row { min-width: 430px; }
                }
                @media (max-width: 480px) {
                    .ce-header { flex-direction: column !important; align-items: flex-start !important; }
                    .ce-stats { grid-template-columns: 1fr !important; }
                    .ce-scroll > .panel { padding: 14px !important; }
                    .ce-chart { gap: 1px !important; }
                }
            `}</style>
        </div>
    );
}

function BigStat({ label, value, color }) {
    const c = { gold: "var(--gold-300)", win: "var(--win-bright)", loss: "var(--loss-bright)" }[color] || "var(--ink-100)";
    return (
        <div className="panel ce-stat" style={{ padding: 22 }}>
            <div style={{ fontSize: 10, color: "var(--ink-300)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 8, fontWeight: 600 }}>{label}</div>
            <div className="ce-stat-value" style={{ fontFamily: "var(--font-display)", fontSize: 32, color: c, fontWeight: 700 }}>{value}</div>
        </div>
    );
}

// Bar chart: pra cada dia, barra verde acima (inflow) e barra vermelha
// embaixo (outflow). Escala compartilhada pelo maior abs value.
function DailyFlowChart({ daily }) {
    if (!daily || daily.length === 0) {
        return <div style={{ height: 120, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-400)", fontSize: 12 }}>{window.t("Sem dados no período.")}</div>;
    }
    const maxAbs = Math.max(
        ...daily.map(d => Math.abs(Number(d.inflow || 0))),
        ...daily.map(d => Math.abs(Number(d.outflow || 0))),
        1,
    );
    return (
        <div className="ce-chart" style={{ display: "flex", alignItems: "center", gap: 2, height: 140 }}>
            {daily.map((d, i) => {
                const inH  = (Number(d.inflow  || 0) / maxAbs) * 60;
                const outH = (Number(d.outflow || 0) / maxAbs) * 60;
                return (
                    <div key={d.day || i} title={`${d.day}: +${d.inflow} / -${d.outflow}`}
                         style={{ flex: 1, display: "flex", flexDirection: "column", height: "100%", alignItems: "center" }}>
                        <div style={{ flex: 1, display: "flex", alignItems: "flex-end", width: "100%" }}>
                            <div style={{ width: "100%", height: `${inH}%`, background: "var(--win-bright)", opacity: 0.85, borderRadius: "2px 2px 0 0" }}/>
                        </div>
                        <div style={{ height: 1, width: "100%", background: "var(--ink-600)" }}/>
                        <div style={{ flex: 1, display: "flex", alignItems: "flex-start", width: "100%" }}>
                            <div style={{ width: "100%", height: `${outH}%`, background: "var(--loss-bright)", opacity: 0.85, borderRadius: "0 0 2px 2px" }}/>
                        </div>
                    </div>
                );
            })}
        </div>
    );
}

Object.assign(window, { CoinEconomyScreen });
