// ============================================
// CREATE ROOM
// ============================================

function CreateRoom({ navigate }) {
    const { GAME_MODES, TABLES, ENVIRONMENTS } = window.MastershotData;
    const [mode, setMode] = React.useState("8ball");
    const [tableId, setTable] = React.useState("royal");
    const [envId, setEnv] = React.useState("pool-hall");
    const [bet, setBet] = React.useState(1000);
    const [currency, setCur] = React.useState("coin");
    const [privacy, setPriv] = React.useState("public");
    const [bestOf, setBo] = React.useState(3);
    const [timePerShot, setTps] = React.useState(45);
    const [spectators, setSpec] = React.useState(true);
    const [name, setName] = React.useState("Mesa do ShadowCue");
    const [password, setPw] = React.useState("");

    const m = GAME_MODES.find(x => x.id === mode);
    const t = TABLES.find(x => x.id === tableId);

    return (
        <div className="screen active" style={{ opacity: 1 }}>
            <AmbientBackdrop/>
            <Particles count={10}/>
            <TopBar navigate={navigate}/>
            <div style={{ position: "absolute", top: 88, left: 48, zIndex: 20 }}>
                <button className="back-btn" onClick={() => navigate("online")}>
                    <span dangerouslySetInnerHTML={{ __html: window.Icon.back(14) }}/>
                    <span>Lobby</span>
                </button>
            </div>

            <div style={{
                position: "relative", zIndex: 5,
                paddingTop: 110, paddingBottom: 40, paddingLeft: 48, paddingRight: 48,
                maxWidth: 1200, margin: "0 auto",
                height: "100%",
                display: "grid", gridTemplateColumns: "1fr 420px", gap: 24,
            }}>
                {/* LEFT: form */}
                <div className="panel" style={{ overflowY: "auto" }}>
                    <div className="panel-header">
                        <div className="panel-title">Criar Sala</div>
                        <span className="chip">Privada ou pública</span>
                    </div>
                    <div className="panel-body" style={{ display: "flex", flexDirection: "column", gap: 22 }}>

                        <div className="field">
                            <label className="field-label">Nome da Sala</label>
                            <input className="input" value={name} onChange={e=>setName(e.target.value)} maxLength={40}/>
                        </div>

                        <div>
                            <label className="field-label" style={{ marginBottom: 10, display: "block" }}>Modo de Jogo</label>
                            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
                                {GAME_MODES.map(gm => (
                                    <button key={gm.id} onClick={()=>setMode(gm.id)}
                                        className={`mini-tile ${mode===gm.id?"sel":""}`}>
                                        <div className="mini-tile-icon">{gm.icon}</div>
                                        <div className="mini-tile-name">{gm.name}</div>
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div>
                            <label className="field-label" style={{ marginBottom: 10, display: "block" }}>Mesa</label>
                            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
                                {TABLES.filter(tb => tb.unlocked).map(tb => (
                                    <button key={tb.id} onClick={()=> setTable(tb.id)}
                                        className={`table-card ${tableId===tb.id?"sel":""} ${!tb.owned?"locked":""}`}>{/* gate de owned removido temporariamente — readicionar quando tiver auth */}
                                        <div style={{
                                            aspectRatio: "2/1.2",
                                            borderRadius: 6,
                                            background: `linear-gradient(145deg, ${tb.rail}, ${shade(tb.rail,-0.3)})`,
                                            padding: 4,
                                            position: "relative",
                                        }}>
                                            <div style={{
                                                width: "100%", height: "100%",
                                                borderRadius: 3,
                                                background: `radial-gradient(ellipse, ${tb.felt}, ${shade(tb.felt,-0.3)})`,
                                                boxShadow: "inset 0 0 8px rgba(0,0,0,0.5)",
                                            }}/>
                                            {!tb.owned && (
                                                <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(0,0,0,0.6)", borderRadius: 6, color: "var(--gold-400)" }}
                                                    dangerouslySetInnerHTML={{ __html: window.Icon.lock(18) }}/>
                                            )}
                                        </div>
                                        <div style={{ fontSize: 11, color: "var(--ink-100)", fontWeight: 600, marginTop: 8 }}>{tb.name}</div>
                                        <div style={{ fontSize: 9, color: "var(--gold-500)", letterSpacing: "0.12em", textTransform: "uppercase" }}>{tb.tier}</div>
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Environment selector */}
                        <div>
                            <label className="field-label" style={{ marginBottom: 10, display: "block" }}>Ambiente</label>
                            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
                                {ENVIRONMENTS.filter(e => e.unlocked).map(e => (
                                    <button key={e.id} onClick={()=> setEnv(e.id)}
                                        className={`table-card ${envId===e.id?"sel":""} ${!e.owned?"locked":""}`}>
                                        <div style={{
                                            aspectRatio: "2/1.2",
                                            borderRadius: 6,
                                            background: `linear-gradient(180deg, ${e.preview.sky} 0%, ${e.preview.sky} 60%, ${e.preview.floor} 60%, ${e.preview.floor} 100%)`,
                                            position: "relative",
                                        }}>
                                            {!e.owned && (
                                                <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(0,0,0,0.6)", borderRadius: 6, color: "var(--gold-400)" }}
                                                    dangerouslySetInnerHTML={{ __html: window.Icon.lock(18) }}/>
                                            )}
                                        </div>
                                        <div style={{ fontSize: 11, color: "var(--ink-100)", fontWeight: 600, marginTop: 8 }}>{e.name}</div>
                                        <div style={{ fontSize: 9, color: "var(--gold-500)", letterSpacing: "0.12em", textTransform: "uppercase" }}>{e.tier}</div>
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                            <div className="field">
                                <label className="field-label">Melhor de</label>
                                <div className="seg">
                                    {[1,3,5,7].map(n => (
                                        <button key={n} className={`seg-btn ${bestOf===n?"sel":""}`} onClick={()=>setBo(n)}>BO{n}</button>
                                    ))}
                                </div>
                            </div>
                            <div className="field">
                                <label className="field-label">Tempo por tacada</label>
                                <div className="seg">
                                    {[20,30,45,60].map(n => (
                                        <button key={n} className={`seg-btn ${timePerShot===n?"sel":""}`} onClick={()=>setTps(n)}>{n}s</button>
                                    ))}
                                </div>
                            </div>
                        </div>

                        <div className="field">
                            <label className="field-label">Aposta ({currency === "coin" ? "moedas" : "fichas premium"})</label>
                            <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                                <div className="seg" style={{ flexShrink: 0 }}>
                                    <button className={`seg-btn ${currency==="coin"?"sel":""}`} onClick={()=>setCur("coin")} style={{ padding: "8px 14px" }}>
                                        <span className="currency-icon coin" style={{ width: 16, height: 16, fontSize: 8, display: "inline-flex", marginRight: 4 }}>$</span>
                                        Moedas
                                    </button>
                                    <button className={`seg-btn ${currency==="chip"?"sel":""}`} onClick={()=>setCur("chip")} style={{ padding: "8px 14px" }}>
                                        <span className="currency-icon chip" style={{ width: 16, height: 16, fontSize: 8, display: "inline-flex", marginRight: 4 }}>◆</span>
                                        Fichas
                                    </button>
                                </div>
                                <div style={{ flex: 1 }}>
                                    <input type="range" min={100} max={50000} step={100} value={bet} onChange={e=>setBet(+e.target.value)} className="slider"/>
                                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: "var(--ink-400)", marginTop: 4 }}>
                                        <span>100</span><span>50.000</span>
                                    </div>
                                </div>
                                <Currency type={currency} amount={bet}/>
                            </div>
                        </div>

                        <div className="field">
                            <label className="field-label">Visibilidade</label>
                            <div className="seg">
                                <button className={`seg-btn ${privacy==="public"?"sel":""}`} onClick={()=>setPriv("public")}>Pública</button>
                                <button className={`seg-btn ${privacy==="friends"?"sel":""}`} onClick={()=>setPriv("friends")}>Só Amigos</button>
                                <button className={`seg-btn ${privacy==="private"?"sel":""}`} onClick={()=>setPriv("private")}>Privada (senha)</button>
                            </div>
                        </div>

                        {privacy === "private" && (
                            <div className="field">
                                <label className="field-label">Senha</label>
                                <input className="input" type="text" value={password} onChange={e=>setPw(e.target.value)} placeholder="••••" maxLength={8}/>
                            </div>
                        )}

                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 0", borderTop: "1px solid var(--ink-700)" }}>
                            <div>
                                <div style={{ fontSize: 13, color: "var(--ink-100)", fontWeight: 500 }}>Permitir espectadores</div>
                                <div style={{ fontSize: 11, color: "var(--ink-400)" }}>Outros jogadores podem assistir à partida</div>
                            </div>
                            <label className="toggle">
                                <input type="checkbox" checked={spectators} onChange={e=>setSpec(e.target.checked)}/>
                                <span className="toggle-slider"/>
                            </label>
                        </div>
                    </div>
                </div>

                {/* RIGHT: summary */}
                <div style={{ display: "flex", flexDirection: "column", gap: 16, minHeight: 0 }}>
                    <div className="panel" style={{ flex: 1, overflow: "hidden", display: "flex", flexDirection: "column" }}>
                        <div className="panel-header">
                            <div className="panel-title">Resumo</div>
                        </div>
                        <div style={{ flex: 1, overflowY: "auto" }}>
                            <TablePreview table={t} mode={m}/>

                            <div style={{ padding: "18px 24px", display: "flex", flexDirection: "column", gap: 10 }}>
                                <SummaryRow label="Modo" value={m.name}/>
                                <SummaryRow label="Mesa" value={t.name}/>
                                <SummaryRow label="Formato" value={`Melhor de ${bestOf}`}/>
                                <SummaryRow label="Tempo" value={`${timePerShot}s por tacada`}/>
                                <SummaryRow label="Visibilidade" value={privacy === "public" ? "Pública" : privacy === "friends" ? "Só Amigos" : "Privada"}/>
                                <SummaryRow label="Aposta" value={<Currency type={currency} amount={bet} size="sm"/>}/>
                                <div style={{ padding: "12px 0", borderTop: "1px dashed var(--ink-700)", marginTop: 8 }}>
                                    <div style={{ fontSize: 11, color: "var(--gold-500)", letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 4 }}>Prêmio ao Vencedor</div>
                                    <div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: "var(--gold-300)" }}>
                                        {currency === "coin" ? "$" : "◆"} {(bet * 1.9).toLocaleString("pt-BR")}
                                    </div>
                                    <div style={{ fontSize: 10, color: "var(--ink-400)" }}>(taxa da casa: 5%)</div>
                                </div>
                            </div>
                        </div>
                        <div style={{ padding: 18, borderTop: "1px solid var(--ink-700)", background: "rgba(0,0,0,0.3)" }}>
                            <button className="btn-cta" style={{ width: "100%" }}
                                onClick={async () => {
                                    const Lobby = window.MastershotLobby;
                                    const spec = {
                                        mode, table_id: tableId, env_id: envId,
                                        bet, best_of: bestOf, max_players: 2,
                                    };
                                    try {
                                        sessionStorage.setItem('mastershot.room', JSON.stringify({
                                            mode, table: tableId, env: envId, bet, bestOf, timePerShot,
                                        }));
                                    } catch (e) {}
                                    if (!Lobby) {
                                        navigate("waiting");
                                        return;
                                    }
                                    try {
                                        const room = await Lobby.createRoom(spec);
                                        navigate("waiting", { roomId: room.id, isHost: true });
                                    } catch (err) {
                                        alert("Erro ao criar sala: " + err.message);
                                    }
                                }}>
                                <span dangerouslySetInnerHTML={{ __html: window.Icon.check(16) }}/>
                                <span>Criar e Entrar</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <style>{`
                .mini-tile {
                    padding: 10px 6px;
                    background: var(--ink-900);
                    border: 1px solid var(--ink-700);
                    border-radius: var(--r-sm);
                    color: var(--ink-200);
                    cursor: pointer;
                    transition: all var(--t-fast);
                    text-align: center;
                }
                .mini-tile:hover { border-color: var(--gold-700); }
                .mini-tile.sel {
                    border-color: var(--gold-500);
                    background: linear-gradient(180deg, rgba(232,185,73,0.08), var(--ink-900));
                    box-shadow: 0 0 0 1px var(--gold-600);
                }
                .mini-tile-icon { font-family: var(--font-display); font-size: 20px; color: var(--gold-400); margin-bottom: 4px; line-height: 1; }
                .mini-tile-name { font-size: 11px; font-weight: 600; color: var(--ink-100); letter-spacing: 0.04em; }
                .table-card {
                    background: transparent;
                    border: 1px solid var(--ink-700);
                    border-radius: var(--r-sm);
                    padding: 10px;
                    cursor: pointer;
                    transition: all var(--t-fast);
                    text-align: left;
                }
                .table-card:hover:not(:disabled) { border-color: var(--gold-700); }
                .table-card.sel { border-color: var(--gold-500); box-shadow: 0 0 0 1px var(--gold-600); }
                .table-card.locked { opacity: 0.65; }
                .table-card.locked:hover { opacity: 0.85; border-color: var(--gold-700); }
            `}</style>
        </div>
    );
}

function SummaryRow({ label, value }) {
    return (
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13 }}>
            <span style={{ color: "var(--ink-400)", letterSpacing: "0.06em" }}>{label}</span>
            <span style={{ color: "var(--ink-100)", fontWeight: 500 }}>{value}</span>
        </div>
    );
}

Object.assign(window, { CreateRoom, SummaryRow });
