// ============================================
// PROFILE — stats, achievements, collection, graphs
// ============================================

function ProfileScreen({ navigate }) {
    const PLAYER = window.MastershotAuth.getPlayer();
    const [tab, setTab] = React.useState("stats");

    return (
        <div className="screen active" style={{ opacity: 1 }}>
            <AmbientBackdrop/>
            <Particles count={8}/>
            <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>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: 20,
            }}>
                {/* Profile header card */}
                <div className="panel" style={{ padding: 28, display: "flex", gap: 28, alignItems: "center" }}>
                    <div style={{ position: "relative" }}>
                        <Avatar initials={PLAYER.avatar} level={PLAYER.level} size="xl"/>
                    </div>
                    <div style={{ flex: 1 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                            <CountryFlag code="BR" size={22}/>
                            <div style={{ fontSize: 11, color: "var(--gold-500)", letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 600 }}>
                                {PLAYER.title}
                            </div>
                        </div>
                        <div style={{ fontFamily: "var(--font-display)", fontSize: 38, color: "var(--ink-100)", letterSpacing: "0.03em", fontWeight: 600 }}>
                            {PLAYER.nick}
                        </div>
                        <div style={{ display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap" }}>
                            <span className="chip chip-gold">ELO {PLAYER.elo}</span>
                            <span className="chip">#{PLAYER.rank} Global</span>
                            <span className="chip chip-win">{PLAYER.stats.winRate}% vitórias</span>
                            <StreakBadge count={PLAYER.stats.currentStreak}/>
                        </div>
                    </div>
                    {/* XP bar */}
                    <div style={{ width: 260 }}>
                        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontSize: 11 }}>
                            <span style={{ color: "var(--gold-500)", letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 600 }}>Nível {PLAYER.level}</span>
                            <span style={{ color: "var(--ink-300)" }}>{PLAYER.xp.toLocaleString()} / {PLAYER.xpNext.toLocaleString()} XP</span>
                        </div>
                        <div style={{ height: 10, background: "var(--ink-900)", border: "1px solid var(--ink-700)", borderRadius: "var(--r-full)", overflow: "hidden" }}>
                            <div style={{ width: `${PLAYER.xp/PLAYER.xpNext*100}%`, height: "100%", background: "var(--g-gold)", boxShadow: "0 0 12px rgba(232,185,73,0.4)" }}/>
                        </div>
                        <div style={{ fontSize: 10, color: "var(--ink-400)", marginTop: 4 }}>{(PLAYER.xpNext - PLAYER.xp).toLocaleString()} XP para Nv. {PLAYER.level + 1}</div>
                    </div>
                </div>

                {/* Tabs */}
                <div className="tabs">
                    {[["stats","Estatísticas"],["achievements","Conquistas"],["history","Histórico"],["collection","Coleção"]].map(([k,l]) => (
                        <button key={k} className={`tab ${tab===k?"active":""}`} onClick={()=>setTab(k)}>{l}</button>
                    ))}
                </div>

                {/* Content */}
                <div style={{ flex: 1, minHeight: 0, overflowY: "auto", paddingRight: 8 }}>
                    {tab === "stats" && <StatsTab/>}
                    {tab === "achievements" && <AchievementsTab/>}
                    {tab === "history" && <HistoryTab/>}
                    {tab === "collection" && <CollectionTab/>}
                </div>
            </div>
        </div>
    );
}

