{% extends "base.html" %}
{% block title %}Perfil TikTok - Viral Social Pro{% endblock %}
{% block nav_tiktok_profile %}active{% endblock %}
{% block page_title %}Perfil TikTok{% endblock %}
{% block page_subtitle %}Top 50 videos mais virais de um perfil{% endblock %}

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

    <!-- Header -->
    <div class="glass-card rounded-2xl p-6 gradient-bg">
        <div class="flex items-center gap-4 mb-6">
            <div class="w-12 h-12 rounded-2xl gradient-brand flex items-center justify-center flex-shrink-0">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="white" xmlns="http://www.w3.org/2000/svg">
                    <path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-2.88 2.5 2.89 2.89 0 0 1-2.89-2.89 2.89 2.89 0 0 1 2.89-2.89c.28 0 .54.04.79.1V9.01a6.31 6.31 0 0 0-.79-.05 6.34 6.34 0 0 0-6.34 6.34 6.34 6.34 0 0 0 6.34 6.34 6.34 6.34 0 0 0 6.33-6.34V8.69a8.18 8.18 0 0 0 4.78 1.52V6.76a4.85 4.85 0 0 1-1.01-.07z"/>
                </svg>
            </div>
            <div>
                <h1 class="text-2xl font-bold">Perfil TikTok Viral</h1>
                <p class="text-white/50 text-sm">Insira um perfil e veja os 50 vídeos mais viralizados, ordenados por visualizações</p>
            </div>
        </div>

        <!-- Search form -->
        <div class="flex gap-3">
            <div class="flex-1 relative">
                <span class="absolute left-4 top-1/2 -translate-y-1/2 text-white/40 font-semibold text-sm">@</span>
                <input
                    x-model="username"
                    @keydown.enter="search()"
                    type="text"
                    placeholder="nome_do_perfil"
                    class="w-full pl-9 pr-4 py-3 rounded-xl bg-white/5 border border-white/10 text-white placeholder-white/30 focus:outline-none focus:border-brand-400 focus:bg-white/8 transition text-sm"
                    :disabled="loading"
                >
            </div>
            <button
                @click="search()"
                :disabled="loading || !username.trim()"
                class="px-6 py-3 rounded-xl gradient-brand text-white font-semibold text-sm transition hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-2 flex-shrink-0"
            >
                <template x-if="!loading">
                    <span class="flex items-center gap-2">
                        <i data-lucide="search" class="w-4 h-4"></i>
                        Buscar
                    </span>
                </template>
                <template x-if="loading">
                    <span class="flex items-center gap-2">
                        <svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                        </svg>
                        Buscando...
                    </span>
                </template>
            </button>
        </div>

        <!-- Error message -->
        <div x-show="error" x-cloak class="mt-3 p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 text-sm" x-text="error"></div>
    </div>

    <!-- Results header -->
    <div x-show="videos.length > 0" x-cloak class="flex items-center justify-between">
        <div>
            <h2 class="text-lg font-bold">
                <span class="text-white/60">@</span><span x-text="searchedUsername" class="text-gradient"></span>
            </h2>
            <p class="text-white/40 text-sm"><span x-text="videos.length"></span> vídeos encontrados · ordenados por visualizações</p>
        </div>
        <div class="text-xs text-white/30 bg-white/5 px-3 py-1.5 rounded-xl border border-white/5">
            <i data-lucide="sort-desc" class="w-3 h-3 inline mr-1"></i>
            Mais virais primeiro
        </div>
    </div>

    <!-- Loading skeleton -->
    <div x-show="loading" x-cloak class="grid-cards">
        <template x-for="i in 12" :key="i">
            <div class="glass-card rounded-2xl overflow-hidden">
                <div class="skeleton h-44 w-full"></div>
                <div class="p-4 space-y-2">
                    <div class="skeleton h-4 w-full rounded"></div>
                    <div class="skeleton h-4 w-2/3 rounded"></div>
                    <div class="skeleton h-8 w-full rounded-lg mt-3"></div>
                </div>
            </div>
        </template>
    </div>

    <!-- Videos grid -->
    <div x-show="!loading && videos.length > 0" x-cloak class="grid-cards">
        <template x-for="(video, index) in videos" :key="video.external_id || index">
            <div class="glass-card rounded-2xl overflow-hidden animate-fade-up" :style="`animation-delay: ${Math.min(index * 20, 400)}ms`">

                <!-- Rank badge + Thumbnail -->
                <div class="relative">
                    <div class="absolute top-2 left-2 z-10 w-7 h-7 rounded-lg flex items-center justify-center text-xs font-bold"
                         :class="index === 0 ? 'bg-yellow-400 text-black' : index === 1 ? 'bg-gray-300 text-black' : index === 2 ? 'bg-amber-600 text-white' : 'bg-black/60 text-white border border-white/20'"
                         x-text="index + 1">
                    </div>
                    <template x-if="video.thumbnail_url">
                        <img :src="video.thumbnail_url" :alt="video.title" class="w-full h-44 object-cover" loading="lazy" @error="$el.style.display='none'">
                    </template>
                    <template x-if="!video.thumbnail_url">
                        <div class="w-full h-44 bg-white/5 flex items-center justify-center">
                            <svg width="32" height="32" viewBox="0 0 24 24" fill="rgba(255,255,255,0.2)" xmlns="http://www.w3.org/2000/svg">
                                <path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-2.88 2.5 2.89 2.89 0 0 1-2.89-2.89 2.89 2.89 0 0 1 2.89-2.89c.28 0 .54.04.79.1V9.01a6.31 6.31 0 0 0-.79-.05 6.34 6.34 0 0 0-6.34 6.34 6.34 6.34 0 0 0 6.34 6.34 6.34 6.34 0 0 0 6.33-6.34V8.69a8.18 8.18 0 0 0 4.78 1.52V6.76a4.85 4.85 0 0 1-1.01-.07z"/>
                            </svg>
                        </div>
                    </template>
                    <!-- Views overlay -->
                    <div class="absolute bottom-2 right-2 bg-black/70 backdrop-blur-sm text-white text-xs font-bold px-2 py-1 rounded-lg flex items-center gap-1">
                        <i data-lucide="eye" class="w-3 h-3"></i>
                        <span x-text="formatNumber(video.views)"></span>
                    </div>
                </div>

                <!-- Content -->
                <div class="p-4 space-y-3">
                    <!-- Title -->
                    <p class="text-sm text-white/80 leading-snug line-clamp-2" x-text="video.title || '(sem título)'"></p>

                    <!-- Metrics -->
                    <div class="flex items-center gap-3 text-xs text-white/40">
                        <span class="flex items-center gap-1">
                            <i data-lucide="heart" class="w-3 h-3 text-accent-pink"></i>
                            <span x-text="formatNumber(video.likes)"></span>
                        </span>
                        <span class="flex items-center gap-1">
                            <i data-lucide="message-circle" class="w-3 h-3 text-brand-300"></i>
                            <span x-text="formatNumber(video.comments)"></span>
                        </span>
                        <span class="flex items-center gap-1">
                            <i data-lucide="share-2" class="w-3 h-3 text-accent-cyan"></i>
                            <span x-text="formatNumber(video.shares)"></span>
                        </span>
                        <template x-if="video.duration">
                            <span class="flex items-center gap-1 ml-auto">
                                <i data-lucide="clock" class="w-3 h-3"></i>
                                <span x-text="formatDuration(video.duration)"></span>
                            </span>
                        </template>
                    </div>

                    <!-- Engagement rate -->
                    <template x-if="video.views > 0 && (video.likes + video.comments) > 0">
                        <div class="text-xs text-white/30">
                            Eng: <span class="text-brand-300 font-semibold" x-text="calcEngagement(video) + '%'"></span>
                        </div>
                    </template>

                    <!-- Actions -->
                    <div class="flex gap-2 pt-1">
                        <a :href="video.url" target="_blank" rel="noopener"
                           class="flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg bg-white/5 hover:bg-white/10 text-white/60 hover:text-white text-xs font-medium transition border border-white/5 hover:border-white/15">
                            <i data-lucide="external-link" class="w-3.5 h-3.5"></i>
                            Ver vídeo
                        </a>
                        <button
                            @click="downloadTranscript(video, $el)"
                            class="flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg gradient-brand text-white text-xs font-semibold transition hover:opacity-90 disabled:opacity-40"
                            :id="`btn-${video.external_id || index}`"
                        >
                            <i data-lucide="file-text" class="w-3.5 h-3.5"></i>
                            Baixar Transcrição
                        </button>
                    </div>
                </div>
            </div>
        </template>
    </div>

    <!-- Empty state -->
    <div x-show="!loading && searched && videos.length === 0" x-cloak class="glass-card rounded-2xl p-12 text-center">
        <div class="w-16 h-16 rounded-2xl bg-white/5 flex items-center justify-center mx-auto mb-4">
            <i data-lucide="search-x" class="w-8 h-8 text-white/20"></i>
        </div>
        <h3 class="text-lg font-semibold text-white/70 mb-2">Nenhum vídeo encontrado</h3>
        <p class="text-white/30 text-sm">Verifique se o nome do perfil está correto e tente novamente.</p>
    </div>

    <!-- Transcript modal -->
    <div x-show="transcriptData" x-cloak
         class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm"
         @click.self="transcriptData = null">
        <div class="glass w-full max-w-2xl max-h-[80vh] rounded-2xl flex flex-col" @click.stop>
            <div class="flex items-center justify-between p-5 border-b border-white/10">
                <div>
                    <h3 class="font-bold">Transcrição</h3>
                    <p class="text-xs text-white/40 mt-0.5" x-text="transcriptData?.title"></p>
                </div>
                <div class="flex items-center gap-2">
                    <button @click="downloadTxt()" class="px-4 py-2 rounded-xl gradient-brand text-white text-xs font-semibold hover:opacity-90 transition flex items-center gap-1.5">
                        <i data-lucide="download" class="w-3.5 h-3.5"></i>
                        Baixar .txt
                    </button>
                    <button @click="transcriptData = null" class="w-8 h-8 rounded-xl bg-white/5 hover:bg-white/10 flex items-center justify-center transition">
                        <i data-lucide="x" class="w-4 h-4"></i>
                    </button>
                </div>
            </div>
            <div class="flex-1 overflow-y-auto p-5">
                <p class="text-sm text-white/70 leading-relaxed whitespace-pre-wrap" x-text="transcriptData?.text"></p>
            </div>
            <div class="p-4 border-t border-white/10 flex items-center gap-4 text-xs text-white/30">
                <span x-show="transcriptData?.language">Idioma: <span class="text-white/50" x-text="transcriptData?.language"></span></span>
                <span x-show="transcriptData?.word_count">Palavras: <span class="text-white/50" x-text="transcriptData?.word_count"></span></span>
                <span x-show="transcriptData?.duration">Duração: <span class="text-white/50" x-text="transcriptData?.duration + 's'"></span></span>
            </div>
        </div>
    </div>

