<!doctype html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Prêmios por Cidade | Survive Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Rajdhani:wght@500;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-main: #060913;
            --panel: #0b122a;
            --panel-2: #0f1735;
            --line: #34427a;
            --text: #f4f7ff;
            --muted: #9aa7d4;
            --accent: #ffcb3c;
            --accent-2: #6d5efc;
            --ok: #22c55e;
        }

        * { box-sizing: border-box; }

        body {
            margin: 0;
            min-height: 100vh;
            font-family: 'Rajdhani', sans-serif;
            color: var(--text);
            background:
                radial-gradient(920px 480px at 15% -10%, #6d28d93d 0%, transparent 56%),
                radial-gradient(800px 480px at 100% 120%, #ff6a2b36 0%, transparent 62%),
                linear-gradient(145deg, #060913, #140b2b);
        }

        .layout {
            min-height: 100vh;
            display: grid;
            grid-template-columns: 292px 1fr;
            gap: 18px;
            padding: 18px;
        }

        .sidebar {
            border: 1px solid #38457c;
            border-radius: 20px;
            background: linear-gradient(180deg, #090f23cc, #070b19cc);
            backdrop-filter: blur(8px);
            padding: 18px 14px;
            display: flex;
            flex-direction: column;
            gap: 14px;
            box-shadow: 0 16px 52px #0008;
        }

        .brand {
            font-family: 'Bebas Neue', sans-serif;
            letter-spacing: 1px;
            font-size: 2.2rem;
            padding: 14px 12px;
            border: 1px solid #3a4a86;
            border-radius: 14px;
            background: linear-gradient(160deg, #0c183a, #0c142d);
            line-height: 1;
        }

        .brand small {
            display: block;
            font-family: 'Rajdhani', sans-serif;
            font-size: 0.9rem;
            color: var(--muted);
            letter-spacing: 0.5px;
            margin-top: 4px;
        }

        .status-chip {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            width: fit-content;
            border: 1px solid #2f6d4a;
            border-radius: 999px;
            background: #0f2e1f;
            color: #9cf7bf;
            font-size: 0.85rem;
            padding: 5px 10px;
            font-weight: 700;
        }

        .status-chip::before {
            content: '';
            width: 8px;
            height: 8px;
            border-radius: 999px;
            background: var(--ok);
            box-shadow: 0 0 10px var(--ok);
        }

        .nav {
            display: grid;
            gap: 8px;
        }

        .nav-item {
            color: #c8d3fb;
            text-decoration: none;
            border: 1px solid #22305f;
            border-radius: 12px;
            padding: 10px 11px;
            background: #0b132e;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: border-color 120ms ease, background 120ms ease, transform 120ms ease;
        }

        .nav-item:hover {
            transform: translateY(-1px);
            border-color: #4b5fa5;
        }

        .nav-icon {
            width: 30px;
            height: 30px;
            border-radius: 9px;
            border: 1px solid #40539a;
            display: grid;
            place-items: center;
            background: #121e42;
            color: #e8edff;
        }

        .nav-item.active {
            border-color: #6f63f8;
            background: linear-gradient(90deg, #3a2680, #16234f);
            color: #fff;
        }

        .nav-item.active .nav-icon {
            border-color: #8b84ff;
            background: #2a2f6d;
        }

        .nav-item.sub {
            margin-left: 16px;
            padding: 8px 10px;
            font-size: 0.95rem;
            border-style: dashed;
        }

        .logout {
            margin-top: auto;
        }

        .logout button {
            width: 100%;
            border: 0;
            border-radius: 12px;
            padding: 11px;
            font: inherit;
            font-weight: 700;
            cursor: pointer;
            background: linear-gradient(90deg, #ef4444, #f97316);
            color: #fff;
        }

        .content {
            padding: 4px;
            min-width: 0;
        }

        .topbar-main {
            min-width: 0;
        }

        .topbar {
            border: 1px solid var(--line);
            border-radius: 20px;
            padding: 18px;
            background: linear-gradient(160deg, #0f1838cc, #0a122acc);
            backdrop-filter: blur(8px);
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
            box-shadow: 0 14px 44px #0007;
        }

        h1 {
            margin: 0;
            font-family: 'Bebas Neue', sans-serif;
            font-size: clamp(2rem, 4vw, 3.2rem);
            letter-spacing: 1px;
        }

        .subtitle {
            margin: 2px 0 0;
            color: var(--muted);
            font-size: 1.05rem;
        }

        .meta {
            margin-top: 10px;
            font-weight: 700;
            color: #d4ddff;
        }

        .topbar-badge {
            border: 1px solid #4456a0;
            background: #0e1738;
            border-radius: 14px;
            padding: 9px 12px;
            font-size: 0.95rem;
            color: #d9e1ff;
            font-weight: 700;
            white-space: nowrap;
        }

        .settings-section {
            border: 1px solid var(--line);
            border-radius: 18px;
            background: linear-gradient(160deg, #0f1838cc, #0a122acc);
            padding: 16px;
            box-shadow: 0 14px 44px #0006;
        }

        .settings-title {
            margin: 0;
            font-family: 'Bebas Neue', sans-serif;
            font-size: 2rem;
            letter-spacing: 0.8px;
        }

        .settings-subtitle {
            margin: 4px 0 12px;
            color: var(--muted);
            font-size: 1rem;
        }

        .settings-layout {
            display: grid;
            grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
            gap: 12px;
        }

        .settings-form,
        .settings-list {
            border: 1px solid #33467f;
            border-radius: 14px;
            background: #0b132e;
            padding: 12px;
        }

        .flash {
            border: 1px solid #2e7a5a;
            border-radius: 14px;
            background: #103122;
            color: #c9f8de;
            padding: 12px;
            font-weight: 700;
            margin-bottom: 12px;
        }

        .flash.error {
            border-color: #a13b3b;
            background: #3a1717;
            color: #ffd8d8;
        }

        .fields {
            display: grid;
            gap: 10px;
        }

        .field {
            display: grid;
            gap: 5px;
        }

        .field label {
            color: #ced8ff;
            font-weight: 700;
        }

        .field input,
        .field select {
            width: 100%;
            border: 1px solid #3a4f94;
            border-radius: 10px;
            background: #101a3a;
            color: #f4f7ff;
            font: inherit;
            font-weight: 700;
            padding: 10px;
            outline: none;
        }

        .field input:focus,
        .field select:focus {
            border-color: #7d6dff;
            box-shadow: 0 0 0 3px #7d6dff2e;
        }

        .field-row {
            display: grid;
            grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
            gap: 10px;
        }

        .checkbox-row {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #d6e0ff;
            font-weight: 700;
        }

        .checkbox-row input {
            width: auto;
        }

        .example-box {
            border: 1px dashed #4960ae;
            border-radius: 10px;
            padding: 10px;
            color: #d6e0ff;
            background: #121f45;
            font-weight: 700;
        }

        .example-values {
            color: var(--accent);
        }

        .save-btn {
            border: 0;
            border-radius: 12px;
            background: linear-gradient(90deg, #6d5efc, #4f46e5);
            color: #fff;
            font: inherit;
            font-weight: 700;
            padding: 11px 12px;
            cursor: pointer;
        }

        .list-title {
            margin: 0 0 8px;
            font-size: 1.1rem;
            color: #e8edff;
            font-weight: 700;
        }

        .list-scroll {
            max-height: 500px;
            overflow: auto;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            border: 1px solid #30457e;
            border-radius: 10px;
        }

        table {
            width: 100%;
            min-width: 460px;
            border-collapse: collapse;
            font-size: 0.95rem;
        }

        th,
        td {
            text-align: left;
            padding: 8px 10px;
            border-bottom: 1px solid #243769;
        }

        th {
            color: #b8c8ff;
            position: sticky;
            top: 0;
            background: #101d42;
            z-index: 1;
        }

        td strong {
            color: #f4f7ff;
        }

        .empty {
            margin: 0;
            color: var(--muted);
        }

        @media (max-width: 1060px) {
            .topbar {
                flex-direction: column;
                align-items: flex-start;
            }

            .topbar-badge {
                width: 100%;
                white-space: normal;
            }

            .settings-layout {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 760px) {
            .layout {
                grid-template-columns: 1fr;
                gap: 12px;
                padding: 12px;
            }

            .brand {
                text-align: center;
            }

            .nav-item.sub {
                margin-left: 8px;
            }

            .field-row {
                grid-template-columns: 1fr;
            }

            .settings-section {
                padding: 12px;
            }

            .settings-form,
            .settings-list {
                padding: 10px;
            }
        }

        @media (max-width: 480px) {
            .layout {
                padding: 10px;
                gap: 10px;
            }

            .sidebar {
                padding: 14px 10px;
                border-radius: 16px;
            }

            .nav-item {
                padding: 9px 10px;
                font-size: 0.95rem;
            }

            .nav-icon {
                width: 28px;
                height: 28px;
            }

            .topbar {
                padding: 14px;
                border-radius: 16px;
            }

            .content {
                padding: 0;
            }

            table {
                min-width: 420px;
            }
        }
    </style>
</head>
<body data-old-state="{{ old('state') }}" data-old-city="{{ old('city') }}">
    <main class="layout">
        <aside class="sidebar">
            @php($showMercadoPagoSubmenu = request()->routeIs('admin.mercadopago.*'))
            <div class="brand">
                SURVIVE
                <small>Admin Panel</small>
            </div>
            <div class="status-chip">Sistema online</div>

            <nav class="nav">
                <a class="nav-item" href="{{ route('admin.dashboard') }}">
                    <span class="nav-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M4 13h7V4H4v9Zm9 7h7v-9h-7v9ZM4 20h7v-5H4v5Zm9-11h7V4h-7v5Z" fill="currentColor"/></svg>
                    </span>
                    Dashboard
                </a>
                <a class="nav-item" href="{{ route('game.index') }}">
                    <span class="nav-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M7 7h10v10H7V7Zm-4 8V9a2 2 0 0 1 2-2h2v2H5v6h2v2H5a2 2 0 0 1-2-2Zm16 2v-2h2V9h-2V7h2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-2Z" fill="currentColor"/></svg>
                    </span>
                    Ver jogo
                </a>
                <a class="nav-item" href="#">
                    <span class="nav-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M16 11a4 4 0 1 0-4-4 4 4 0 0 0 4 4ZM8 13a4 4 0 1 0-4-4 4 4 0 0 0 4 4Zm8 2c-3.33 0-10 1.67-10 5v2h20v-2c0-3.33-6.67-5-10-5ZM8 15c-.49 0-1.01.03-1.55.08C4.94 15.28 2 16.04 2 18.5V22h4v-2c0-1.6.83-2.94 2.13-3.95A11.87 11.87 0 0 0 8 15Z" fill="currentColor"/></svg>
                    </span>
                    Jogadores
                </a>
                <a class="nav-item" href="#">
                    <span class="nav-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M19 3h-1V1h-2v2H8V1H6v2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2Zm0 16H5V9h14v10Zm-7-8a3 3 0 1 0 3 3 3 3 0 0 0-3-3Z" fill="currentColor"/></svg>
                    </span>
                    Rodadas
                </a>
                <a class="nav-item active" href="{{ route('admin.city-payout.index') }}">
                    <span class="nav-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 2 3 6v6c0 5 3.84 9.74 9 11 5.16-1.26 9-6 9-11V6l-9-4Zm1 14h-2v-2h2v2Zm0-4h-2V7h2v5Z" fill="currentColor"/></svg>
                    </span>
                    Configuração
                </a>
                <a class="nav-item sub active" href="{{ route('admin.city-payout.index') }}">
                    Configuração por cidade
                </a>
                <a class="nav-item" href="{{ route('admin.mercadopago.index') }}">
                    <span class="nav-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 2 3 6v6c0 5 3.84 9.74 9 11 5.16-1.26 9-6 9-11V6l-9-4Zm1 14h-2v-2h2v2Zm0-4h-2V7h2v5Z" fill="currentColor"/></svg>
                    </span>
                    Mercado Pago
                </a>
                @if ($showMercadoPagoSubmenu)
                    <a class="nav-item sub" href="{{ route('admin.mercadopago.index') }}">
                        Configurações PIX
                    </a>
                @endif
                <a class="nav-item" href="#">
                    <span class="nav-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M3 3h2v18H3V3Zm16 0h2v18h-2V3ZM7 13h4v8H7v-8Zm6-10h4v18h-4V3Z" fill="currentColor"/></svg>
                    </span>
                    Relatórios
                </a>
            </nav>

            <form method="post" action="{{ route('admin.logout') }}">
                @csrf
                <div class="logout">
                    <button type="submit">Sair do painel</button>
                </div>
            </form>
        </aside>

        <section class="content">
            <header class="topbar">
                <div class="topbar-main">
                    <h1>Prêmios por Cidade</h1>
                    <p class="subtitle">Defina a divisão por localidade e aplique nas rodadas abertas</p>
                    <div class="meta">Administrador conectado: {{ $adminEmail }}</div>
                </div>
                <div class="topbar-badge">Configuração operacional</div>
            </header>

            @if (session('status'))
                <div class="flash">{{ session('status') }}</div>
            @endif

            @if ($errors->any())
                <div class="flash error">{{ $errors->first() }}</div>
            @endif

            <section class="settings-section">
                <h2 class="settings-title">Configuração de prêmio por cidade</h2>
                <p class="settings-subtitle">
                    Defina o percentual do prêmio por cidade. O restante fica para a casa.
                </p>

                <div class="settings-layout">
                    <form method="post" action="{{ route('admin.city-payout.save') }}" class="settings-form">
                        @csrf
                        <div class="fields">
                            <div class="field-row">
                                <div class="field">
                                    <label for="state">Estado</label>
                                    <select id="state" name="state" required>
                                        <option value="">Selecione o estado</option>
                                        @foreach (array_keys($statesCities) as $uf)
                                            <option value="{{ $uf }}" {{ old('state') === $uf ? 'selected' : '' }}>{{ $uf }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="field">
                                    <label for="prize_percentage">% do prêmio</label>
                                    <input
                                        id="prize_percentage"
                                        name="prize_percentage"
                                        type="number"
                                        min="0"
                                        max="100"
                                        step="0.01"
                                        value="{{ old('prize_percentage', number_format($defaultPrizePercentage, 2, '.', '')) }}"
                                        required
                                    >
                                </div>
                            </div>

                            <div class="field">
                                <label for="citySearch">Buscar cidade</label>
                                <input id="citySearch" type="text" placeholder="Digite para filtrar cidades" autocomplete="off">
                            </div>

                            <div class="field">
                                <label for="city">Cidade</label>
                                <select id="city" name="city" required>
                                    <option value="">Selecione a cidade</option>
                                </select>
                            </div>

                            <div class="field">
                                <label for="house_percentage">% da casa</label>
                                <input id="house_percentage" type="text" readonly>
                            </div>

                            <label class="checkbox-row" for="apply_to_open_rounds">
                                <input
                                    id="apply_to_open_rounds"
                                    name="apply_to_open_rounds"
                                    type="checkbox"
                                    value="1"
                                    {{ old('apply_to_open_rounds', '1') ? 'checked' : '' }}
                                >
                                Aplicar agora nas rodadas abertas dessa cidade
                            </label>

                            <div class="example-box">
                                Exemplo com 100 jogadores a R$ 5,00 (R$ 500,00 total):
                                prêmio <span class="example-values" id="examplePrize">R$ 0,00</span>
                                e casa <span class="example-values" id="exampleHouse">R$ 0,00</span>.
                            </div>

                            <button class="save-btn" type="submit">Salvar configuração</button>
                        </div>
                    </form>

                    <div class="settings-list">
                        <p class="list-title">Cidades configuradas</p>

                        @if ($cityPayoutSettings->isEmpty())
                            <p class="empty">Nenhuma cidade com percentual customizado ainda.</p>
                        @else
                            <div class="list-scroll">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>UF</th>
                                            <th>Cidade</th>
                                            <th>Prêmio</th>
                                            <th>Casa</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach ($cityPayoutSettings as $setting)
                                            @php
                                                $prizePct = (float) $setting->prize_percentage;
                                                $housePct = max(0, 100 - $prizePct);
                                            @endphp
                                            <tr>
                                                <td><strong>{{ $setting->state }}</strong></td>
                                                <td>{{ $setting->city }}</td>
                                                <td>{{ number_format($prizePct, 2, ',', '.') }}%</td>
                                                <td>{{ number_format($housePct, 2, ',', '.') }}%</td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        @endif
                    </div>
                </div>
            </section>
        </section>
    </main>

    <script id="statesCitiesData" type="application/json">{!! json_encode($statesCities, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) !!}</script>

    <script>
        (() => {
            const statesCities = JSON.parse(document.getElementById('statesCitiesData').textContent);
            const stateSelect = document.getElementById('state');
            const citySearchInput = document.getElementById('citySearch');
            const citySelect = document.getElementById('city');
            const prizePercentageInput = document.getElementById('prize_percentage');
            const housePercentageInput = document.getElementById('house_percentage');
            const examplePrize = document.getElementById('examplePrize');
            const exampleHouse = document.getElementById('exampleHouse');
            const oldState = document.body.dataset.oldState;
            const oldCity = document.body.dataset.oldCity;

            let currentCities = [];

            const normalizeText = (value) => (
                value
                    .normalize('NFD')
                    .replace(/[\u0300-\u036f]/g, '')
                    .toLowerCase()
                    .trim()
            );

            const formatBrl = (value) => {
                return new Intl.NumberFormat('pt-BR', {
                    style: 'currency',
                    currency: 'BRL',
                    minimumFractionDigits: 2,
                }).format(value);
            };

            const renderCityOptions = (cities, selectedCity = '') => {
                citySelect.innerHTML = '';

                const placeholder = document.createElement('option');
                placeholder.value = '';
                placeholder.textContent = cities.length > 0
                    ? 'Selecione a cidade'
                    : 'Nenhuma cidade encontrada';
                citySelect.appendChild(placeholder);

                let selectedExists = false;

                cities.forEach((city) => {
                    const option = document.createElement('option');
                    option.value = city;
                    option.textContent = city;

                    if (city === selectedCity) {
                        option.selected = true;
                        selectedExists = true;
                    }

                    citySelect.appendChild(option);
                });

                if (!selectedExists) {
                    citySelect.value = '';
                }
            };

            const populateCities = (stateValue, selectedCity = '') => {
                citySearchInput.value = '';

                if (!stateValue || !statesCities[stateValue]) {
                    currentCities = [];
                    renderCityOptions([]);
                    citySelect.disabled = true;
                    citySearchInput.disabled = true;

                    return;
                }

                currentCities = statesCities[stateValue];
                renderCityOptions(currentCities, selectedCity);
                citySelect.disabled = false;
                citySearchInput.disabled = false;
            };

            const filterCities = () => {
                const term = normalizeText(citySearchInput.value);
                const selectedBeforeFilter = citySelect.value;

                const filteredCities = term === ''
                    ? currentCities
                    : currentCities.filter((city) => normalizeText(city).includes(term));

                const keepSelected = filteredCities.includes(selectedBeforeFilter)
                    ? selectedBeforeFilter
                    : '';

                renderCityOptions(filteredCities, keepSelected);
            };

            const updateExample = () => {
                const prizePctRaw = parseFloat(prizePercentageInput.value);
                const prizePct = Number.isNaN(prizePctRaw)
                    ? 0
                    : Math.max(0, Math.min(100, prizePctRaw));

                const housePct = Math.max(0, 100 - prizePct);
                const gross = 500;
                const prizeAmount = gross * (prizePct / 100);
                const houseAmount = gross - prizeAmount;

                housePercentageInput.value = housePct.toFixed(2).replace('.', ',') + '%';
                examplePrize.textContent = formatBrl(prizeAmount);
                exampleHouse.textContent = formatBrl(houseAmount);
            };

            stateSelect.addEventListener('change', () => {
                populateCities(stateSelect.value, '');
            });

            citySearchInput.addEventListener('input', filterCities);
            prizePercentageInput.addEventListener('input', updateExample);

            if (oldState) {
                populateCities(oldState, oldCity || '');
            } else {
                citySelect.disabled = true;
                citySearchInput.disabled = true;
            }

            updateExample();
        })();
    </script>
</body>
</html>