function StatsTab() {
    const PLAYER = window.MastershotAuth.getPlayer();
    return (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
            <StatCard label="Partidas Totais" value={PLAYER.stats.totalGames.toLocaleString()}/>
            <StatCard label="Vitórias" value={PLAYER.stats.wins.toLocaleString()} delta={`${PLAYER.stats.winRate}%`} color="win"/>
            <StatCard label="Derrotas" value={PLAYER.stats.losses.toLocaleString()}/>
            <StatCard label="Maior Streak" value={PLAYER.stats.longestStreak} icon="flame"/>
            <StatCard label="Acerto Médio" value={`${PLAYER.stats.avgPotAccuracy}%`} color="gold"/>
            <StatCard label="Vitórias no Break" value={`${PLAYER.stats.breakWinRate}%`}/>
            <StatCard label="Tacadas Totais" value={PLAYER.stats.shotsTotal.toLocaleString()}/>
            <StatCard label="Ganhos Totais" value={`$ ${PLAYER.stats.totalEarnings.toLocaleString()}`} color="gold"/>

            {/* Graph */}
            <div className="panel" style={{ gridColumn: "1 / 3", padding: 20 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
                    <div className="panel-title">Win Rate · 30 dias</div>
                    <span className="chip chip-win">↑ +12%</span>
                </div>
                <PerformanceGraph data={PLAYER.winRateGraph} color="#3fa075" unit="%"/>
            </div>

            <div className="panel" style={{ gridColumn: "3 / 5", padding: 20 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
                    <div className="panel-title">Ganhos · 30 dias</div>
                    <span className="chip chip-gold">$ 52.430</span>
                </div>
                <EarningsGraph data={PLAYER.earningsGraph}/>
            </div>

            {/* Mode stats */}
            <div className="panel" style={{ gridColumn: "1 / -1", padding: 20 }}>
                <div className="panel-title" style={{ marginBottom: 14 }}>Desempenho por Modo</div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12 }}>
                    {PLAYER.modeStats.map(m => (
                        <div key={m.mode} style={{
                            padding: 16,
                            background: "var(--ink-900)",
                            border: "1px solid var(--ink-700)",
                            borderRadius: "var(--r-sm)",
                        }}>
                            <div style={{ fontFamily: "var(--font-display)", fontSize: 16, color: "var(--gold-300)", marginBottom: 8 }}>{m.mode}</div>
                            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 6 }}>
                                <span style={{ color: "var(--ink-400)" }}>Partidas</span>
                                <span style={{ color: "var(--ink-100)" }}>{m.games}</span>
                            </div>
                            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 6 }}>
                                <span style={{ color: "var(--ink-400)" }}>Vitórias</span>
                                <span style={{ color: "var(--win-bright)" }}>{m.wins} ({m.winRate}%)</span>
                            </div>
                            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12 }}>
                                <span style={{ color: "var(--ink-400)" }}>ELO</span>
                                <span style={{ color: "var(--gold-300)" }}>{m.elo}</span>
                            </div>
                            <div style={{ height: 4, background: "var(--ink-800)", borderRadius: 2, marginTop: 10, overflow: "hidden" }}>
                                <div style={{ width: `${m.winRate}%`, height: "100%", background: "var(--g-gold)" }}/>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
}

function StatCard({ label, value, delta, color, icon }) {
    const c = { win: "var(--win-bright)", gold: "var(--gold-300)" }[color] || "var(--ink-100)";
    return (
        <div className="panel" style={{ padding: 20 }}>
            <div style={{ fontSize: 10, color: "var(--ink-300)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 8, fontWeight: 600 }}>{label}</div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 30, color: c, fontWeight: 700 }}>{value}</div>
                {delta && <span style={{ fontSize: 12, color: "var(--win-bright)" }}>{delta}</span>}
                {icon === "flame" && <FlameSvg size={18} intense/>}
            </div>
        </div>
    );
}

function PerformanceGraph({ data, color, unit }) {
    const max = Math.max(...data);
    const min = Math.min(...data);
    const pts = data.map((v, i) => {
        const x = (i / (data.length - 1)) * 100;
        const y = 100 - ((v - min) / (max - min)) * 80 - 10;
        return `${x},${y}`;
    }).join(" ");
    return (
        <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: "100%", height: 120 }}>
            <defs>
                <linearGradient id="graph-area" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor={color} stopOpacity="0.35"/>
                    <stop offset="100%" stopColor={color} stopOpacity="0"/>
                </linearGradient>
            </defs>
            {/* gridlines */}
            {[25,50,75].map(y => <line key={y} x1="0" y1={y} x2="100" y2={y} stroke="rgba(255,255,255,0.05)" strokeWidth="0.3"/>)}
            <polyline points={`0,100 ${pts} 100,100`} fill="url(#graph-area)"/>
            <polyline points={pts} fill="none" stroke={color} strokeWidth="0.8" strokeLinejoin="round"/>
            {data.map((v, i) => {
                const x = (i / (data.length - 1)) * 100;
                const y = 100 - ((v - min) / (max - min)) * 80 - 10;
                return <circle key={i} cx={x} cy={y} r="0.8" fill={color}/>;
            })}
        </svg>
    );
}

