<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minha Área - Alemão Conveniência</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap"
        rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #f59e0b;
            --primary-dark: #d97706;
            --bg-dark: #0f172a;
            --bg-card: #1e293b;
            --bg-section: #131c2e;
            --text-light: #f1f5f9;
            --text-muted: #94a3b8;
            --glass-border: rgba(255, 255, 255, 0.08);
            --success: #10b981;
            --gradient-primary: linear-gradient(135deg, #f59e0b, #d97706);
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg-dark);
            color: var(--text-light);
            min-height: 100vh;
        }

        .navbar-custom {
            background: rgba(15, 23, 42, 0.9);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid var(--glass-border);
            padding: 16px 0;
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 100;
        }

        .brand-icon {
            width: 36px;
            height: 36px;
            background: var(--gradient-primary);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
        }

        .main-content {
            padding-top: 100px;
            padding-bottom: 60px;
        }

        .welcome-section {
            margin-bottom: 40px;
        }

        .welcome-section h1 {
            font-weight: 800;
            font-size: 2rem;
            margin-bottom: 8px;
        }

        .ticket-card {
            background: var(--bg-card);
            border: 1px solid var(--glass-border);
            border-radius: 20px;
            padding: 24px;
            margin-bottom: 24px;
            transition: transform 0.3s;
        }

        .ticket-card:hover {
            transform: translateY(-5px);
        }

        .ticket-number {
            font-family: 'monospace';
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary);
            letter-spacing: 2px;
        }

        .badge-active {
            background: rgba(16, 185, 129, 0.1);
            color: var(--success);
            border: 1px solid rgba(16, 185, 129, 0.2);
            padding: 4px 12px;
            border-radius: 99px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .logout-btn {
            color: var(--text-muted);
            text-decoration: none;
            font-weight: 500;
            font-size: 0.9rem;
            transition: color 0.3s;
        }

        .logout-btn:hover {
            color: #ef4444;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: rgba(255, 255, 255, 0.02);
            border-radius: 24px;
            border: 1px dashed var(--glass-border);
        }

        .empty-state i {
            font-size: 48px;
            color: var(--text-muted);
            margin-bottom: 20px;
            display: block;
        }

        .form-check-input:checked {
            background-color: #25d366;
            border-color: #25d366;
        }

        .optin-card {
            background: var(--bg-card);
            border: 1px solid var(--glass-border);
            border-radius: 20px;
            padding: 24px;
        }

        .optin-card .wa-icon {
            width: 40px;
            height: 40px;
            background: rgba(37,211,102,0.12);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: #25d366;
        }
    </style>
</head>

<body>
    <nav class="navbar-custom">
        <div class="container d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center gap-2">
                <div class="brand-icon">
                    <i class="bi bi-person-fill text-white"></i>
                </div>
                <span class="fw-bold fs-5">Minha Área</span>
            </div>
            <a href="/user/logout" class="logout-btn">
                <i class="bi bi-box-arrow-right me-1"></i> Sair
            </a>
        </div>
    </nav>

    <div class="container main-content">
        <div class="welcome-section">
            <h1 id="user-name">Olá, Carregando...</h1>
            <p class="text-muted">Acompanhe seus tickets para o sorteio e promoções ativas.</p>
        </div>

        <div class="row">
            <div class="col-lg-8">
                <h4 class="mb-4">Meus Tickets da Sorte</h4>
                <div id="tickets-container">
                    <div class="text-center p-5">
                        <div class="spinner-border text-warning" role="status"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card bg-card border-0 rounded-4 p-4 mb-4">
                    <h5 class="mb-3">Informações</h5>
                    <p class="small text-muted mb-4">Esta área é exclusiva para clientes cadastrados no WiFi da Alemão
                        Conveniência.</p>
                    <a href="/" class="btn btn-outline-warning rounded-pill w-100">Ver Promoções</a>
                </div>

                <div class="optin-card mb-4">
                    <div class="d-flex align-items-center gap-3 mb-3">
                        <div class="wa-icon"><i class="bi bi-whatsapp"></i></div>
                        <div>
                            <div class="fw-semibold" style="font-size:.95rem">Notificações WhatsApp</div>
                            <div class="text-muted" style="font-size:.78rem">Sorteios, promoções e avisos</div>
                        </div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <span id="optin-label" class="small text-muted">Carregando...</span>
                        <div class="form-check form-switch mb-0">
                            <input class="form-check-input" type="checkbox" id="optin-toggle"
                                style="width:2.5em;height:1.3em;cursor:pointer" disabled
                                onchange="toggleOptin(this.checked)">
                        </div>
                    </div>
                    <div id="optin-feedback" class="small mt-2" style="min-height:1.2em"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        async function loadUserData() {
            try {
                // Fetch real tickets from the API
                const res = await fetch('/api/raffle/my-tickets');
                const tickets = await res.json();

                const container = document.getElementById('tickets-container');

                if (!res.ok) {
                    container.innerHTML = `<div class="alert alert-danger">Erro ao carregar dados. Por favor, faça login novamente.</div>`;
                    return;
                }

                // Update welcome message
                try {
                    const meRes = await fetch('/api/me');
                    if (meRes.ok) {
                        const meData = await meRes.json();
                        document.getElementById('user-name').textContent = `Olá, ${meData.nome}!`;
                    } else {
                        const userName = tickets.length > 0 ? tickets[0].usuario_nome : "Cliente Especial";
                        document.getElementById('user-name').textContent = `Olá, ${userName}!`;
                    }
                } catch (e) {
                    const userName = tickets.length > 0 ? tickets[0].usuario_nome : "Cliente Especial";
                    document.getElementById('user-name').textContent = `Olá, ${userName}!`;
                }

                if (tickets.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state mt-4">
                            <i class="bi bi-gift"></i>
                            <h5>Você ainda não tem tickets</h5>
                            <p class="text-muted small">Visite a loja e use o Wi-Fi para ganhar chances no sorteio!</p>
                            <a href="/" class="btn btn-warning rounded-pill mt-3">Ver Promoções</a>
                        </div>
                    `;
                    return;
                }

                // Render ticket list
                container.innerHTML = tickets.map(ticket => `
                    <div class="ticket-card d-flex justify-content-between align-items-center">
                        <div>
                            <span class="text-muted small d-block mb-1">${ticket.raffle_titulo || 'SORTEIO GERAL'}</span>
                            <div class="ticket-number">#AL-${ticket.numero.toString().padStart(4, '0')}</div>
                        </div>
                        <div class="text-end">
                            <span class="badge-active mb-2 d-inline-block">ATIVO</span>
                            <div class="text-muted small">${new Date(ticket.data_compra).toLocaleDateString('pt-BR')}</div>
                        </div>
                    </div>
                `).join('');

            } catch (err) {
                console.error(err);
                document.getElementById('tickets-container').innerHTML = `<div class="alert alert-danger">Erro de conexão com o servidor.</div>`;
            }
        }

        loadUserData();
        loadOptinStatus();

        async function loadOptinStatus() {
            try {
                const res = await fetch('/api/me');
                if (!res.ok) return;
                const user = await res.json();
                const toggle = document.getElementById('optin-toggle');
                const label  = document.getElementById('optin-label');
                toggle.checked  = user.whatsapp_optin !== false;
                toggle.disabled = false;
                label.textContent = toggle.checked ? 'Ativado' : 'Desativado';
                label.style.color = toggle.checked ? '#25d366' : '';
            } catch (e) {
                document.getElementById('optin-label').textContent = 'Indisponível';
            }
        }

        async function toggleOptin(value) {
            const toggle   = document.getElementById('optin-toggle');
            const label    = document.getElementById('optin-label');
            const feedback = document.getElementById('optin-feedback');
            toggle.disabled = true;
            feedback.textContent = '';
            try {
                const res = await fetch('/api/me/optin', {
                    method: 'PATCH',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ optin: value }),
                });
                if (!res.ok) throw new Error('Falha');
                label.textContent = value ? 'Ativado' : 'Desativado';
                label.style.color = value ? '#25d366' : '#94a3b8';
                feedback.style.color = '#25d366';
                feedback.textContent = value ? '✓ Notificações ativadas' : '✓ Notificações desativadas';
            } catch (e) {
                toggle.checked = !value; // reverte visualmente
                feedback.style.color = '#ef4444';
                feedback.textContent = 'Erro ao salvar. Tente novamente.';
            } finally {
                toggle.disabled = false;
                setTimeout(() => { feedback.textContent = ''; }, 3000);
            }
        }
    </script>
</body>

</html>