<!DOCTYPE html>
<html lang="pt-BR" class="h-full dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#0f0a1e">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>{% block title %}Viral Social Pro{% endblock %}</title>

    <!-- Fonts -->
    <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=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

    <!-- Tailwind + Alpine + Chart.js -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <!-- Lucide Icons -->
    <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>

    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    fontFamily: { sans: ['"Plus Jakarta Sans"', 'system-ui', 'sans-serif'] },
                    colors: {
                        dark: { 950: '#050208', 900: '#0f0a1e', 800: '#170f2e', 700: '#1f1538', 600: '#2a1f4e', 500: '#362a5c' },
                        brand: { 50:'#f0edff', 100:'#e0d9ff', 200:'#c4b5fd', 300:'#a78bfa', 400:'#8b5cf6', 500:'#7c3aed', 600:'#6d28d9', 700:'#5b21b6', 800:'#4c1d95', 900:'#3b0764' },
                        accent: { pink:'#ec4899', orange:'#f97316', green:'#10b981', cyan:'#06b6d4', red:'#ef4444' }
                    }
                }
            }
        }
    </script>

    <style>
        [x-cloak] { display: none !important; }
        * { font-family: 'Plus Jakarta Sans', system-ui, sans-serif; }
        body { background: #0f0a1e; }

        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: rgba(124,58,237,0.3); border-radius: 3px; }
        ::-webkit-scrollbar-thumb:hover { background: rgba(124,58,237,0.5); }

        .glass { background: rgba(23, 15, 46, 0.6); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid rgba(124, 58, 237, 0.1); }
        .glass-light { background: rgba(31, 21, 56, 0.4); backdrop-filter: blur(12px); border: 1px solid rgba(124, 58, 237, 0.08); }
        .glass-card { background: rgba(31, 21, 56, 0.5); backdrop-filter: blur(16px); border: 1px solid rgba(124, 58, 237, 0.12); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
        .glass-card:hover { border-color: rgba(124, 58, 237, 0.3); transform: translateY(-2px); box-shadow: 0 8px 32px rgba(124, 58, 237, 0.15); }

        .gradient-brand { background: linear-gradient(135deg, #7c3aed 0%, #ec4899 100%); }
        .gradient-fire { background: linear-gradient(135deg, #f97316 0%, #ef4444 100%); }
        .gradient-ocean { background: linear-gradient(135deg, #06b6d4 0%, #7c3aed 100%); }
        .gradient-success { background: linear-gradient(135deg, #10b981 0%, #06b6d4 100%); }
        .gradient-bg { background: radial-gradient(ellipse at top left, rgba(124,58,237,0.15) 0%, transparent 50%), radial-gradient(ellipse at bottom right, rgba(236,72,153,0.1) 0%, transparent 50%); }
        .text-gradient { background: linear-gradient(135deg, #a78bfa, #ec4899); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }

        @keyframes fadeUp { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes pulse-glow { 0%, 100% { box-shadow: 0 0 0 0 rgba(124,58,237,0.4); } 50% { box-shadow: 0 0 20px 4px rgba(124,58,237,0.2); } }
        @keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }
        .animate-fade-up { animation: fadeUp 0.4s ease-out both; }
        .animate-fade-up-delay { animation: fadeUp 0.4s ease-out 0.1s both; }
        .animate-pulse-glow { animation: pulse-glow 2s ease-in-out infinite; }
        .skeleton { background: linear-gradient(90deg, rgba(31,21,56,0.5) 25%, rgba(54,42,92,0.5) 50%, rgba(31,21,56,0.5) 75%); background-size: 200% 100%; animation: shimmer 1.5s infinite; border-radius: 8px; }

        .sidebar-link { display: flex; align-items: center; gap: 12px; padding: 10px 14px; border-radius: 12px; color: rgba(255,255,255,0.55); font-size: 14px; font-weight: 500; transition: all 0.2s; }
        .sidebar-link:hover { color: rgba(255,255,255,0.9); background: rgba(124,58,237,0.1); }
        .sidebar-link.active { color: #fff; background: rgba(124,58,237,0.2); box-shadow: 0 0 20px rgba(124,58,237,0.1); }
        .sidebar-link.active i { color: #a78bfa; }

        .score-ring { width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 13px; font-weight: 700; position: relative; }
        .score-ring::before { content: ''; position: absolute; inset: 0; border-radius: 50%; padding: 3px; background: conic-gradient(var(--ring-color) calc(var(--score) * 3.6deg), rgba(255,255,255,0.08) 0); -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); -webkit-mask-composite: xor; mask-composite: exclude; }

        .mobile-nav { display: none; }
        @media (max-width: 768px) {
            .desktop-sidebar { display: none !important; }
            .mobile-nav { display: flex; position: fixed; bottom: 0; left: 0; right: 0; z-index: 50; background: rgba(15, 10, 30, 0.95); backdrop-filter: blur(20px); border-top: 1px solid rgba(124,58,237,0.15); padding: 6px 0 env(safe-area-inset-bottom, 8px); }
            .main-content { padding-bottom: 80px !important; margin-left: 0 !important; }
        }
        .mobile-nav-item { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 3px; padding: 6px 4px; color: rgba(255,255,255,0.45); font-size: 10px; font-weight: 500; transition: color 0.2s; text-decoration: none; }
        .mobile-nav-item.active { color: #a78bfa; }
        .mobile-nav-item i { width: 22px; height: 22px; }

        .toast-container { position: fixed; top: 20px; right: 20px; z-index: 9999; display: flex; flex-direction: column; gap: 8px; }
        @media (max-width: 768px) { .toast-container { top: auto; bottom: 90px; right: 12px; left: 12px; } }
        .toast { padding: 12px 20px; border-radius: 12px; font-size: 14px; font-weight: 500; color: #fff; animation: fadeUp 0.3s ease-out; backdrop-filter: blur(12px); }

        .badge-youtube { background: rgba(255,0,0,0.15); color: #ff4444; border: 1px solid rgba(255,0,0,0.2); }
        .badge-tiktok { background: rgba(255,255,255,0.08); color: #fff; border: 1px solid rgba(255,255,255,0.15); }
        .badge-instagram { background: rgba(225,48,108,0.15); color: #e1306c; border: 1px solid rgba(225,48,108,0.2); }

        .grid-cards { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); }
        @media (max-width: 640px) { .grid-cards { grid-template-columns: 1fr; gap: 12px; } }

        .tab-btn { padding: 8px 16px; border-radius: 10px; font-size: 13px; font-weight: 600; color: rgba(255,255,255,0.5); transition: all 0.2s; cursor: pointer; white-space: nowrap; }
        .tab-btn:hover { color: rgba(255,255,255,0.8); }
        .tab-btn.active { background: rgba(124,58,237,0.2); color: #fff; }

        .stat-number { font-size: 28px; font-weight: 800; line-height: 1; }
        @media (max-width: 640px) { .stat-number { font-size: 22px; } }

        :focus-visible { outline: 2px solid #7c3aed; outline-offset: 2px; border-radius: 4px; }
        @media print { .no-print { display: none !important; } }
    </style>
</head>
<body class="h-full text-white antialiased" x-data="viralApp()" x-init="init()">
    <div class="toast-container no-print" id="toastContainer"></div>

    <div class="flex h-full">
        <!-- DESKTOP SIDEBAR -->
        <aside class="desktop-sidebar fixed top-0 left-0 h-full z-40 flex flex-col transition-all duration-300"
               :class="sidebarExpanded ? 'w-[240px]' : 'w-[72px]'"
               style="background: linear-gradient(180deg, rgba(15,10,30,0.98) 0%, rgba(5,2,8,0.98) 100%); border-right: 1px solid rgba(124,58,237,0.1);">

            <div class="flex items-center gap-3 p-4 h-16">
                <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center text-white font-bold text-lg flex-shrink-0 animate-pulse-glow">V</div>
                <div x-show="sidebarExpanded" x-transition.opacity class="overflow-hidden">
                    <h1 class="font-bold text-base leading-tight">Viral Social</h1>
                    <p class="text-[10px] text-brand-300 font-medium tracking-wider uppercase">Pro Intelligence</p>
                </div>
            </div>

            <nav class="flex-1 px-3 py-2 space-y-1 overflow-y-auto" role="navigation" aria-label="Menu principal">
                <a href="/" class="sidebar-link {% block nav_dashboard %}{% endblock %}"><i data-lucide="layout-dashboard" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Dashboard</span></a>
                <a href="/viral-scanner" class="sidebar-link {% block nav_scanner %}{% endblock %}"><i data-lucide="scan-search" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Viral Scanner</span></a>
                <a href="/scrape" class="sidebar-link {% block nav_scrape %}{% endblock %}"><i data-lucide="radar" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Coletar</span></a>

                <div class="pt-3 pb-1" x-show="sidebarExpanded"><p class="px-3 text-[10px] text-white/30 uppercase tracking-widest font-semibold">Inteligencia</p></div>
                <div class="pt-2" x-show="!sidebarExpanded"><div class="border-t border-white/5 mx-2"></div></div>

                <a href="/opportunities" class="sidebar-link {% block nav_opportunities %}{% endblock %}"><i data-lucide="target" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Oportunidades</span></a>
                <a href="/intelligence" class="sidebar-link {% block nav_intelligence %}{% endblock %}"><i data-lucide="brain" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Inteligencia</span></a>
                <a href="/trends" class="sidebar-link {% block nav_trends %}{% endblock %}"><i data-lucide="trending-up" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Tendencias</span></a>
                <a href="/trends-discovery" class="sidebar-link {% block nav_trends_discovery %}{% endblock %}"><i data-lucide="flame" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Trends Discovery</span></a>
                <a href="/sounds" class="sidebar-link {% block nav_sounds %}{% endblock %}"><i data-lucide="music" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Sons & Musicas</span></a>
                <a href="/hashtags-page" class="sidebar-link {% block nav_hashtags %}{% endblock %}"><i data-lucide="hash" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Hashtags</span></a>
                <a href="/videos-campeoes" class="sidebar-link {% block nav_campeoes %}{% endblock %}"><i data-lucide="trophy" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Videos Campeoes</span></a>
                <a href="/tiktok-profile" class="sidebar-link {% block nav_tiktok_profile %}{% endblock %}"><i data-lucide="user-search" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Perfil TikTok</span></a>
                <a href="/shop" class="sidebar-link {% block nav_shop %}{% endblock %}"><i data-lucide="shopping-bag" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>TikTok Shop</span></a>
                <a href="/shop-dashboard" class="sidebar-link {% block nav_shop_dashboard %}{% endblock %}"><i data-lucide="layout-grid" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Shop Dashboard</span></a>
                <a href="/scanner-history" class="sidebar-link {% block nav_scanner_history %}{% endblock %}"><i data-lucide="history" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Historico Scanner</span></a>

                <div class="pt-3 pb-1" x-show="sidebarExpanded"><p class="px-3 text-[10px] text-white/30 uppercase tracking-widest font-semibold">Estrategia</p></div>
                <div class="pt-2" x-show="!sidebarExpanded"><div class="border-t border-white/5 mx-2"></div></div>

                <a href="/transcribe" class="sidebar-link {% block nav_transcribe %}{% endblock %}"><i data-lucide="file-text" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Transcrever</span></a>
                <a href="/ideas" class="sidebar-link {% block nav_ideas %}{% endblock %}"><i data-lucide="lightbulb" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Banco de Ideias</span></a>
                <a href="/creators-page" class="sidebar-link {% block nav_creators %}{% endblock %}"><i data-lucide="users" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Criadores</span></a>
                <a href="/competitors-spy" class="sidebar-link {% block nav_competitors %}{% endblock %}"><i data-lucide="eye" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Espiao</span></a>
                <a href="/script-genius" class="sidebar-link {% block nav_scriptgenius %}{% endblock %}"><i data-lucide="pen-tool" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>ScriptGenius</span></a>
                <a href="/academy" class="sidebar-link {% block nav_academy %}{% endblock %}"><i data-lucide="graduation-cap" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Academy</span></a>
                <a href="/calendar-page" class="sidebar-link {% block nav_calendar %}{% endblock %}"><i data-lucide="calendar" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Calendario</span></a>
                <a href="/engage" class="sidebar-link {% block nav_engage %}{% endblock %}"><i data-lucide="message-circle" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>EngageBot</span></a>
                <a href="/dark-factory" class="sidebar-link {% block nav_darkfactory %}{% endblock %}"><i data-lucide="clapperboard" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>DarkFactory</span></a>
                <a href="/automate" class="sidebar-link {% block nav_automate %}{% endblock %}"><i data-lucide="workflow" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>AutoFlow</span></a>
                <a href="/crm" class="sidebar-link {% block nav_crm %}{% endblock %}"><i data-lucide="contact" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>CreatorCRM</span></a>
                <a href="/agency" class="sidebar-link {% block nav_agency %}{% endblock %}"><i data-lucide="building-2" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>AgencyHub</span></a>
                <a href="/youtube-upload" class="sidebar-link {% block nav_ytupload %}{% endblock %}"><i data-lucide="upload-cloud" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>YT Upload</span></a>

                <div class="pt-3 pb-1" x-show="sidebarExpanded"><p class="px-3 text-[10px] text-white/30 uppercase tracking-widest font-semibold">Sistema</p></div>
                <div class="pt-2" x-show="!sidebarExpanded"><div class="border-t border-white/5 mx-2"></div></div>

                <a href="/downloads-page" class="sidebar-link {% block nav_downloads %}{% endblock %}"><i data-lucide="download-cloud" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Downloads</span></a>
                <a href="/scheduler-page" class="sidebar-link {% block nav_scheduler %}{% endblock %}"><i data-lucide="settings-2" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Automacao</span></a>
                <a href="/alerts-page" class="sidebar-link {% block nav_alerts %}{% endblock %}"><i data-lucide="bell" class="w-5 h-5 flex-shrink-0"></i>
                    <span x-show="sidebarExpanded" x-transition.opacity>Alertas <span x-show="unreadAlerts > 0" class="ml-1 px-1.5 py-0.5 text-[10px] rounded-full gradient-fire" x-text="unreadAlerts"></span></span>
                </a>
                <a href="/settings-page" class="sidebar-link {% block nav_settings %}{% endblock %}"><i data-lucide="sliders-horizontal" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Configuracoes</span></a>
                <a href="/tutorial" class="sidebar-link {% block nav_tutorial %}{% endblock %}"><i data-lucide="book-open" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Tutorial</span></a>
                <a href="/mega-plano" class="sidebar-link {% block nav_megaplano %}{% endblock %}"><i data-lucide="rocket" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Mega Plano</span></a>
                <a href="/ciencia-viralizacao" class="sidebar-link {% block nav_ciencia %}{% endblock %}"><i data-lucide="graduation-cap" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Viralizacao</span></a>
                <a href="/roadmap-dev" class="sidebar-link {% block nav_roadmapdev %}{% endblock %}"><i data-lucide="target" class="w-5 h-5 flex-shrink-0"></i><span x-show="sidebarExpanded" x-transition.opacity>Roadmap Dev</span></a>
            </nav>

            <div class="p-3 border-t border-white/5">
                <button @click="sidebarExpanded = !sidebarExpanded; localStorage.setItem('sidebar', sidebarExpanded)" class="sidebar-link w-full justify-center" aria-label="Expandir ou recolher menu">
                    <i data-lucide="panel-left-close" class="w-5 h-5 flex-shrink-0 transition-transform" :class="!sidebarExpanded && 'rotate-180'"></i>
                    <span x-show="sidebarExpanded" x-transition.opacity>Recolher</span>
                </button>
            </div>
        </aside>

        <!-- MAIN CONTENT -->
        <main class="main-content flex-1 min-h-screen transition-all duration-300" :class="sidebarExpanded ? 'ml-[240px]' : 'ml-[72px]'">
            <header class="sticky top-0 z-30 glass no-print">
                <div class="flex items-center justify-between h-14 px-4 md:px-6">
                    <div class="flex items-center gap-3">
                        <h2 class="text-base md:text-lg font-bold text-white/90">{% block page_title %}Dashboard{% endblock %}</h2>
                        <p class="hidden md:block text-xs text-white/40">{% block page_subtitle %}{% endblock %}</p>
                    </div>
                    <div class="flex items-center gap-2">
                        <!-- Language selector -->
                        <div class="hidden md:flex items-center gap-1 bg-white/5 rounded-xl p-0.5">
                            <button @click="setGlobalLang('')" class="px-2.5 py-1.5 rounded-lg text-xs font-medium transition" :class="globalLang==='' ? 'bg-brand-500 text-white' : 'text-white/40 hover:text-white/70'" title="Todos os idiomas">ALL</button>
                            <button @click="setGlobalLang('pt')" class="px-2.5 py-1.5 rounded-lg text-xs font-medium transition" :class="globalLang==='pt' ? 'bg-brand-500 text-white' : 'text-white/40 hover:text-white/70'" title="Portugues">PT</button>
                            <button @click="setGlobalLang('en')" class="px-2.5 py-1.5 rounded-lg text-xs font-medium transition" :class="globalLang==='en' ? 'bg-brand-500 text-white' : 'text-white/40 hover:text-white/70'" title="English">EN</button>
                            <button @click="setGlobalLang('es')" class="px-2.5 py-1.5 rounded-lg text-xs font-medium transition" :class="globalLang==='es' ? 'bg-brand-500 text-white' : 'text-white/40 hover:text-white/70'" title="Espanol">ES</button>
                        </div>
                        <div class="hidden md:flex items-center glass-light rounded-xl px-3 py-2 w-64">
                            <i data-lucide="search" class="w-4 h-4 text-white/30 mr-2"></i>
                            <input type="text" placeholder="Buscar videos, criadores..." class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full" @keyup.enter="globalSearch($event.target.value)">
                        </div>
                        <button @click="quickDiscover()" class="p-2 rounded-xl hover:bg-white/5 transition relative group" title="Descoberta rapida">
                            <i data-lucide="zap" class="w-5 h-5 text-brand-400"></i>
                        </button>
                        <a href="/alerts-page" class="p-2 rounded-xl hover:bg-white/5 transition relative" aria-label="Alertas">
                            <i data-lucide="bell" class="w-5 h-5 text-white/50"></i>
                            <span x-show="unreadAlerts > 0" class="absolute -top-0.5 -right-0.5 w-4 h-4 rounded-full gradient-fire flex items-center justify-center text-[9px] font-bold" x-text="unreadAlerts"></span>
                        </a>
                    </div>
                </div>
            </header>

            <div class="p-4 md:p-6 gradient-bg min-h-[calc(100vh-56px)]">
                {% block content %}{% endblock %}
            </div>
        </main>
    </div>

    <!-- MOBILE BOTTOM NAV -->
    <nav class="mobile-nav no-print" role="navigation" aria-label="Menu mobile">
        <a href="/" class="mobile-nav-item {% block mnav_dashboard %}{% endblock %}"><i data-lucide="layout-dashboard"></i><span>Home</span></a>
        <a href="/viral-scanner" class="mobile-nav-item {% block mnav_scanner %}{% endblock %}"><i data-lucide="scan-search"></i><span>Scanner</span></a>
        <a href="/intelligence" class="mobile-nav-item {% block mnav_intelligence %}{% endblock %}"><i data-lucide="brain"></i><span>Insights</span></a>
        <a href="/ideas" class="mobile-nav-item {% block mnav_ideas %}{% endblock %}"><i data-lucide="lightbulb"></i><span>Ideias</span></a>
        <a href="/scrape" class="mobile-nav-item {% block mnav_scrape %}{% endblock %}"><i data-lucide="radar"></i><span>Coletar</span></a>
    </nav>

    <!-- VIDEO PREVIEW MODAL -->
    <div x-show="previewVideo" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
         @click.self="previewVideo = null" @keydown.escape.window="previewVideo = null"
         x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-150" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0"
         role="dialog" aria-modal="true">
        <div class="glass rounded-2xl w-full max-h-[90vh] overflow-y-auto"
             :class="getEmbeddableVideoId(previewVideo) ? 'max-w-4xl' : 'max-w-2xl'" @click.stop>
            <div class="p-4 flex items-center justify-between border-b border-white/5">
                <h3 class="font-bold text-white/90 truncate pr-4" x-text="previewVideo?.title"></h3>
                <button @click="previewVideo = null" class="p-1.5 rounded-lg hover:bg-white/10 flex-shrink-0"><i data-lucide="x" class="w-5 h-5"></i></button>
            </div>
            <div class="p-4 space-y-4">
                <!-- Embeddable Video Player (TikTok or YouTube) -->
                <template x-if="getEmbeddableVideoId(previewVideo)">
                    <div class="flex flex-col md:flex-row gap-4">
                        <div class="flex-shrink-0 mx-auto md:mx-0 rounded-xl overflow-hidden bg-dark-800 border border-white/5" style="width: 340px; height: 605px; max-width: 100%;">
                            <!-- TikTok iframe -->
                            <iframe x-show="getTikTokVideoId(previewVideo)" :src="getTikTokVideoId(previewVideo) ? 'https://www.tiktok.com/player/v1/' + getTikTokVideoId(previewVideo) + '?autoplay=1&loop=0&controls=1&music_info=0&description=0&rel=0' : ''"
                                width="100%" height="100%" frameborder="0" allow="autoplay; encrypted-media; fullscreen" allowfullscreen
                                style="border:0; border-radius: 12px;"></iframe>
                            <!-- YouTube iframe -->
                            <iframe x-show="!getTikTokVideoId(previewVideo) && getYouTubeVideoId(previewVideo)" :src="getYouTubeVideoId(previewVideo) ? 'https://www.youtube-nocookie.com/embed/' + getYouTubeVideoId(previewVideo) + '?autoplay=1&loop=1&rel=0&modestbranding=1&playsinline=1' : ''"
                                width="100%" height="100%" frameborder="0" allow="autoplay; encrypted-media; fullscreen" allowfullscreen
                                style="border:0; border-radius: 12px;"></iframe>
                        </div>
                        <div class="flex-1 min-w-0 space-y-4">
                            <div class="grid grid-cols-2 gap-3">
                                <div class="glass-light rounded-xl p-3 text-center"><p class="text-lg font-bold text-white" x-text="formatNumber(previewVideo?.views || 0)"></p><p class="text-[10px] text-white/40">Views</p></div>
                                <div class="glass-light rounded-xl p-3 text-center"><p class="text-lg font-bold text-accent-pink" x-text="formatNumber(previewVideo?.likes || 0)"></p><p class="text-[10px] text-white/40">Likes</p></div>
                                <div class="glass-light rounded-xl p-3 text-center"><p class="text-lg font-bold text-accent-cyan" x-text="formatNumber(previewVideo?.comments || 0)"></p><p class="text-[10px] text-white/40">Comentarios</p></div>
                                <div class="glass-light rounded-xl p-3 text-center"><p class="text-lg font-bold text-accent-green" x-text="formatNumber(previewVideo?.shares || 0)"></p><p class="text-[10px] text-white/40">Shares</p></div>
                            </div>
                            <div x-show="previewVideo?.description" class="text-sm text-white/50 leading-relaxed line-clamp-4" x-text="previewVideo?.description?.substring(0, 300)"></div>
                            <div x-show="previewVideo?.hashtags?.length" class="flex flex-wrap gap-1.5">
                                <template x-for="tag in (previewVideo?.hashtags || []).slice(0, 8)">
                                    <span class="px-2 py-0.5 rounded-lg text-[10px] font-medium glass-light text-brand-300" x-text="'#' + tag"></span>
                                </template>
                            </div>
                            <div class="flex gap-2 flex-wrap">
                                <a :href="previewVideo?.url" target="_blank" rel="noopener" class="flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-xl gradient-brand text-white font-semibold text-xs hover:opacity-90 transition">
                                    <i data-lucide="external-link" class="w-3.5 h-3.5"></i> <span x-text="previewVideo?.platform === 'youtube' ? 'Abrir no YouTube' : 'Abrir no TikTok'"></span>
                                </a>
                                <button @click="downloadVideo(previewVideo)" :disabled="downloadingId === previewVideo?.id" class="flex items-center justify-center gap-2 px-3 py-2 rounded-xl glass-card text-white/80 font-medium text-xs hover:text-white disabled:opacity-50">
                                    <i data-lucide="download" class="w-3.5 h-3.5" :class="downloadingId === previewVideo?.id && 'animate-bounce'"></i>
                                    <span x-text="downloadingId === previewVideo?.id ? 'Baixando...' : 'Download'"></span>
                                </button>
                                <button @click="saveIdea(previewVideo)" class="flex items-center justify-center gap-2 px-3 py-2 rounded-xl glass-card text-white/80 font-medium text-xs hover:text-white">
                                    <i data-lucide="bookmark-plus" class="w-3.5 h-3.5"></i> Salvar
                                </button>
                            </div>
                        </div>
                    </div>
                </template>
                <!-- Non-embeddable fallback (Instagram, etc) -->
                <template x-if="!getEmbeddableVideoId(previewVideo)">
                    <div>
                        <div class="rounded-xl overflow-hidden bg-dark-800 aspect-video flex items-center justify-center">
                            <img :src="previewVideo?.id ? '/api/thumbnail/' + previewVideo.id : ''" class="w-full h-full object-cover" :alt="previewVideo?.title" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex'">
                            <div class="hidden items-center justify-center text-white/20"><i data-lucide="video" class="w-12 h-12"></i></div>
                        </div>
                        <div class="grid grid-cols-4 gap-3 mt-4">
                            <div class="text-center"><p class="text-lg font-bold text-white" x-text="formatNumber(previewVideo?.views || 0)"></p><p class="text-xs text-white/40">Views</p></div>
                            <div class="text-center"><p class="text-lg font-bold text-accent-pink" x-text="formatNumber(previewVideo?.likes || 0)"></p><p class="text-xs text-white/40">Likes</p></div>
                            <div class="text-center"><p class="text-lg font-bold text-accent-cyan" x-text="formatNumber(previewVideo?.comments || 0)"></p><p class="text-xs text-white/40">Comentarios</p></div>
                            <div class="text-center"><p class="text-lg font-bold text-accent-green" x-text="formatNumber(previewVideo?.shares || 0)"></p><p class="text-xs text-white/40">Shares</p></div>
                        </div>
                        <div class="flex gap-3 flex-wrap mt-4">
                            <a :href="previewVideo?.url" target="_blank" rel="noopener" class="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition min-w-[140px]">
                                <i data-lucide="external-link" class="w-4 h-4"></i> Abrir Original
                            </a>
                            <button @click="downloadVideo(previewVideo)" :disabled="downloadingId === previewVideo?.id" class="flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl glass-card text-white/80 font-medium text-sm hover:text-white disabled:opacity-50">
                                <i data-lucide="download" class="w-4 h-4" :class="downloadingId === previewVideo?.id && 'animate-bounce'"></i>
                                <span x-text="downloadingId === previewVideo?.id ? 'Baixando...' : 'Download'"></span>
                            </button>
                            <button @click="saveIdea(previewVideo)" class="flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl glass-card text-white/80 font-medium text-sm hover:text-white">
                                <i data-lucide="bookmark-plus" class="w-4 h-4"></i> Salvar Ideia
                            </button>
                        </div>
                        <div x-show="previewVideo?.description" class="text-sm text-white/50 leading-relaxed mt-4" x-text="previewVideo?.description?.substring(0, 300)"></div>
                        <div x-show="previewVideo?.hashtags?.length" class="flex flex-wrap gap-2 mt-3">
                            <template x-for="tag in (previewVideo?.hashtags || []).slice(0, 10)">
                                <span class="px-2.5 py-1 rounded-lg text-xs font-medium glass-light text-brand-300" x-text="'#' + tag"></span>
                            </template>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <script>
        function viralApp() {
            return {
                sidebarExpanded: localStorage.getItem('sidebar') !== 'false',
                mobileMenuOpen: false,
                unreadAlerts: 0,
                previewVideo: null,
                globalLang: localStorage.getItem('globalLang') || '',
                downloadingId: null,

                init() {
                    this.fetchAlerts();
                    setInterval(() => this.fetchAlerts(), 60000);
                    this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
                    window.addEventListener('preview-video', e => { this.previewVideo = e.detail; });
                },

                setGlobalLang(lang) {
                    this.globalLang = lang;
                    localStorage.setItem('globalLang', lang);
                    // Dispatch event so child pages can react
                    window.dispatchEvent(new CustomEvent('lang-changed', { detail: lang }));
                },

                async downloadVideo(video) {
                    if (!video?.url || this.downloadingId) return;
                    this.downloadingId = video.id;
                    showToast('Baixando video... aguarde', 'info');
                    try {
                        const params = new URLSearchParams({ url: video.url, quality: 'best' });
                        const r = await fetch('/api/download/url?' + params, { method: 'POST' });
                        const d = await r.json();
                        if (d.error) { showToast('Erro: ' + d.error, 'error'); }
                        else {
                            showToast('Download concluido! Baixando para seu computador...', 'success');
                            const a = document.createElement('a');
                            a.href = '/api/downloads/file?path=' + encodeURIComponent(d.path);
                            a.download = d.filename || 'video.mp4';
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                        }
                    } catch(e) { showToast('Erro no download', 'error'); }
                    this.downloadingId = null;
                },

                async fetchAlerts() {
                    try { const r = await fetch('/api/alerts'); const a = await r.json(); this.unreadAlerts = a.filter(x => !x.read).length; } catch(e) {}
                },

                async quickDiscover() {
                    showToast('Iniciando descoberta rapida...', 'info');
                    try {
                        const r = await fetch('/api/discover/all?region=BR&max_per_platform=25');
                        const d = await r.json();
                        showToast(`${d.total} videos descobertos!`, 'success');
                        if (window.location.pathname === '/') setTimeout(() => location.reload(), 1500);
                    } catch(e) { showToast('Erro na descoberta', 'error'); }
                },

                globalSearch(q) { if (q.trim()) window.location.href = '/viral-scanner'; },

                async saveIdea(video) {
                    if (!video) return;
                    try {
                        await apiCall('/api/ideas', 'POST', { video_id: video.id, title: video.title, platform: video.platform, url: video.url, thumbnail_url: video.thumbnail_url, notes: '', status: 'idea' });
                        showToast('Ideia salva!', 'success');
                    } catch(e) { showToast('Erro ao salvar ideia', 'error'); }
                },
            };
        }

        function getTikTokVideoId(video) {
            if (!video) return null;
            if (video.platform === 'tiktok' && video.external_id) return video.external_id;
            if (video.url) {
                const m = video.url.match(/tiktok\.com\/@[^/]+\/video\/(\d+)/);
                if (m) return m[1];
            }
            return null;
        }

        function getYouTubeVideoId(video) {
            if (!video) return null;
            if (video.platform === 'youtube' && video.external_id) return video.external_id;
            if (video.url) {
                let m = video.url.match(/youtube\.com\/shorts\/([a-zA-Z0-9_-]+)/);
                if (m) return m[1];
                m = video.url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);
                if (m) return m[1];
            }
            return null;
        }

        function getEmbeddableVideoId(video) {
            return getTikTokVideoId(video) ? 'tiktok' : (getYouTubeVideoId(video) ? 'youtube' : null);
        }

        function showToast(message, type = 'info') {
            const c = document.getElementById('toastContainer');
            const colors = { success: 'background:rgba(16,185,129,0.9)', error: 'background:rgba(239,68,68,0.9)', info: 'background:rgba(124,58,237,0.9)', warning: 'background:rgba(249,115,22,0.9)' };
            const t = document.createElement('div'); t.className = 'toast'; t.style.cssText = colors[type] || colors.info; t.textContent = message;
            c.appendChild(t); setTimeout(() => { t.style.opacity='0'; t.style.transform='translateY(-10px)'; t.style.transition='all 0.3s'; setTimeout(() => t.remove(), 300); }, 4000);
        }

        async function apiCall(url, method = 'GET', body = null) {
            const opts = { method, headers: { 'Content-Type': 'application/json' } };
            if (body && method !== 'GET') opts.body = JSON.stringify(body);
            const r = await fetch(url, opts); if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json();
        }

        function formatNumber(n) {
            if (n == null) return '0'; n = parseInt(n);
            if (n >= 1e9) return (n/1e9).toFixed(1)+'B'; if (n >= 1e6) return (n/1e6).toFixed(1)+'M'; if (n >= 1e3) return (n/1e3).toFixed(1)+'K'; return n.toLocaleString('pt-BR');
        }
        function formatDuration(s) { if(!s) return '--'; return Math.floor(s/60)+':'+String(s%60).padStart(2,'0'); }
        function scoreColor(s) { if(s>=80) return '#10b981'; if(s>=60) return '#f97316'; if(s>=40) return '#eab308'; return '#6b7280'; }
        function engagementRate(v,l,c,s) { if(!v) return '0'; return (((l||0)+(c||0)+(s||0))/v*100).toFixed(2); }
        function timeAgo(d) { if(!d) return ''; const s=Math.floor((new Date()-new Date(d))/1000); if(s<60) return 'agora'; if(s<3600) return Math.floor(s/60)+'min'; if(s<86400) return Math.floor(s/3600)+'h'; if(s<604800) return Math.floor(s/86400)+'d'; return Math.floor(s/604800)+'sem'; }
        function platformLabel(p) { return {youtube:'YouTube',tiktok:'TikTok',instagram:'Instagram'}[(p||'').toLowerCase()]||p; }

        document.addEventListener('DOMContentLoaded', () => { if(window.lucide) lucide.createIcons(); });
        document.addEventListener('alpine:initialized', () => { if(window.lucide) lucide.createIcons(); });
    </script>
    {% block scripts %}{% endblock %}
</body>
</html>
