{% extends "base.html" %}
{% block title %}YT Bulk Upload - Viral Social Pro{% endblock %}
{% block nav_ytupload %}active{% endblock %}
{% block page_title %}YouTube Bulk Upload{% endblock %}
{% block page_subtitle %}Upload e agendamento em massa{% endblock %}

{% block content %}
<div x-data="youtubeUploadApp()" x-init="init()">

    <!-- Header -->
    <div class="glass-card rounded-2xl p-6 mb-6 gradient-bg">
        <div class="flex items-center gap-4">
            <div class="w-14 h-14 rounded-2xl bg-red-500/20 flex items-center justify-center">
                <i data-lucide="upload-cloud" class="w-7 h-7 text-red-400"></i>
            </div>
            <div>
                <h1 class="text-2xl font-bold text-white">YouTube Bulk Upload</h1>
                <p class="text-sm text-white/50">Aponte uma pasta com videos, defina intervalo e agende tudo automaticamente</p>
            </div>
        </div>
    </div>

    <!-- OAuth Setup Section -->
    <div class="glass-card rounded-2xl p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-lg font-bold text-white flex items-center gap-2">
                <i data-lucide="key" class="w-5 h-5 text-brand-400"></i>
                Conexao YouTube
            </h2>
            <div class="flex items-center gap-2">
                <template x-if="authStatus.authenticated">
                    <span class="px-3 py-1 rounded-full text-xs font-semibold bg-green-500/20 text-green-400 border border-green-500/20">Conectado</span>
                </template>
                <template x-if="!authStatus.authenticated && authStatus.has_client_secret">
                    <span class="px-3 py-1 rounded-full text-xs font-semibold bg-yellow-500/20 text-yellow-400 border border-yellow-500/20">Nao conectado</span>
                </template>
                <template x-if="!authStatus.has_client_secret">
                    <span class="px-3 py-1 rounded-full text-xs font-semibold bg-red-500/20 text-red-400 border border-red-500/20">Client Secret ausente</span>
                </template>
            </div>
        </div>

        <!-- Step 1: Upload client_secret.json -->
        <div x-show="!authStatus.has_client_secret" class="space-y-4">
            <div class="glass-light rounded-xl p-4">
                <h3 class="font-semibold text-white/90 mb-2">Passo 1: Upload do client_secret.json</h3>
                <ol class="text-sm text-white/50 space-y-1 mb-4 list-decimal list-inside">
                    <li>Acesse <a href="https://console.cloud.google.com" target="_blank" class="text-brand-300 underline">Google Cloud Console</a></li>
                    <li>Crie um projeto e ative a YouTube Data API v3</li>
                    <li>Va em Credenciais > Criar credenciais > ID do cliente OAuth</li>
                    <li>Tipo: Aplicativo da Web. Adicione o redirect URI: <code class="text-brand-200 bg-dark-700 px-1 rounded" x-text="window.location.origin + '/api/youtube/upload/oauth/callback'"></code></li>
                    <li>Baixe o JSON e faca upload abaixo</li>
                </ol>
                <div class="flex items-center gap-3">
                    <label class="flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl border-2 border-dashed border-brand-500/30 hover:border-brand-500/60 cursor-pointer transition">
                        <i data-lucide="upload" class="w-5 h-5 text-brand-400"></i>
                        <span class="text-sm font-medium text-white/70">Escolher client_secret.json</span>
                        <input type="file" accept=".json" class="hidden" @change="uploadClientSecret($event)">
                    </label>
                </div>
                <p x-show="uploadError" class="text-red-400 text-xs mt-2" x-text="uploadError"></p>
            </div>
        </div>

        <!-- Step 2: Connect YouTube -->
        <div x-show="authStatus.has_client_secret && !authStatus.authenticated" class="space-y-4">
            <div class="glass-light rounded-xl p-4">
                <h3 class="font-semibold text-white/90 mb-2">Passo 2: Conectar conta YouTube</h3>
                <p class="text-sm text-white/50 mb-4">Autorize o acesso para upload de videos.</p>
                <button @click="startAuth()" :disabled="authLoading" class="px-6 py-3 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-50 flex items-center gap-2">
                    <i data-lucide="log-in" class="w-4 h-4"></i>
                    <span x-text="authLoading ? 'Gerando link...' : 'Conectar YouTube'"></span>
                </button>
            </div>
        </div>

        <!-- Connected state -->
        <div x-show="authStatus.authenticated" class="flex items-center justify-between">
            <p class="text-sm text-white/60">Conta YouTube conectada e pronta para uploads.</p>
            <button @click="revokeAuth()" class="px-4 py-2 rounded-xl glass-card text-red-400 text-xs font-semibold hover:text-red-300 transition">
                <i data-lucide="unlink" class="w-3.5 h-3.5 inline mr-1"></i> Desconectar
            </button>
        </div>
    </div>

    <!-- New Batch Section -->
    <div x-show="authStatus.authenticated" class="glass-card rounded-2xl p-6 mb-6">
        <h2 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
            <i data-lucide="folder-plus" class="w-5 h-5 text-brand-400"></i>
            Novo Batch de Upload
        </h2>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Left: Folder + Scan -->
            <div class="space-y-4">
                <div>
                    <label class="text-sm font-medium text-white/70 mb-1 block">Pasta com videos</label>
                    <div class="flex gap-2">
                        <input type="text" x-model="newBatch.folder_path" placeholder="/caminho/para/videos" class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white placeholder:text-white/25 focus:border-brand-500 focus:outline-none">
                        <button @click="scanFolder()" :disabled="scanning" class="px-4 py-2.5 rounded-xl gradient-ocean text-white text-sm font-semibold hover:opacity-90 transition disabled:opacity-50 flex items-center gap-2 whitespace-nowrap">
                            <i data-lucide="search" class="w-4 h-4" :class="scanning && 'animate-spin'"></i>
                            <span x-text="scanning ? 'Escaneando...' : 'Escanear'"></span>
                        </button>
                    </div>
                </div>

                <!-- Scan results -->
                <div x-show="scanResult" class="glass-light rounded-xl p-4">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm font-semibold text-white/80" x-text="scanResult?.count + ' videos encontrados'"></span>
                        <span class="text-xs text-white/40" x-text="scanResult?.total_size_formatted"></span>
                    </div>
                    <div class="max-h-48 overflow-y-auto space-y-1">
                        <template x-for="(f, idx) in (scanResult?.files || [])" :key="idx">
                            <div class="flex items-center justify-between py-1 text-xs">
                                <span class="text-white/60 truncate mr-2" x-text="f.filename"></span>
                                <span class="text-white/30 flex-shrink-0" x-text="f.size_formatted"></span>
                            </div>
                        </template>
                    </div>
                </div>

                <div>
                    <label class="text-sm font-medium text-white/70 mb-1 block">Nome do batch (opcional)</label>
                    <input type="text" x-model="newBatch.name" placeholder="Ex: Videos Semana 1" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white placeholder:text-white/25 focus:border-brand-500 focus:outline-none">
                </div>
            </div>

            <!-- Right: Schedule + Metadata -->
            <div class="space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="text-sm font-medium text-white/70 mb-1 block">Inicio agendamento</label>
                        <input type="datetime-local" x-model="newBatch.start_datetime" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white focus:border-brand-500 focus:outline-none">
                    </div>
                    <div>
                        <label class="text-sm font-medium text-white/70 mb-1 block">Intervalo entre uploads</label>
                        <select x-model="newBatch.interval_minutes" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white focus:border-brand-500 focus:outline-none">
                            <option value="30">30 min</option>
                            <option value="60">1 hora</option>
                            <option value="120">2 horas</option>
                            <option value="180">3 horas</option>
                            <option value="240">4 horas</option>
                            <option value="360">6 horas</option>
                            <option value="480">8 horas</option>
                            <option value="720">12 horas</option>
                            <option value="1440">24 horas</option>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="text-sm font-medium text-white/70 mb-1 block">Descricao padrao</label>
                    <textarea x-model="newBatch.default_description" rows="2" placeholder="Descricao aplicada a todos os videos" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white placeholder:text-white/25 focus:border-brand-500 focus:outline-none resize-none"></textarea>
                </div>

                <div>
                    <label class="text-sm font-medium text-white/70 mb-1 block">Tags padrao (separadas por virgula)</label>
                    <input type="text" x-model="newBatch.default_tags" placeholder="tag1, tag2, tag3" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white placeholder:text-white/25 focus:border-brand-500 focus:outline-none">
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="text-sm font-medium text-white/70 mb-1 block">Categoria</label>
                        <select x-model="newBatch.default_category_id" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white focus:border-brand-500 focus:outline-none">
                            <template x-for="cat in categories" :key="cat.id">
                                <option :value="cat.id" x-text="cat.title"></option>
                            </template>
                        </select>
                    </div>
                    <div>
                        <label class="text-sm font-medium text-white/70 mb-1 block">Privacidade</label>
                        <select x-model="newBatch.default_privacy" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white focus:border-brand-500 focus:outline-none">
                            <option value="private">Privado</option>
                            <option value="unlisted">Nao listado</option>
                            <option value="public">Publico</option>
                        </select>
                    </div>
                </div>

                <div class="flex items-center gap-3">
                    <label class="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" x-model="newBatch.use_publish_at" class="w-4 h-4 rounded border-white/20 bg-dark-700 text-brand-500 focus:ring-brand-500">
                        <span class="text-sm text-white/70">Usar publishAt (upload privado, YouTube publica no horario agendado)</span>
                    </label>
                </div>
            </div>
        </div>

        <div class="mt-6 flex items-center justify-between">
            <p class="text-xs text-white/30">
                <i data-lucide="info" class="w-3.5 h-3.5 inline"></i>
                Quota: Projetos nao-verificados tem ~6 uploads/dia. Verifique seu limite no Google Cloud Console.
            </p>
            <button @click="createBatch()" :disabled="!scanResult || creatingBatch" class="px-8 py-3 rounded-xl gradient-brand text-white font-bold text-sm hover:opacity-90 transition disabled:opacity-50 flex items-center gap-2">
                <i data-lucide="rocket" class="w-4 h-4"></i>
                <span x-text="creatingBatch ? 'Criando...' : 'Iniciar Upload'"></span>
            </button>
        </div>
    </div>

    <!-- Active Batches -->
    <div x-show="activeBatches.length > 0" class="mb-6">
        <h2 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
            <i data-lucide="activity" class="w-5 h-5 text-accent-green"></i>
            Batches Ativos
            <span class="text-xs text-white/30 font-normal" x-text="'(' + activeBatches.length + ')'"></span>
        </h2>
        <div class="space-y-4">
            <template x-for="batch in activeBatches" :key="batch.id">
                <div class="glass-card rounded-2xl p-5">
                    <div class="flex items-center justify-between mb-3">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-xl bg-brand-500/20 flex items-center justify-center">
                                <i data-lucide="upload-cloud" class="w-5 h-5 text-brand-400"></i>
                            </div>
                            <div>
                                <h3 class="font-bold text-white" x-text="batch.name || 'Batch #' + batch.id"></h3>
                                <p class="text-xs text-white/40" x-text="batch.folder_path"></p>
                            </div>
                        </div>
                        <div class="flex items-center gap-2">
                            <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase"
                                  :class="batchStatusClass(batch.status)" x-text="batch.status"></span>
                        </div>
                    </div>

                    <!-- Progress Bar -->
                    <div class="mb-3">
                        <div class="flex justify-between text-xs text-white/50 mb-1">
                            <span x-text="batch.uploaded_count + ' / ' + batch.total_files + ' enviados'"></span>
                            <span x-text="batch.failed_count > 0 ? batch.failed_count + ' falhas' : ''" class="text-red-400"></span>
                        </div>
                        <div class="w-full h-2 rounded-full bg-dark-700 overflow-hidden">
                            <div class="h-full rounded-full gradient-success transition-all duration-500"
                                 :style="'width:' + (batch.total_files ? (batch.uploaded_count / batch.total_files * 100) : 0) + '%'"></div>
                        </div>
                    </div>

                    <div class="flex items-center justify-between">
                        <div class="text-xs text-white/40">
                            <span>Intervalo: <strong class="text-white/60" x-text="formatInterval(batch.interval_minutes)"></strong></span>
                            <span class="mx-2">|</span>
                            <span>Inicio: <strong class="text-white/60" x-text="formatDate(batch.start_datetime)"></strong></span>
                        </div>
                        <div class="flex items-center gap-2">
                            <template x-if="batch.status === 'active'">
                                <button @click="pauseBatch(batch.id)" class="p-2 rounded-lg glass-light text-yellow-400 hover:text-yellow-300" title="Pausar">
                                    <i data-lucide="pause" class="w-4 h-4"></i>
                                </button>
                            </template>
                            <template x-if="batch.status === 'paused'">
                                <button @click="resumeBatch(batch.id)" class="p-2 rounded-lg glass-light text-green-400 hover:text-green-300" title="Retomar">
                                    <i data-lucide="play" class="w-4 h-4"></i>
                                </button>
                            </template>
                            <button @click="cancelBatch(batch.id)" class="p-2 rounded-lg glass-light text-red-400 hover:text-red-300" title="Cancelar">
                                <i data-lucide="x-circle" class="w-4 h-4"></i>
                            </button>
                            <template x-if="batch.failed_count > 0">
                                <button @click="retryBatch(batch.id)" class="p-2 rounded-lg glass-light text-brand-400 hover:text-brand-300" title="Retentar falhas">
                                    <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                                </button>
                            </template>
                            <button @click="toggleBatchDetail(batch.id)" class="p-2 rounded-lg glass-light text-white/40 hover:text-white/70" title="Ver detalhes">
                                <i data-lucide="chevron-down" class="w-4 h-4 transition-transform" :class="expandedBatch === batch.id && 'rotate-180'"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Batch Detail (expandable) -->
                    <div x-show="expandedBatch === batch.id" x-collapse class="mt-4 border-t border-white/5 pt-4">
                        <div class="max-h-64 overflow-y-auto space-y-2">
                            <template x-for="item in (batchDetails[batch.id]?.items || [])" :key="item.id">
                                <div class="flex items-center gap-3 py-2 px-3 rounded-lg glass-light text-xs">
                                    <span class="w-6 text-white/30 text-right" x-text="item.sort_order + 1"></span>
                                    <i data-lucide="file-video" class="w-4 h-4 text-white/30 flex-shrink-0"></i>
                                    <span class="flex-1 text-white/70 truncate" x-text="item.filename"></span>
                                    <span class="text-white/30 flex-shrink-0" x-text="formatDate(item.scheduled_time)"></span>
                                    <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase flex-shrink-0"
                                          :class="itemStatusClass(item.status)" x-text="item.status"></span>
                                    <a x-show="item.youtube_url" :href="item.youtube_url" target="_blank" class="text-red-400 hover:text-red-300 flex-shrink-0">
                                        <i data-lucide="external-link" class="w-3.5 h-3.5"></i>
                                    </a>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- History (completed/cancelled) -->
    <div x-show="historyBatches.length > 0">
        <button @click="showHistory = !showHistory" class="flex items-center gap-2 text-lg font-bold text-white mb-4">
            <i data-lucide="history" class="w-5 h-5 text-white/40"></i>
            Historico
            <span class="text-xs text-white/30 font-normal" x-text="'(' + historyBatches.length + ')'"></span>
            <i data-lucide="chevron-down" class="w-4 h-4 text-white/30 transition-transform" :class="showHistory && 'rotate-180'"></i>
        </button>
        <div x-show="showHistory" x-collapse class="space-y-3">
            <template x-for="batch in historyBatches" :key="batch.id">
                <div class="glass-card rounded-xl p-4">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-3">
                            <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase" :class="batchStatusClass(batch.status)" x-text="batch.status"></span>
                            <span class="font-semibold text-white/80 text-sm" x-text="batch.name || 'Batch #' + batch.id"></span>
                            <span class="text-xs text-white/30" x-text="batch.uploaded_count + '/' + batch.total_files + ' enviados'"></span>
                        </div>
                        <div class="flex items-center gap-2">
                            <span class="text-xs text-white/30" x-text="formatDate(batch.created_at)"></span>
                            <button @click="toggleBatchDetail(batch.id)" class="p-1.5 rounded-lg glass-light text-white/40 hover:text-white/70">
                                <i data-lucide="chevron-down" class="w-3.5 h-3.5 transition-transform" :class="expandedBatch === batch.id && 'rotate-180'"></i>
                            </button>
                            <button @click="deleteBatch(batch.id)" class="p-1.5 rounded-lg glass-light text-red-400/50 hover:text-red-400">
                                <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                            </button>
                        </div>
                    </div>

                    <div x-show="expandedBatch === batch.id" x-collapse class="mt-3 border-t border-white/5 pt-3">
                        <div class="max-h-48 overflow-y-auto space-y-1">
                            <template x-for="item in (batchDetails[batch.id]?.items || [])" :key="item.id">
                                <div class="flex items-center gap-3 py-1.5 px-2 text-xs">
                                    <span class="w-5 text-white/30 text-right" x-text="item.sort_order + 1"></span>
                                    <span class="flex-1 text-white/60 truncate" x-text="item.filename"></span>
                                    <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase" :class="itemStatusClass(item.status)" x-text="item.status"></span>
                                    <a x-show="item.youtube_url" :href="item.youtube_url" target="_blank" class="text-red-400 hover:text-red-300">
                                        <i data-lucide="external-link" class="w-3 h-3"></i>
                                    </a>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- Empty state -->
    <div x-show="!authStatus.authenticated && authStatus.has_client_secret === false && batches.length === 0" class="text-center py-16 text-white/30">
        <i data-lucide="upload-cloud" class="w-16 h-16 mx-auto mb-4 opacity-30"></i>
        <p class="text-lg font-semibold">Configure a conexao YouTube para comecar</p>
        <p class="text-sm mt-1">Siga os passos acima para conectar sua conta</p>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function youtubeUploadApp() {
    return {
        authStatus: { has_client_secret: false, authenticated: false },
        authLoading: false,
        uploadError: '',
        scanning: false,
        scanResult: null,
        creatingBatch: false,
        batches: [],
        batchDetails: {},
        expandedBatch: null,
        showHistory: false,
        categories: [
            {id: '1', title: 'Film & Animation'},
            {id: '2', title: 'Autos & Vehicles'},
            {id: '10', title: 'Music'},
            {id: '15', title: 'Pets & Animals'},
            {id: '17', title: 'Sports'},
            {id: '20', title: 'Gaming'},
            {id: '22', title: 'People & Blogs'},
            {id: '23', title: 'Comedy'},
            {id: '24', title: 'Entertainment'},
            {id: '25', title: 'News & Politics'},
            {id: '26', title: 'Howto & Style'},
            {id: '27', title: 'Education'},
            {id: '28', title: 'Science & Technology'},
        ],
        newBatch: {
            folder_path: '',
            name: '',
            start_datetime: '',
            interval_minutes: 120,
            default_description: '',
            default_tags: '',
            default_category_id: '22',
            default_privacy: 'private',
            use_publish_at: true,
        },
        pollTimer: null,

        async init() {
            // Set default start_datetime to now + 1 hour
            const d = new Date(Date.now() + 3600000);
            d.setMinutes(0, 0, 0);
            this.newBatch.start_datetime = d.toISOString().slice(0, 16);

            // Check auth params
            const params = new URLSearchParams(window.location.search);
            if (params.get('auth') === 'success') {
                showToast('YouTube conectado com sucesso!', 'success');
                window.history.replaceState({}, '', '/youtube-upload');
            }
            if (params.get('auth_error')) {
                showToast('Erro na autenticacao: ' + params.get('auth_error'), 'error');
                window.history.replaceState({}, '', '/youtube-upload');
            }
            if (params.get('code')) {
                // OAuth callback with code - exchange it
                await this.handleOAuthCode(params.get('code'));
                window.history.replaceState({}, '', '/youtube-upload');
            }

            await this.checkAuth();
            await this.loadBatches();
            await this.loadCategories();

            // Poll every 10 seconds for progress
            this.pollTimer = setInterval(() => this.loadBatches(), 10000);

            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async checkAuth() {
            try {
                const r = await fetch('/api/youtube/upload/auth/status');
                this.authStatus = await r.json();
            } catch(e) { console.error('Auth check failed:', e); }
        },

        async uploadClientSecret(event) {
            this.uploadError = '';
            const file = event.target.files[0];
            if (!file) return;
            const formData = new FormData();
            formData.append('file', file);
            try {
                const r = await fetch('/api/youtube/upload/client-secret', { method: 'POST', body: formData });
                const d = await r.json();
                if (d.error) { this.uploadError = d.error; showToast(d.error, 'error'); }
                else { showToast('client_secret.json salvo!', 'success'); await this.checkAuth(); }
            } catch(e) { this.uploadError = 'Erro no upload'; }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async startAuth() {
            this.authLoading = true;
            try {
                const baseUrl = window.location.origin;
                const r = await fetch('/api/youtube/upload/auth/start-with-url', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ base_url: baseUrl }),
                });
                const d = await r.json();
                if (d.error) { showToast(d.error, 'error'); }
                else if (d.auth_url) { window.location.href = d.auth_url; }
            } catch(e) { showToast('Erro ao gerar link de autorizacao', 'error'); }
            this.authLoading = false;
        },

        async handleOAuthCode(code) {
            try {
                const baseUrl = window.location.origin;
                const redirectUri = baseUrl + '/api/youtube/upload/oauth/callback';
                const r = await fetch('/api/youtube/upload/auth/callback', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ code, redirect_uri: redirectUri }),
                });
                const d = await r.json();
                if (d.success) { showToast('YouTube conectado com sucesso!', 'success'); }
                else { showToast('Erro: ' + (d.error || 'desconhecido'), 'error'); }
            } catch(e) { showToast('Erro no callback OAuth', 'error'); }
            await this.checkAuth();
        },

        async revokeAuth() {
            if (!confirm('Desconectar conta YouTube? Batches ativos serao pausados.')) return;
            try {
                await fetch('/api/youtube/upload/auth/revoke', { method: 'POST' });
                showToast('YouTube desconectado', 'info');
                await this.checkAuth();
            } catch(e) { showToast('Erro ao desconectar', 'error'); }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async scanFolder() {
            if (!this.newBatch.folder_path) { showToast('Informe o caminho da pasta', 'warning'); return; }
            this.scanning = true;
            this.scanResult = null;
            try {
                const r = await fetch('/api/youtube/upload/scan', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ folder_path: this.newBatch.folder_path }),
                });
                const d = await r.json();
                if (d.error) { showToast(d.error, 'error'); }
                else {
                    this.scanResult = d;
                    if (d.count === 0) showToast('Nenhum video encontrado na pasta', 'warning');
                    else showToast(d.count + ' videos encontrados!', 'success');
                }
            } catch(e) { showToast('Erro ao escanear pasta', 'error'); }
            this.scanning = false;
        },

        async createBatch() {
            if (!this.scanResult || this.scanResult.count === 0) return;
            if (!this.newBatch.start_datetime) { showToast('Defina a data/hora de inicio', 'warning'); return; }
            this.creatingBatch = true;
            try {
                const r = await fetch('/api/youtube/upload/batch', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(this.newBatch),
                });
                const d = await r.json();
                if (d.error) { showToast(d.error, 'error'); }
                else {
                    showToast('Batch criado com ' + (d.total_files || d.items?.length || 0) + ' videos!', 'success');
                    this.scanResult = null;
                    this.newBatch.folder_path = '';
                    this.newBatch.name = '';
                    await this.loadBatches();
                }
            } catch(e) { showToast('Erro ao criar batch', 'error'); }
            this.creatingBatch = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadBatches() {
            try {
                const r = await fetch('/api/youtube/upload/batches');
                this.batches = await r.json();
            } catch(e) {}
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadCategories() {
            try {
                const r = await fetch('/api/youtube/upload/categories');
                const cats = await r.json();
                if (Array.isArray(cats) && cats.length > 0) this.categories = cats;
            } catch(e) {}
        },

        async toggleBatchDetail(batchId) {
            if (this.expandedBatch === batchId) {
                this.expandedBatch = null;
                return;
            }
            this.expandedBatch = batchId;
            if (!this.batchDetails[batchId]) {
                try {
                    const r = await fetch('/api/youtube/upload/batch/' + batchId);
                    this.batchDetails[batchId] = await r.json();
                } catch(e) {}
            }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async pauseBatch(id) {
            await fetch('/api/youtube/upload/batch/' + id + '/pause', { method: 'POST' });
            showToast('Batch pausado', 'info');
            await this.loadBatches();
        },
        async resumeBatch(id) {
            await fetch('/api/youtube/upload/batch/' + id + '/resume', { method: 'POST' });
            showToast('Batch retomado', 'success');
            await this.loadBatches();
        },
        async cancelBatch(id) {
            if (!confirm('Cancelar este batch? Items pendentes serao cancelados.')) return;
            await fetch('/api/youtube/upload/batch/' + id + '/cancel', { method: 'POST' });
            showToast('Batch cancelado', 'warning');
            await this.loadBatches();
        },
        async retryBatch(id) {
            await fetch('/api/youtube/upload/batch/' + id + '/retry', { method: 'POST' });
            showToast('Retentando uploads falhos', 'info');
            delete this.batchDetails[id];
            await this.loadBatches();
        },
        async deleteBatch(id) {
            if (!confirm('Deletar este batch permanentemente?')) return;
            await fetch('/api/youtube/upload/batch/' + id, { method: 'DELETE' });
            showToast('Batch deletado', 'info');
            delete this.batchDetails[id];
            await this.loadBatches();
        },

        get activeBatches() {
            return this.batches.filter(b => ['active', 'paused', 'pending'].includes(b.status));
        },
        get historyBatches() {
            return this.batches.filter(b => ['completed', 'cancelled'].includes(b.status));
        },

        batchStatusClass(status) {
            const m = {
                active: 'bg-green-500/20 text-green-400 border border-green-500/20',
                paused: 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/20',
                pending: 'bg-blue-500/20 text-blue-400 border border-blue-500/20',
                completed: 'bg-brand-500/20 text-brand-300 border border-brand-500/20',
                cancelled: 'bg-red-500/20 text-red-400 border border-red-500/20',
            };
            return m[status] || 'bg-white/10 text-white/40';
        },

        itemStatusClass(status) {
            const m = {
                pending: 'bg-blue-500/20 text-blue-400',
                uploading: 'bg-yellow-500/20 text-yellow-400',
                uploaded: 'bg-green-500/20 text-green-400',
                failed: 'bg-red-500/20 text-red-400',
                skipped: 'bg-white/10 text-white/40',
                cancelled: 'bg-red-500/10 text-red-400/50',
            };
            return m[status] || 'bg-white/10 text-white/40';
        },

        formatInterval(minutes) {
            if (minutes < 60) return minutes + ' min';
            const h = Math.floor(minutes / 60);
            const m = minutes % 60;
            return m ? h + 'h ' + m + 'min' : h + 'h';
        },

        formatDate(iso) {
            if (!iso) return '';
            const d = new Date(iso);
            return d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' }) + ' ' +
                   d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
        },
    };
}
</script>
{% endblock %}