function EarningsGraph({ data }) {
    const max = Math.max(...data.map(Math.abs));
    return (
        <div style={{ display: "flex", alignItems: "center", gap: 2, height: 120 }}>
            {data.map((v, i) => {
                const h = Math.abs(v) / max * 50;
                const positive = v >= 0;
                return (
                    <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", height: "100%", alignItems: "center" }}>
                        <div style={{ flex: 1, display: "flex", alignItems: "flex-end", width: "100%" }}>
                            {positive && <div style={{ width: "100%", height: `${h}%`, background: "linear-gradient(180deg, var(--gold-400), var(--gold-700))", 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%" }}>
                            {!positive && <div style={{ width: "100%", height: `${h}%`, background: "linear-gradient(0deg, var(--loss), var(--loss-bright))", borderRadius: "0 0 2px 2px" }}/>}
                        </div>
                    </div>
                );
            })}
        </div>
    );
}

function AchievementsTab() {
    const PLAYER = window.MastershotAuth.getPlayer();
    const tierColors = {
        bronze: ["#b08553", "#6b4f2e"],
        silver: ["#c8c8c8", "#7a7a7a"],
        gold: ["#f4cf6e", "#9c7a1a"],
        legend: ["#ff9ec4", "#8e6bc9"],
    };
    return (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
            {PLAYER.achievements.map(a => {
                const [c1, c2] = tierColors[a.tier];
                return (
                    <div key={a.id} className="panel" style={{
                        padding: 20,
                        opacity: a.unlocked ? 1 : 0.65,
                        position: "relative",
                        overflow: "hidden",
                    }}>
                        {a.unlocked && (
                            <div style={{
                                position: "absolute", top: 0, right: 0,
                                padding: "3px 10px",
                                fontSize: 9, fontWeight: 700, letterSpacing: "0.14em",
                                color: "var(--ink-900)",
                                background: `linear-gradient(135deg, ${c1}, ${c2})`,
                                borderBottomLeftRadius: 8,
                                textTransform: "uppercase",
                            }}>{a.tier}</div>
                        )}
                        <div style={{
                            width: 52, height: 52,
                            borderRadius: "50%",
                            background: a.unlocked ? `radial-gradient(circle at 35% 30%, ${c1}, ${c2})` : "var(--ink-800)",
                            border: `2px solid ${a.unlocked ? c2 : "var(--ink-600)"}`,
                            display: "flex", alignItems: "center", justifyContent: "center",
                            fontSize: 24,
                            margin: "0 0 14px",
                            filter: a.unlocked ? `drop-shadow(0 0 12px ${c1}60)` : "grayscale(1)",
                        }}>
                            {a.icon}
                        </div>
                        <div style={{ fontFamily: "var(--font-display)", fontSize: 15, color: a.unlocked ? "var(--ink-100)" : "var(--ink-300)", fontWeight: 600, marginBottom: 4 }}>{a.name}</div>
                        <div style={{ fontSize: 11, color: "var(--ink-400)", lineHeight: 1.5, marginBottom: 10 }}>{a.desc}</div>
                        {!a.unlocked && (
                            <>
                                <div style={{ height: 4, background: "var(--ink-800)", borderRadius: 2, overflow: "hidden" }}>
                                    <div style={{ width: `${a.progress}%`, height: "100%", background: `linear-gradient(90deg, ${c1}, ${c2})` }}/>
                                </div>
                                <div style={{ fontSize: 10, color: "var(--ink-400)", marginTop: 4, textAlign: "right" }}>{a.progress}%</div>
                            </>
                        )}
                        {a.unlocked && <div style={{ fontSize: 10, color: c1, letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 600 }}>✓ Desbloqueado</div>}
                    </div>
                );
            })}
        </div>
    );
}

function HistoryTab() {
    const PLAYER = window.MastershotAuth.getPlayer();
    return (
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <div style={{
                display: "grid",
                gridTemplateColumns: "auto 1.5fr 1fr 1fr 100px 1fr 1fr",
                gap: 14, padding: "10px 18px",
                fontSize: 10, fontWeight: 600, letterSpacing: "0.14em",
                textTransform: "uppercase", color: "var(--ink-400)",
            }}>
                <div>Res.</div><div>Oponente</div><div>Modo</div><div>Placar</div><div>Streak</div><div>Recompensa</div><div>Quando</div>
            </div>
            {PLAYER.history.map((h, i) => (
                <div key={i} className="panel" style={{
                    display: "grid",
                    gridTemplateColumns: "auto 1.5fr 1fr 1fr 100px 1fr 1fr",
                    gap: 14, padding: "14px 18px", alignItems: "center",
                    borderLeft: `3px solid ${h.result === "W" ? "var(--win-bright)" : "var(--loss-bright)"}`,
                    animation: `card-in 0.3s var(--ease-out) ${i * 0.04}s both`,
                }}>
                    <div style={{
                        width: 32, height: 32, borderRadius: "50%",
                        display: "flex", alignItems: "center", justifyContent: "center",
                        background: h.result === "W" ? "rgba(63,160,117,0.2)" : "rgba(194,69,58,0.2)",
                        color: h.result === "W" ? "var(--win-bright)" : "var(--loss-bright)",
                        fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 13,
                        border: `1px solid ${h.result === "W" ? "rgba(63,160,117,0.4)" : "rgba(194,69,58,0.4)"}`,
                    }}>{h.result}</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <Avatar initials={h.oppAvatar} size="sm"/>
                        <span style={{ fontSize: 13, color: "var(--ink-100)" }}>{h.opp}</span>
                    </div>
                    <div style={{ fontSize: 12, color: "var(--ink-200)" }}>{h.mode}</div>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--gold-300)" }}>{h.score}</div>
                    <div><StreakBadge count={h.streak}/></div>
                    <div style={{ fontSize: 13, color: h.reward > 0 ? "var(--win-bright)" : "var(--loss-bright)", fontWeight: 600 }}>
                        {h.reward > 0 ? "+" : ""}{h.reward.toLocaleString()}
                    </div>
                    <div style={{ fontSize: 12, color: "var(--ink-400)" }}>{h.time}</div>
                </div>
            ))}
        </div>
    );
}

function CollectionTab() {
    const { TABLES, CUES } = window.MastershotData;
    return (
        <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            <div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "var(--gold-300)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 14 }}>
                    Tacos · {CUES.filter(c=>c.owned).length}/{CUES.length}
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
                    {CUES.map(c => <CueCard key={c.id} cue={c}/>)}
                </div>
            </div>
            <div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "var(--gold-300)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 14 }}>
                    Mesas · {TABLES.filter(t=>t.owned).length}/{TABLES.length}
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
                    {TABLES.map(t => (
                        <div key={t.id} className="panel" style={{ padding: 14, opacity: t.owned ? 1 : 0.6 }}>
                            <div style={{
                                aspectRatio: "2/1.2",
                                borderRadius: 6,
                                background: `linear-gradient(145deg, ${t.rail}, ${shade(t.rail,-0.3)})`,
                                padding: 6,
                            }}>
                                <div style={{
                                    width: "100%", height: "100%",
                                    borderRadius: 4,
                                    background: `radial-gradient(ellipse, ${t.felt}, ${shade(t.felt,-0.3)})`,
                                    boxShadow: "inset 0 0 12px rgba(0,0,0,0.6)",
                                }}/>
                            </div>
                            <div style={{ fontSize: 13, color: "var(--ink-100)", fontWeight: 600, marginTop: 10 }}>{t.name}</div>
                            <div style={{ fontSize: 10, color: "var(--gold-500)", letterSpacing: "0.14em", textTransform: "uppercase" }}>{t.tier}</div>
                            {!t.owned && <div style={{ fontSize: 11, color: "var(--ink-400)", marginTop: 4 }}>
                                {t.unlocked ? `$ ${t.price.toLocaleString()}` : "🔒 Bloqueada"}
                            </div>}
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
}

function CueCard({ cue }) {
    return (
        <div className="panel" style={{ padding: 18, opacity: cue.owned ? 1 : 0.7 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 10 }}>
                <div>
                    <div style={{ fontFamily: "var(--font-display)", fontSize: 15, color: "var(--ink-100)", fontWeight: 600 }}>{cue.name}</div>
                    <div style={{ fontSize: 10, color: "var(--gold-500)", letterSpacing: "0.14em", textTransform: "uppercase" }}>{cue.tier}</div>
                </div>
                {cue.owned && <span className="chip chip-gold">Possui</span>}
            </div>
            {/* cue visual */}
            <div style={{
                height: 14,
                background: "linear-gradient(90deg, #3a1d0f 0%, #7a421f 70%, #fce29a 85%, #a89368 100%)",
                borderRadius: "var(--r-full)",
                marginBottom: 12,
                boxShadow: "0 2px 4px rgba(0,0,0,0.4)",
            }}/>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <StatBar label="Força" value={cue.power}/>
                <StatBar label="Precisão" value={cue.accuracy}/>
                <StatBar label="Efeito" value={cue.spin}/>
            </div>
        </div>
    );
}

function StatBar({ label, value }) {
    return (
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11 }}>
            <span style={{ width: 60, color: "var(--ink-400)", letterSpacing: "0.08em" }}>{label}</span>
            <div style={{ flex: 1, height: 4, background: "var(--ink-800)", borderRadius: 2, overflow: "hidden" }}>
                <div style={{ width: `${value}%`, height: "100%", background: "var(--g-gold)" }}/>
            </div>
            <span style={{ color: "var(--gold-300)", fontFamily: "var(--font-mono)", width: 24, textAlign: "right" }}>{value}</span>
        </div>
    );
}

Object.assign(window, { ProfileScreen, StatCard, CueCard, StatBar });
