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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Administrativo | IG Radio</title>
    <link rel="stylesheet" href="/static/css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800;900&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --admin-sidebar-w: 260px;
        }

        body {
            background: #09090b;
            color: var(--text-main);
            display: flex;
            min-height: 100vh;
        }

        /* ── Sidebar ───────────────────────────────────── */
        .sidebar {
            width: var(--admin-sidebar-w);
            background: #111114;
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            position: fixed;
            height: 100vh;
            left: 0;
            top: 0;
            z-index: 100;
        }

        .sidebar-header {
            padding: 30px;
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .sidebar-logo {
            height: 40px;
        }

        .sidebar-nav {
            padding: 20px;
            flex: 1;
        }

        .side-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 15px;
            color: var(--text-muted);
            text-decoration: none;
            border-radius: 10px;
            margin-bottom: 5px;
            font-weight: 600;
            transition: all 0.2s;
        }

        .side-link:hover, .side-link.active {
            background: rgba(255, 0, 127, 0.1);
            color: var(--primary);
        }

        .sidebar-footer {
            padding: 20px;
            border-top: 1px solid var(--border);
        }

        /* ── Main Content ───────────────────────────────── */
        .main-content {
            margin-left: var(--admin-sidebar-w);
            flex: 1;
            padding: 40px;
            transition: all 0.3s;
            width: 100%;
        }

        .dashboard-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 40px;
        }

        /* ── Mobile Elements ─────────────────────────────── */
        .mobile-admin-header {
            display: none;
            background: #111114;
            padding: 0 20px;
            height: 60px;
            border-bottom: 1px solid var(--border);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
            justify-content: space-between;
            align-items: center;
            backdrop-filter: blur(10px);
        }

        .menu-toggle {
            background: none;
            border: none;
            color: #fff;
            font-size: 1.5rem;
            cursor: pointer;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* ── Responsive ─────────────────────────────────── */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                z-index: 2000;
                box-shadow: 20px 0 50px rgba(0,0,0,0.5);
            }
            .sidebar.active {
                transform: translateX(0);
            }
            .main-content {
                margin-left: 0;
                padding: 80px 15px 30px; /* Top padding to clear fixed header */
            }
            .mobile-admin-header {
                display: flex;
            }
            .dashboard-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
                margin-bottom: 30px;
            }
            #live-indicator-admin { 
                width: 100%; 
                justify-content: center;
                font-size: 0.8rem;
                padding: 8px 15px;
            }
            .admin-section-grid { 
                grid-template-columns: 1fr !important; 
                gap: 20px;
            }
            .panel-card { padding: 20px; }
            .chart-container { height: 250px; }
        }

        @media (max-width: 480px) {
            .stats-grid { grid-template-columns: 1fr; }
            .stat-card { padding: 15px; gap: 15px; }
            .stat-icon { width: 40px; height: 40px; font-size: 1.2rem; }
            .value { font-size: 1.3rem; }
            h1#tab-title { font-size: 1.6rem !important; }
            #tab-subtitle { font-size: 0.85rem; }
        }

        /* ── Stats Grid ─────────────────────────────────── */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }

        .stat-card {
            background: var(--bg-card);
            border: 1px solid var(--border);
            padding: 25px;
            border-radius: 20px;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .stat-icon {
            width: 50px;
            height: 50px;
            background: rgba(255, 0, 127, 0.1);
            color: var(--primary);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }

        .stat-info h4 {
            font-size: 0.8rem;
            text-transform: uppercase;
            color: var(--text-muted);
            margin-bottom: 5px;
            letter-spacing: 1px;
        }

        .stat-info .value {
            font-size: 1.5rem;
            font-weight: 900;
            color: #fff;
        }

        /* ── Section Styles ─────────────────────────────── */
        .admin-section-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 30px;
        }

        .panel-card {
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
        }

        .panel-card h3 {
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.2rem;
            color: #fff;
        }

        /* ── Chart ─────────────────────────────────────── */
        .chart-container {
            height: 300px;
            width: 100%;
            margin-top: 20px;
        }

        /* ── Lists ─────────────────────────────────────── */
        .admin-list {
            list-style: none;
        }
        
        /* ── Custom Modal ─────────────────────────────── */
        .modal-overlay {
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.8);
            backdrop-filter: blur(8px);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s;
        }

        .modal-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .modal-card {
            background: #1a1a1e;
            border: 1px solid var(--border);
            width: 100%;
            max-width: 500px;
            border-radius: 24px;
            padding: 40px;
            box-shadow: 0 30px 60px rgba(0,0,0,0.5);
            transform: translateY(20px);
            transition: all 0.3s;
        }

        .modal-overlay.active .modal-card {
            transform: translateY(0);
        }

        .modal-card h2 {
            margin-bottom: 25px;
            font-weight: 900;
            color: #fff;
        }

        .modal-form label {
            display: block;
            font-size: 0.8rem;
            color: var(--text-muted);
            margin-bottom: 8px;
            font-weight: 700;
            text-transform: uppercase;
        }

        .modal-form input, .modal-form textarea {
            width: 100%;
            background: rgba(0,0,0,0.3);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 12px 15px;
            color: #fff;
            margin-bottom: 20px;
            font-family: inherit;
        }

        .modal-form input:focus { border-color: var(--primary); outline: none; }

        .admin-list li {
            padding: 15px 0;
            border-bottom: 1px solid var(--border);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .admin-list li:last-child { border-bottom: none; }

        .song-meta { display: flex; flex-direction: column; }
        .song-meta .artist { font-size: 0.8rem; color: var(--text-muted); }

        /* ── Responsive ────────────────────────────────── */
        @media (max-width: 1200px) {
            .admin-section-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>

<body>
    <div class="mobile-admin-header">
        <div style="display: flex; align-items: center; gap: 10px;">
            <img src="/static/images/logo.png" alt="Logo" style="height: 30px;">
            <span style="font-weight: 900; color: #fff; font-size: 0.9rem;">ADMIN</span>
        </div>
        <button class="menu-toggle" onclick="toggleSidebar()">☰</button>
    </div>

    <!-- ── Sidebar ───────────────────────────────────── -->
    <aside class="sidebar" id="adminSidebar">
        <div class="sidebar-header">
            <img src="/static/images/logo.png" alt="Logo" class="sidebar-logo">
            <span style="font-weight: 900; letter-spacing: -1px; color: #fff;">ADMIN</span>
        </div>
        <nav class="sidebar-nav">
            <a href="#" onclick="showTab('tab-dashboard')" class="side-link active" id="link-tab-dashboard">📊 Dashboard</a>
            <a href="#" onclick="showTab('tab-library')" class="side-link" id="link-tab-library">🎵 Biblioteca</a>
            <a href="#" onclick="showTab('tab-blog')" class="side-link" id="link-tab-blog">📝 Blog</a>
            <a href="#" onclick="showTab('tab-polls')" class="side-link" id="link-tab-polls">🗳️ Votações</a>
            <a href="/blog" class="side-link">🌐 Ver Blog</a>
            <a href="/" class="side-link">📡 Ver Site</a>
        </nav>
        <div class="sidebar-footer">
            <a href="/admin/logout" class="side-link" style="color: #ff3b3b; background: rgba(255, 59, 59, 0.05);">
                🚪 Terminar Sessão
            </a>
        </div>
    </aside>

    <!-- ── Main Content ───────────────────────────────── -->
    <main class="main-content">
        <div class="dashboard-header">
            <div>
                <h1 style="font-weight: 900; font-size: 2rem; color: #fff;" id="tab-title">Olá, Administrador</h1>
                <p style="color: var(--text-muted);" id="tab-subtitle">Aqui está o resumo da tua rádio hoje.</p>
            </div>
            <div id="live-indicator-admin" style="background: rgba(0, 255, 127, 0.1); color: #00ff7f; padding: 10px 20px; border-radius: 100px; font-weight: 800; border: 1px solid rgba(0, 255, 127, 0.2);">
                📡 <span id="listener-count">0</span> Ouvintes Agora
            </div>
        </div>

        <!-- ── TAB: DASHBOARD ────────────────────────── -->
        <div id="tab-dashboard" class="admin-tab-content">
            <!-- Quick Stats -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">🎵</div>
                    <div class="stat-info">
                        <h4>Músicas</h4>
                        <div class="value">{{ songs|length }}</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">📄</div>
                    <div class="stat-info">
                        <h4>Artigos</h4>
                        <div class="value">{{ blog_posts|length }}</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">📩</div>
                    <div class="stat-info">
                        <h4>Pedidos</h4>
                        <div class="value">{{ recommendations|length }}</div>
                    </div>
                </div>
            </div>

            <!-- Audience Chart -->
            <section class="panel-card">
                <h3>📈 Audiência em Direto (24h)</h3>
                <div class="chart-container">
                    <canvas id="audienceChart"></canvas>
                </div>
                <div style="margin-top: 25px; display: flex; justify-content: space-between; font-size: 0.85rem; color: var(--text-muted); border-top: 1px solid var(--border); padding-top: 15px;">
                    <span>Pico Registado: <strong id="max-listeners-24h" style="color: var(--primary);">0</strong></span>
                    <span>Dados atualizados em tempo real</span>
                </div>
            </section>

            <!-- Pending Recommendations (Preview on Dashboard) -->
            <section class="panel-card">
                <h3>📩 Últimas Recomendações</h3>
                <ul class="admin-list">
                    {% for rec in recommendations[:5] %}
                    <li>
                        <div class="song-meta" style="flex:1;">
                            <span style="font-weight: 700; font-size: 0.9rem;">{{ rec.title }}</span>
                            <span class="artist">{{ rec.artist }}</span>
                        </div>
                        <div style="display: flex; gap: 5px;">
                            <form action="/admin/recommend/{{ rec.id }}/accept" method="post">
                                <button class="btn small success" style="padding: 4px;">✓</button>
                            </form>
                            <button data-rec-id="{{ rec.id }}" class="btn small danger reject-btn" style="padding: 4px;">✗</button>
                        </div>
                    </li>
                    {% else %}
                    <p style="text-align: center; color: var(--text-muted); padding: 20px; font-size: 0.9rem;">Nenhum pedido de música pendente.</p>
                    {% endfor %}
                </ul>
            </section>
        </div>

        <!-- ── TAB: LIBRARY ──────────────────────────── -->
        <div id="tab-library" class="admin-tab-content hidden">
            <div class="admin-section-grid">
                <div>
                    <section class="panel-card">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
                            <h3 style="margin:0;">📚 Biblioteca Musical</h3>
                            <details style="position: relative;">
                                <summary class="btn small" style="list-style: none; cursor:pointer;">+ Upload</summary>
                                <div class="card" style="position: absolute; right: 0; top: 40px; width: 300px; z-index: 50; box-shadow: var(--shadow);">
                                    <form action="/admin/upload" method="post" enctype="multipart/form-data">
                                        <input type="file" name="file" accept=".mp3,.wav" required style="margin-bottom: 10px; font-size: 0.8rem;">
                                        <input type="text" name="title" placeholder="Título Opcional" style="margin-bottom: 10px; padding: 8px;">
                                        <button type="submit" class="btn small" style="width: 100%;">Começar Upload</button>
                                    </form>
                                </div>
                            </details>
                        </div>
                        <div style="max-height: 600px; overflow-y: auto; padding-right: 10px;">
                            <ul class="admin-list">
                                {% for song in songs %}
                                <li>
                                    <div class="song-meta">
                                        <span style="font-weight: 700;">{{ song.title }}</span>
                                        <span class="artist">{{ song.artist }}</span>
                                    </div>
                                    <div style="display: flex; gap: 8px;">
                                        <form action="/admin/queue/{{ song.id }}" method="post">
                                            <button class="btn small success" style="padding: 4px 10px;">Fila</button>
                                        </form>
                                        <form action="/admin/delete_song/{{ song.id }}" method="post" onsubmit="return confirm('Apagar música?')">
                                            <button class="btn small danger" style="padding: 4px 10px;">🗑️</button>
                                        </form>
                                    </div>
                                </li>
                                {% endfor %}
                            </ul>
                        </div>
                    </section>
                </div>
                <div>
                    <section class="panel-card">
                        <h3>⏭️ Próximas na Fila</h3>
                        <ul class="admin-list">
                            {% for q in queue %}
                            <li>
                                <div class="song-meta">
                                    <span style="font-weight: 700;">{{ q.song.title }}</span>
                                    <span class="artist">{{ q.song.artist }}</span>
                                </div>
                                <span style="font-size: 0.8rem; background: rgba(255,255,255,0.05); padding: 2px 8px; border-radius: 4px;">#{{ q.position }}</span>
                            </li>
                            {% else %}
                            <p style="text-align: center; color: var(--text-muted); padding: 20px;">Nenhuma música na fila.</p>
                            {% endfor %}
                        </ul>
                    </section>
                </div>
            </div>
        </div>

        <!-- ── TAB: BLOG ─────────────────────────────── -->
        <div id="tab-blog" class="admin-tab-content hidden">
            <section class="panel-card">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
                    <h3 style="margin:0;">📝 Gestão de Blog</h3>
                    <button onclick="openCreateModal()" class="btn small">+ Novo Artigo</button>
                </div>
                <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;">
                    {% for post in blog_posts %}
                    <div class="card" style="padding: 20px;">
                        <h4 style="margin-bottom: 10px; color: #fff;">{{ post.title }}</h4>
                        <p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 20px;">Publicado em {{ post.published_at.strftime('%d/%m/%Y') }}</p>
                        <div style="display: flex; gap: 10px;">
                            <button onclick="editPost({{ post.id }}, '{{ post.title|replace("'", "\\'") }}')" class="btn small secondary" style="flex:1;">Editar</button>
                            <form action="/admin/blog/delete/{{ post.id }}" method="post" onsubmit="return confirm('Apagar artigo?')" style="flex:0;">
                                <button class="btn small danger">🗑️</button>
                            </form>
                        </div>
                    </div>
                    {% else %}
                    <div style="grid-column: 1/-1; text-align: center; padding: 40px; color: var(--text-muted);">
                        Nenhum artigo publicado no blog de momento.
                    </div>
                    {% endfor %}
                </div>
            </section>
        </div>

        <!-- ── TAB: POLLS ────────────────────────────── -->
        <div id="tab-polls" class="admin-tab-content hidden">
            <section class="panel-card">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
                    <h3 style="margin:0;">🗳️ Mural de Votação</h3>
                    <details style="position: relative;">
                        <summary class="btn small" style="list-style: none; cursor:pointer;">+ Nova Opção</summary>
                        <div class="card" style="position: absolute; right: 0; top: 40px; width: 300px; z-index: 50; box-shadow: var(--shadow);">
                            <form action="/admin/poll/add" method="post">
                                <input type="text" name="title" placeholder="Título da Música" required style="margin-bottom: 10px;">
                                <input type="text" name="artist" placeholder="Artista" required style="margin-bottom: 15px;">
                                <button type="submit" class="btn small" style="width: 100%;">Adicionar à Votação</button>
                            </form>
                        </div>
                    </details>
                </div>
                
                <ul class="admin-list">
                    {% for p in poll_songs %}
                    <li>
                        <div class="song-meta">
                            <span style="font-weight: 700;">{{ p.title }}</span>
                            <span class="artist">{{ p.artist }}</span>
                        </div>
                        <div style="display: flex; align-items: center; gap: 20px;">
                            <span class="stats-badge">{{ p.votes }} votos</span>
                            <form action="/admin/poll/delete/{{ p.id }}" method="post" onsubmit="return confirm('Remover esta opção?')">
                                <button class="btn small danger">🗑️</button>
                            </form>
                        </div>
                    </li>
                    {% else %}
                    <p style="text-align: center; color: var(--text-muted); padding: 20px;">Nenhuma música em votação no momento.</p>
                    {% endfor %}
                </ul>
            </section>
        </div>
    </main>

    <!-- Edit Modal -->
    <div id="editModal" class="modal-overlay">
        <div class="modal-card">
            <h2>Editar Artigo</h2>
            <form id="editForm" method="POST" enctype="multipart/form-data" class="modal-form">
                <div class="input-group">
                    <label>Título</label>
                    <input type="text" name="title" id="edit-title" required>
                </div>
                <div class="input-group">
                    <label>Conteúdo</label>
                    <textarea name="description" id="edit-desc" rows="6" required></textarea>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div class="input-group">
                        <label>Etiqueta Link</label>
                        <input type="text" name="link_label" id="edit-link-label">
                    </div>
                    <div class="input-group">
                        <label>URL Link</label>
                        <input type="url" name="link_url" id="edit-link-url">
                    </div>
                </div>
                <div class="input-group">
                    <label>Novo Banner (Opcional)</label>
                    <input type="file" name="banner" accept="image/*">
                </div>
                <div style="display: flex; gap: 15px; margin-top: 10px;">
                    <button type="submit" class="btn" style="flex:1;">Guardar Alterações</button>
                    <button type="button" onclick="closeModal()" class="btn secondary" style="flex:1;">Cancelar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Create Blog Modal -->
    <div id="createModal" class="modal-overlay">
        <div class="modal-card">
            <h2>Novo Artigo</h2>
            <form action="/admin/blog/create" method="POST" enctype="multipart/form-data" class="modal-form">
                <div class="input-group">
                    <label>Título do Artigo</label>
                    <input type="text" name="title" placeholder="Ex: Grande Concerto de Verão" required>
                </div>
                <div class="input-group">
                    <label>Conteúdo</label>
                    <textarea name="description" placeholder="Escreve aqui a notícia..." rows="6" required></textarea>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div class="input-group">
                        <label>Etiqueta Link (Opcional)</label>
                        <input type="text" name="link_label" placeholder="Ex: Bilhetes">
                    </div>
                    <div class="input-group">
                        <label>URL do Link</label>
                        <input type="url" name="link_url" placeholder="https://...">
                    </div>
                </div>
                <div class="input-group">
                    <label>Imagem de Capa</label>
                    <input type="file" name="banner" accept="image/*">
                </div>
                <div style="display: flex; gap: 15px; margin-top: 10px;">
                    <button type="submit" class="btn" style="flex:1;">Publicar Artigo</button>
                    <button type="button" onclick="closeCreateModal()" class="btn secondary" style="flex:1;">Cancelar</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const socket = io();
        let audienceChart = null;

        socket.on('admin_stats', (data) => {
            document.getElementById('listener-count').textContent = data.listener_count;
        });

        async function initChart() {
            const ctx = document.getElementById('audienceChart').getContext('2d');
            
            // Create gradient
            const gradient = ctx.createLinearGradient(0, 0, 0, 300);
            gradient.addColorStop(0, 'rgba(255, 0, 127, 0.4)');
            gradient.addColorStop(1, 'rgba(255, 0, 127, 0)');

            audienceChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Ouvintes',
                        data: [],
                        borderColor: '#ff007f',
                        backgroundColor: gradient,
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointRadius: 4,
                        pointBackgroundColor: '#ff007f',
                        pointBorderColor: '#fff',
                        pointHoverRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: '#1a1a1e',
                            titleColor: '#fff',
                            bodyColor: '#e0e0e0',
                            borderColor: '#2a2a2e',
                            borderWidth: 1,
                            padding: 12,
                            displayColors: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: { color: 'rgba(255, 255, 255, 0.05)' },
                            ticks: { color: '#888', stepSize: 1 }
                        },
                        x: {
                            grid: { display: false },
                            ticks: { color: '#888' }
                        }
                    }
                }
            });
            updateChart();
        }

        async function updateChart() {
            try {
                const res = await fetch('/api/stats/listeners');
                const data = await res.json();
                if(data.success) {
                    const stats = data.stats;
                    const labels = stats.map(s => s.hour.split(' ')[1].split(':')[0] + 'h');
                    const counts = stats.map(s => s.count);
                    
                    document.getElementById('max-listeners-24h').textContent = Math.max(...counts, 0);
                    
                    if(audienceChart) {
                        audienceChart.data.labels = labels;
                        audienceChart.data.datasets[0].data = counts;
                        audienceChart.update();
                    }
                }
            } catch(e) {}
        }

        initChart();
        setInterval(updateChart, 60000);

        document.querySelectorAll('.reject-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const id = btn.dataset.recId;
                const reason = prompt("Razão da rejeição:");
                if(reason) {
                    const f = document.createElement('form');
                    f.method = 'POST';
                    f.action = `/admin/recommend/${id}/reject`;
                    const i = document.createElement('input');
                    i.type = 'hidden'; i.name = 'reason'; i.value = reason;
                    f.appendChild(i);
                    document.body.appendChild(f);
                    f.submit();
                }
            });
        });

        function editPost(id, title) {
            const modal = document.getElementById('editModal');
            const form = document.getElementById('editForm');
            
            // Set action URL
            form.action = `/admin/blog/edit/${id}`;
            
            // Pre-fill current title
            document.getElementById('edit-title').value = title;
            
            // Note: We can't easily pre-fill description/links without another API call or storing them in data attributes
            // For now, let's just show the modal.
            
            modal.classList.add('active');
        }

        function closeModal() {
            document.getElementById('editModal').classList.remove('active');
        }

        function openCreateModal() {
            document.getElementById('createModal').classList.add('active');
        }

        function closeCreateModal() {
            document.getElementById('createModal').classList.remove('active');
        }

        // ── Tabs System ──────────────────────────────────
        function showTab(tabId) {
            // Hide all tabs
            document.querySelectorAll('.admin-tab-content').forEach(tab => {
                tab.classList.add('hidden');
            });
            // Show target tab
            document.getElementById(tabId).classList.remove('hidden');
            
            // Update sidebar links
            document.querySelectorAll('.side-link').forEach(link => {
                link.classList.remove('active');
            });
            document.getElementById('link-' + tabId).classList.add('active');
            
            // Update header title
            const titleEl = document.getElementById('tab-title');
            const subEl = document.getElementById('tab-subtitle');
            
            if (tabId === 'tab-dashboard') {
                titleEl.textContent = "Olá, Administrador";
                subEl.textContent = "Aqui está o resumo da tua rádio hoje.";
            } else if (tabId === 'tab-library') {
                titleEl.textContent = "Biblioteca Musical";
                subEl.textContent = "Gere as tuas músicas e a fila de reprodução.";
            } else if (tabId === 'tab-blog') {
                titleEl.textContent = "Gestão de Conteúdo";
                subEl.textContent = "Publica e edita artigos no blog da rádio.";
            } else if (tabId === 'tab-polls') {
                titleEl.textContent = "Mural de Votações";
                subEl.textContent = "Controla as músicas que os ouvintes podem votar.";
            }

            // Close sidebar on mobile after selecting a tab
            if (window.innerWidth <= 1024) {
                toggleSidebar();
            }
        }

        function toggleSidebar() {
            document.getElementById('adminSidebar').classList.toggle('active');
        }

        // Close modals when clicking outside
        document.getElementById('editModal').addEventListener('click', (e) => {
            if(e.target === document.getElementById('editModal')) closeModal();
        });
        document.getElementById('createModal').addEventListener('click', (e) => {
            if(e.target === document.getElementById('createModal')) closeCreateModal();
        });
    </script>
</body>

</html>
