{% extends "base.html" %}
{% block title %}Transcrever Video - Viral Social Pro{% endblock %}
{% block nav_transcribe %}active{% endblock %}
{% block page_title %}Transcrever Video{% endblock %}
{% block page_subtitle %}Transcricao fiel de videos{% endblock %}

{% block content %}
<div class="p-4 md:p-6 space-y-6" x-data="transcribeApp()">

    <!-- Header + Input -->
    <div class="glass-card rounded-2xl p-6 md:p-8" style="background: linear-gradient(135deg, rgba(124,58,237,0.15) 0%, rgba(168,85,247,0.08) 100%);">
        <div class="flex items-center gap-4 mb-5">
            <div class="w-14 h-14 rounded-2xl gradient-brand flex items-center justify-center">
                <i data-lucide="file-text" class="w-7 h-7 text-white"></i>
            </div>
            <div>
                <h1 class="text-2xl md:text-3xl font-bold text-white/95">Transcrever Video</h1>
                <p class="text-sm text-white/50">Transcricao 100% fiel ao audio do video</p>
            </div>
        </div>

        <!-- Mode Tabs -->
        <div class="flex items-center gap-1 bg-white/5 rounded-xl p-1 mb-5 w-fit">
            <button @click="mode = 'url'" class="px-4 py-2 rounded-lg text-sm font-medium transition flex items-center gap-2"
                :class="mode === 'url' ? 'bg-emerald-500 text-white' : 'text-white/40 hover:text-white/60'">
                <i data-lucide="link" class="w-4 h-4"></i> Por Link
                <span class="px-1.5 py-0.5 rounded text-[9px] font-bold bg-emerald-500/30 text-emerald-300">GRATIS</span>
            </button>
            <button @click="mode = 'upload'" class="px-4 py-2 rounded-lg text-sm font-medium transition flex items-center gap-2"
                :class="mode === 'upload' ? 'bg-emerald-500 text-white' : 'text-white/40 hover:text-white/60'">
                <i data-lucide="upload" class="w-4 h-4"></i> Upload Arquivo
                <span class="px-1.5 py-0.5 rounded text-[9px] font-bold bg-emerald-500/30 text-emerald-300">GRATIS</span>
            </button>
        </div>

        <!-- URL Mode -->
        <div x-show="mode === 'url'" x-transition>
            <div class="flex flex-col md:flex-row gap-3">
                <div class="flex-1 relative">
                    <i data-lucide="link" class="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-white/30"></i>
                    <input type="text" x-model="videoUrl" @keyup.enter="transcribeFromUrl()"
                        placeholder="Cole o link do video (YouTube, TikTok ou Instagram)..."
                        class="w-full bg-dark-700/80 border border-white/10 rounded-xl pl-12 pr-4 py-3.5 text-sm text-white/90 placeholder:text-white/25 focus:border-brand-500 focus:ring-1 focus:ring-brand-500/30 outline-none transition">
                </div>
                <button @click="transcribeFromUrl()" :disabled="loading || !videoUrl.trim()"
                    class="px-8 py-3.5 rounded-xl text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-40 flex items-center justify-center gap-2 whitespace-nowrap"
                    style="background: linear-gradient(135deg, #10b981, #059669);">
                    <template x-if="!loading"><span class="flex items-center gap-2"><i data-lucide="cpu" class="w-4 h-4"></i> Transcrever com IA</span></template>
                    <template x-if="loading"><span class="flex items-center gap-2"><div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div> Baixando e transcrevendo...</span></template>
                </button>
            </div>
            <div class="flex items-center gap-3 mt-3 flex-wrap">
                <span class="px-3 py-1 rounded-lg text-[10px] font-bold bg-red-500/20 text-red-400 flex items-center gap-1.5"><i data-lucide="youtube" class="w-3 h-3"></i> YouTube</span>
                <span class="px-3 py-1 rounded-lg text-[10px] font-bold bg-pink-500/20 text-pink-400 flex items-center gap-1.5"><i data-lucide="music" class="w-3 h-3"></i> TikTok</span>
                <span class="px-3 py-1 rounded-lg text-[10px] font-bold bg-purple-500/20 text-purple-400 flex items-center gap-1.5"><i data-lucide="instagram" class="w-3 h-3"></i> Instagram</span>
                <span class="px-2.5 py-1 rounded-lg text-[10px] font-bold bg-emerald-500/20 text-emerald-400">Whisper IA Local - 0 creditos</span>
            </div>
            <!-- Language selector -->
            <div class="flex items-center gap-3 mt-3">
                <span class="text-[10px] text-white/40">Idioma:</span>
                <select x-model="urlLang" class="bg-dark-700/80 border border-white/10 rounded-lg px-2 py-1.5 text-xs text-white/70 outline-none focus:border-emerald-500">
                    <option value="">Detectar automatico</option>
                    <option value="pt">Portugues</option>
                    <option value="en">Ingles</option>
                    <option value="es">Espanhol</option>
                </select>
            </div>
        </div>

        <!-- Upload Mode -->
        <div x-show="mode === 'upload'" x-transition>
            <div class="border-2 border-dashed rounded-xl p-8 text-center transition cursor-pointer"
                 :class="dragOver ? 'border-emerald-400 bg-emerald-500/10' : 'border-white/10 hover:border-white/20'"
                 @dragover.prevent="dragOver = true"
                 @dragleave.prevent="dragOver = false"
                 @drop.prevent="dragOver = false; handleDrop($event)"
                 @click="$refs.fileInput.click()">
                <input type="file" x-ref="fileInput" class="hidden"
                    accept=".mp4,.mp3,.wav,.webm,.m4a,.ogg,.aac,.flac,.mkv,.mov"
                    @change="handleFileSelect($event)">
                <div x-show="!selectedFile">
                    <i data-lucide="upload-cloud" class="w-12 h-12 text-white/20 mx-auto mb-3"></i>
                    <p class="text-sm text-white/50 mb-1">Arraste um arquivo de video/audio ou clique para selecionar</p>
                    <p class="text-[10px] text-white/30">MP4, MP3, WAV, WebM, M4A, OGG, AAC, FLAC, MKV, MOV (max 100MB)</p>
                </div>
                <div x-show="selectedFile" class="flex items-center justify-center gap-3">
                    <i data-lucide="file-audio" class="w-8 h-8 text-emerald-400"></i>
                    <div class="text-left">
                        <p class="text-sm font-medium text-white/80" x-text="selectedFile?.name"></p>
                        <p class="text-[10px] text-white/40" x-text="selectedFile ? (selectedFile.size / 1024 / 1024).toFixed(1) + ' MB' : ''"></p>
                    </div>
                    <button @click.stop="selectedFile = null; $refs.fileInput.value = ''" class="p-1 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-4 h-4 text-white/40"></i></button>
                </div>
            </div>

            <!-- Language selector + Transcribe button -->
            <div class="flex items-center gap-3 mt-4">
                <select x-model="uploadLang" class="bg-dark-700/80 border border-white/10 rounded-xl px-3 py-2.5 text-sm text-white/70 outline-none focus:border-emerald-500">
                    <option value="">Detectar idioma</option>
                    <option value="pt">Portugues</option>
                    <option value="en">Ingles</option>
                    <option value="es">Espanhol</option>
                    <option value="fr">Frances</option>
                    <option value="de">Alemao</option>
                    <option value="ja">Japones</option>
                    <option value="ko">Coreano</option>
                    <option value="zh">Chines</option>
                </select>
                <button @click="transcribeUpload()" :disabled="loading || !selectedFile"
                    class="px-8 py-2.5 rounded-xl text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-40 flex items-center justify-center gap-2"
                    style="background: linear-gradient(135deg, #10b981, #059669);">
                    <template x-if="!loading"><span class="flex items-center gap-2"><i data-lucide="cpu" class="w-4 h-4"></i> Transcrever com Whisper</span></template>
                    <template x-if="loading"><span class="flex items-center gap-2"><div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div> Processando...</span></template>
                </button>
                <span class="px-2.5 py-1 rounded-lg text-[10px] font-bold bg-emerald-500/20 text-emerald-400">100% Gratis - IA Local</span>
            </div>
        </div>
    </div>

    <!-- Progress bar -->
    <div x-show="loading" x-cloak class="glass-card rounded-xl p-4">
        <div class="flex items-center gap-3 mb-2">
            <div class="w-5 h-5 border-2 border-emerald-400 border-t-transparent rounded-full animate-spin"></div>
            <span class="text-sm text-white/70" x-text="uploadProgress"></span>
        </div>
        <div class="w-full bg-dark-700 rounded-full h-1.5">
            <div class="bg-emerald-500 h-1.5 rounded-full transition-all duration-1000" :style="'width:' + uploadPercent + '%'"></div>
        </div>
    </div>

    <!-- Error -->
    <div x-show="error" x-cloak class="glass-card rounded-xl p-4 border border-red-500/30">
        <div class="flex items-center gap-3">
            <i data-lucide="alert-circle" class="w-5 h-5 text-red-400 flex-shrink-0"></i>
            <p class="text-sm text-red-300" x-text="error"></p>
        </div>
    </div>

    <!-- Result -->
    <div x-show="result" x-cloak class="space-y-4">
        <!-- Info Bar -->
        <div class="glass-card rounded-xl p-4">
            <div class="flex items-center justify-between flex-wrap gap-3">
                <div class="flex items-center gap-3 min-w-0">
                    <span x-show="detectedPlatform" class="px-2.5 py-1 rounded-lg text-[10px] font-bold uppercase"
                        :class="{'bg-red-500/20 text-red-400': detectedPlatform==='youtube', 'bg-pink-500/20 text-pink-400': detectedPlatform==='tiktok', 'bg-purple-500/20 text-purple-400': detectedPlatform==='instagram', 'bg-emerald-500/20 text-emerald-400': detectedPlatform==='whisper'}"
                        x-text="detectedPlatform"></span>
                    <span x-show="result?.language" class="px-2 py-0.5 rounded-lg text-[10px] font-medium glass-light text-white/60" x-text="'Idioma: ' + result?.language"></span>
                    <span x-show="result?.processing_time" class="px-2 py-0.5 rounded-lg text-[10px] font-medium glass-light text-white/40" x-text="result?.processing_time + 's processamento'"></span>
                    <span x-show="result?.duration" class="px-2 py-0.5 rounded-lg text-[10px] font-medium glass-light text-white/40" x-text="formatTime(result?.duration) + ' duracao'"></span>
                    <span class="text-xs text-white/40 truncate" x-text="lastUrl || lastFilename"></span>
                </div>
                <div class="flex items-center gap-2">
                    <button @click="copyTranscript()" class="px-3 py-1.5 rounded-lg glass-card text-white/70 text-xs font-medium hover:text-white transition flex items-center gap-1.5"><i data-lucide="copy" class="w-3.5 h-3.5"></i> Copiar</button>
                    <button @click="downloadTxt()" class="px-3 py-1.5 rounded-lg glass-card text-white/70 text-xs font-medium hover:text-white transition flex items-center gap-1.5"><i data-lucide="download" class="w-3.5 h-3.5"></i> .txt</button>
                    <button @click="clearResult()" class="px-3 py-1.5 rounded-lg glass-card text-red-400/70 text-xs font-medium hover:text-red-400 transition flex items-center gap-1.5"><i data-lucide="x" class="w-3.5 h-3.5"></i></button>
                </div>
            </div>
        </div>

        <!-- Transcript Content -->
        <div class="glass-card rounded-xl p-5 md:p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-sm font-bold text-white/80 flex items-center gap-2"><i data-lucide="file-text" class="w-4 h-4 text-brand-400"></i> Transcricao</h3>
                <div class="flex items-center gap-3">
                    <div class="flex items-center gap-1 bg-white/5 rounded-lg p-0.5">
                        <button @click="showTimestamps = true" class="px-2.5 py-1 rounded-md text-[10px] font-medium transition" :class="showTimestamps ? 'bg-brand-500 text-white' : 'text-white/40 hover:text-white/60'">Com Tempo</button>
                        <button @click="showTimestamps = false" class="px-2.5 py-1 rounded-md text-[10px] font-medium transition" :class="!showTimestamps ? 'bg-brand-500 text-white' : 'text-white/40 hover:text-white/60'">Texto Limpo</button>
                    </div>
                    <span class="text-[10px] text-white/30" x-text="wordCount + ' palavras'"></span>
                </div>
            </div>
            <div x-show="showTimestamps && hasTimestamps" class="space-y-1 max-h-[60vh] overflow-y-auto pr-2 custom-scroll">
                <template x-for="(seg, i) in segments" :key="i">
                    <div class="flex gap-3 py-1.5 px-2 rounded-lg hover:bg-white/5 transition">
                        <span class="text-[11px] font-mono text-brand-400/70 flex-shrink-0 pt-0.5 w-16 text-right" x-text="seg.timeText || formatTime(seg.start)"></span>
                        <p class="text-sm text-white/80 leading-relaxed" x-text="seg.text"></p>
                    </div>
                </template>
            </div>
            <div x-show="!showTimestamps || !hasTimestamps" class="max-h-[60vh] overflow-y-auto pr-2 custom-scroll">
                <p class="text-sm text-white/80 leading-relaxed whitespace-pre-wrap" x-text="cleanText"></p>
            </div>
        </div>
    </div>

    <!-- Empty state -->
    <div x-show="!result && !loading && !error" class="glass-card rounded-2xl p-12 text-center">
        <div class="w-20 h-20 rounded-2xl gradient-brand flex items-center justify-center mx-auto mb-5 opacity-50">
            <i data-lucide="file-text" class="w-10 h-10 text-white"></i>
        </div>
        <h3 class="text-lg font-bold text-white/60 mb-2" x-text="mode === 'url' ? 'Cole um link para comecar' : 'Faca upload de um arquivo'"></h3>
        <p class="text-sm text-white/30 max-w-md mx-auto" x-text="mode === 'url' ? 'Suporta YouTube, TikTok e Instagram. Whisper IA local, 100% gratis.' : 'Envie um video ou audio. Whisper transcreve localmente, 100% gratis.'"></p>
    </div>