</div>

<script>
function tiktokProfile() {
    return {
        username: '',
        searchedUsername: '',
        videos: [],
        loading: false,
        searched: false,
        error: null,
        transcriptData: null,

        async search() {
            const u = this.username.trim().replace(/^@/, '');
            if (!u) return;
            this.loading = true;
            this.error = null;
            this.videos = [];
            this.searched = false;

            try {
                const res = await fetch('/api/tiktok/profile-videos', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username: u })
                });
                const data = await res.json();
                if (!res.ok) {
                    this.error = data.detail || 'Erro ao buscar perfil';
                } else if (data.error) {
                    this.error = data.error;
                } else {
                    this.videos = data.videos || [];
                    this.searchedUsername = data.username;
                    this.searched = true;
                }
            } catch (e) {
                this.error = 'Erro de conexão. Tente novamente.';
            } finally {
                this.loading = false;
                this.$nextTick(() => lucide.createIcons());
            }
        },

        async downloadTranscript(video, btn) {
            if (!video.url) return;
            const original = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<svg class="w-3.5 h-3.5 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg> Transcrevendo...';

            try {
                const url = `/api/transcript/whisper?url=${encodeURIComponent(video.url)}`;
                const res = await fetch(url);
                const data = await res.json();

                if (!res.ok || !data.transcript_text) {
                    showToast('Erro: ' + (data.detail || data.error || 'Não foi possível transcrever'), 'error');
                    return;
                }

                this.transcriptData = {
                    title: video.title || video.external_id,
                    text: data.transcript_text,
                    language: data.language,
                    word_count: data.word_count,
                    duration: data.duration,
                    url: video.url,
                };

                this.$nextTick(() => lucide.createIcons());
            } catch (e) {
                showToast('Erro de conexão ao transcrever', 'error');
            } finally {
                btn.disabled = false;
                btn.innerHTML = original;
            }
        },

        downloadTxt() {
            if (!this.transcriptData) return;
            const blob = new Blob([this.transcriptData.text], { type: 'text/plain;charset=utf-8' });
            const a = document.createElement('a');
            a.href = URL.createObjectURL(blob);
            const filename = (this.transcriptData.title || 'transcricao').slice(0, 60).replace(/[^\w\s-]/g, '').trim().replace(/\s+/g, '_');
            a.download = filename + '.txt';
            a.click();
            URL.revokeObjectURL(a.href);
        },

        formatNumber(n) {
            if (!n) return '0';
            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 String(n);
        },

        formatDuration(s) {
            if (!s) return '';
            const m = Math.floor(s / 60);
            const sec = s % 60;
            return m + ':' + String(sec).padStart(2, '0');
        },

        calcEngagement(v) {
            if (!v.views || v.views === 0) return '0.0';
            const eng = ((v.likes + v.comments + v.shares) / v.views) * 100;
            return eng.toFixed(1);
        }
    }
}

function showToast(msg, type = 'info') {
    const container = document.getElementById('toastContainer');
    if (!container) return;
    const colors = { info: 'rgba(124,58,237,0.9)', error: 'rgba(239,68,68,0.9)', success: 'rgba(16,185,129,0.9)' };
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.style.background = colors[type] || colors.info;
    toast.textContent = msg;
    container.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
}
</script>
{% endblock %}