</div>

<style>
.custom-scroll::-webkit-scrollbar { width: 4px; }
.custom-scroll::-webkit-scrollbar-track { background: transparent; }
.custom-scroll::-webkit-scrollbar-thumb { background: rgba(124,58,237,0.3); border-radius: 4px; }
.custom-scroll::-webkit-scrollbar-thumb:hover { background: rgba(124,58,237,0.5); }
</style>

<script>
function transcribeApp() {
    return {
        mode: 'url',
        videoUrl: '',
        selectedFile: null,
        uploadLang: '',
        urlLang: '',
        loading: false,
        error: null,
        result: null,
        lastUrl: '',
        lastFilename: '',
        detectedPlatform: '',
        showTimestamps: true,
        segments: [],
        cleanText: '',
        hasTimestamps: false,
        wordCount: 0,
        dragOver: false,
        uploadProgress: 'Enviando arquivo...',
        uploadPercent: 10,
        history: [],
        currentHistoryIndex: -1,

        handleFileSelect(e) {
            const file = e.target.files[0];
            if (file) this.selectedFile = file;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        handleDrop(e) {
            const file = e.dataTransfer.files[0];
            if (file) this.selectedFile = file;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async transcribeFromUrl() {
            const url = this.videoUrl.trim();
            if (!url) return;
            this.loading = true;
            this.error = null;
            this.result = null;
            this.uploadProgress = 'Baixando audio do video...';
            this.uploadPercent = 10;
            try {
                let apiUrl = `/api/transcript/whisper?url=${encodeURIComponent(url)}`;
                if (this.urlLang) apiUrl += `&language=${encodeURIComponent(this.urlLang)}`;

                this.uploadPercent = 20;
                this.uploadProgress = 'Baixando audio do video...';

                const r = await fetch(apiUrl);

                this.uploadPercent = 80;
                this.uploadProgress = 'Transcrevendo com Whisper IA...';

                const data = await r.json();
                if (!r.ok) throw new Error(data.detail || 'Erro ao transcrever');

                this.uploadPercent = 100;
                this.uploadProgress = 'Concluido!';
                this.result = data;
                this.lastUrl = url;
                this.lastFilename = '';
                this.detectedPlatform = data.platform || this.detectPlatform(url);
                this.processResult(data);
                this.history.push({ url, platform: this.detectedPlatform, data });
                this.currentHistoryIndex = this.history.length - 1;
            } catch (e) {
                this.error = e.message || 'Erro ao transcrever o video';
            }
            this.loading = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async transcribeUrl() {
            const url = this.videoUrl.trim();
            if (!url) return;
            this.loading = true;
            this.error = null;
            this.result = null;
            try {
                const r = await fetch(`/api/transcript?url=${encodeURIComponent(url)}`);
                const data = await r.json();
                if (!r.ok) throw new Error(data.detail || 'Erro ao transcrever');
                this.result = data;
                this.lastUrl = url;
                this.lastFilename = '';
                this.detectedPlatform = this.detectPlatform(url);
                this.processResult(data);
                this.history.push({ url, platform: this.detectedPlatform, data });
                this.currentHistoryIndex = this.history.length - 1;
            } catch (e) {
                this.error = e.message || 'Erro ao transcrever o video';
            }
            this.loading = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async transcribeUpload() {
            if (!this.selectedFile) return;
            this.loading = true;
            this.error = null;
            this.result = null;
            this.uploadProgress = 'Enviando arquivo...';
            this.uploadPercent = 10;

            try {
                const formData = new FormData();
                formData.append('file', this.selectedFile);
                if (this.uploadLang) formData.append('language', this.uploadLang);

                this.uploadPercent = 30;
                this.uploadProgress = 'Processando com Whisper IA...';

                const r = await fetch('/api/transcript/upload', { method: 'POST', body: formData });

                this.uploadPercent = 90;
                const data = await r.json();
                if (!r.ok) throw new Error(data.detail || 'Erro ao transcrever');

                this.uploadPercent = 100;
                this.result = data;
                this.lastUrl = '';
                this.lastFilename = this.selectedFile.name;
                this.detectedPlatform = 'whisper';
                this.processResult(data);
                this.history.push({ url: this.selectedFile.name, platform: 'whisper', data });
                this.currentHistoryIndex = this.history.length - 1;
            } catch (e) {
                this.error = e.message || 'Erro ao transcrever o arquivo';
            }
            this.loading = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        processResult(data) {
            const transcript = data.transcript || data.transcript_text || data.text || '';
            if (Array.isArray(transcript)) {
                this.segments = transcript.map(s => ({
                    text: (s.text || s.content || '').trim(),
                    start: s.start || (s.startMs ? parseFloat(s.startMs) / 1000 : 0) || s.offset || 0,
                    end: s.end || 0,
                    timeText: s.startTimeText || '',
                })).filter(s => s.text.length > 0);
                this.hasTimestamps = this.segments.length > 0;
                this.cleanText = this.segments.map(s => s.text).join(' ');
                this.showTimestamps = true;
            } else if (typeof transcript === 'string' && transcript.length > 0) {
                this.cleanText = transcript;
                this.segments = [];
                this.hasTimestamps = false;
                this.showTimestamps = false;
            } else {
                this.cleanText = data.transcript_text || data.transcript_only_text || JSON.stringify(data, null, 2);
                this.segments = [];
                this.hasTimestamps = false;
                this.showTimestamps = false;
            }
            this.wordCount = this.cleanText.split(/\s+/).filter(w => w.length > 0).length;
        },

        detectPlatform(url) {
            if (url.includes('tiktok.com')) return 'tiktok';
            if (url.includes('instagram.com')) return 'instagram';
            if (url.includes('youtube.com') || url.includes('youtu.be')) return 'youtube';
            return 'unknown';
        },

        formatTime(seconds) {
            if (!seconds && seconds !== 0) return '';
            const s = Math.floor(seconds);
            const m = Math.floor(s / 60);
            const sec = s % 60;
            if (m >= 60) { const h = Math.floor(m / 60); return `${h}:${String(m%60).padStart(2,'0')}:${String(sec).padStart(2,'0')}`; }
            return `${m}:${String(sec).padStart(2,'0')}`;
        },

        async copyTranscript() {
            const text = this.showTimestamps && this.hasTimestamps
                ? this.segments.map(s => `[${s.timeText || this.formatTime(s.start)}] ${s.text}`).join('\n')
                : this.cleanText;
            try { await navigator.clipboard.writeText(text); showToast('Transcricao copiada!', 'success'); }
            catch { const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); showToast('Copiado!', 'success'); }
        },

        downloadTxt() {
            const text = this.showTimestamps && this.hasTimestamps
                ? this.segments.map(s => `[${s.timeText || this.formatTime(s.start)}] ${s.text}`).join('\n')
                : this.cleanText;
            const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
            const a = document.createElement('a'); a.href = URL.createObjectURL(blob);
            a.download = `transcricao_${this.detectedPlatform}_${Date.now()}.txt`;
            a.click(); URL.revokeObjectURL(a.href);
            showToast('Arquivo baixado!', 'success');
        },

        clearResult() {
            this.result = null; this.error = null; this.segments = []; this.cleanText = '';
            this.videoUrl = ''; this.selectedFile = null;
            if (this.$refs.fileInput) this.$refs.fileInput.value = '';
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        loadFromHistory(index) {
            this.currentHistoryIndex = index;
            const item = this.history[index];
            this.lastUrl = item.platform === 'whisper' ? '' : item.url;
            this.lastFilename = item.platform === 'whisper' ? item.url : '';
            this.detectedPlatform = item.platform;
            this.result = item.data;
            this.processResult(item.data);
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },
    }
}
</script>
{% endblock %}
