{% extends "base.html" %}
{% block title %}Criadores - Viral Social Pro{% endblock %}
{% block nav_creators %}active{% endblock %}
{% block page_title %}Criadores{% endblock %}
{% block page_subtitle %}{{ total }} criadores encontrados{% endblock %}

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

    <!-- Stats -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 mb-6 animate-fade-up">
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center flex-shrink-0">
                    <i data-lucide="users" class="w-5 h-5 text-white"></i>
                </div>
                <div>
                    <p class="stat-number text-white">{{ total }}</p>
                    <p class="text-xs text-white/40 mt-0.5">Total</p>
                </div>
            </div>
        </div>
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center flex-shrink-0">
                    <i data-lucide="music" class="w-5 h-5 text-white"></i>
                </div>
                <div>
                    <p class="stat-number text-white">{{ creators | selectattr('platform', 'equalto', 'tiktok') | list | length }}</p>
                    <p class="text-xs text-white/40 mt-0.5">TikTok</p>
                </div>
            </div>
        </div>
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center flex-shrink-0">
                    <i data-lucide="play" class="w-5 h-5 text-white"></i>
                </div>
                <div>
                    <p class="stat-number text-white">{{ creators | selectattr('platform', 'equalto', 'youtube') | list | length }}</p>
                    <p class="text-xs text-white/40 mt-0.5">YouTube</p>
                </div>
            </div>
        </div>
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center flex-shrink-0">
                    <i data-lucide="camera" class="w-5 h-5 text-white"></i>
                </div>
                <div>
                    <p class="stat-number text-white">{{ creators | selectattr('platform', 'equalto', 'instagram') | list | length }}</p>
                    <p class="text-xs text-white/40 mt-0.5">Instagram</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="glass-card rounded-2xl p-4 mb-6 animate-fade-up-delay">
        <form method="GET" action="/creators-page" class="flex flex-wrap gap-3 items-end w-full">
            <div class="flex-1 min-w-[200px] relative">
                <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/20"></i>
                <input type="text" name="search" value="{{ search }}" placeholder="Buscar criador..."
                       class="w-full bg-dark-800/50 border border-white/5 rounded-xl pl-10 pr-4 py-3 text-sm text-white placeholder:text-white/25 outline-none focus:border-brand-500/50 transition">
            </div>
            <select name="platform" class="bg-dark-800/50 border border-white/5 rounded-xl px-4 py-3 text-sm text-white/80 outline-none focus:border-brand-500/50 transition appearance-none cursor-pointer min-w-[160px]">
                <option value="">Todas plataformas</option>
                <option value="youtube" {% if platform == 'youtube' %}selected{% endif %}>YouTube</option>
                <option value="tiktok" {% if platform == 'tiktok' %}selected{% endif %}>TikTok</option>
                <option value="instagram" {% if platform == 'instagram' %}selected{% endif %}>Instagram</option>
            </select>
            <label class="flex items-center gap-2 px-4 py-3 glass-light rounded-xl cursor-pointer">
                <input type="checkbox" name="tracked_only" value="true" {% if tracked_only %}checked{% endif %} class="rounded accent-brand-500">
                <span class="text-sm text-white/60">Monitorados</span>
            </label>
            <button type="submit" class="px-6 py-3 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition">Filtrar</button>
        </form>
    </div>

    <!-- Creators Grid -->
    {% if creators %}
    <div class="grid-cards">
        {% for c in creators %}
        <div class="glass-card rounded-2xl overflow-hidden group animate-fade-up" style="animation-delay: {{ loop.index0 * 30 }}ms">
            <!-- Header -->
            <div class="p-4 flex items-center gap-3 border-b border-white/5">
                <div class="w-12 h-12 rounded-full flex items-center justify-center text-white font-bold text-lg flex-shrink-0
                    {% if c.platform == 'youtube' %}bg-red-500{% elif c.platform == 'tiktok' %}bg-white/10{% else %}bg-gradient-to-br from-purple-500 to-pink-500{% endif %}">
                    {{ c.username[0] | upper }}
                </div>
                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2">
                        <p class="font-bold text-white/90 truncate text-sm">@{{ c.username }}</p>
                        {% if c.tracked %}
                        <span class="px-1.5 py-0.5 text-[10px] font-semibold bg-green-500/15 text-green-400 rounded border border-green-500/20">MONITORANDO</span>
                        {% endif %}
                    </div>
                    <p class="text-xs text-white/40">
                        <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide
                            {% if c.platform == 'youtube' %}badge-youtube{% elif c.platform == 'tiktok' %}badge-tiktok{% else %}badge-instagram{% endif %}">
                            {{ c.platform }}
                        </span>
                        {% if c.display_name and c.display_name != c.username %}<span class="ml-1">{{ c.display_name }}</span>{% endif %}
                    </p>
                </div>
            </div>

            <!-- Stats -->
            <div class="p-4 grid grid-cols-3 gap-2 text-center">
                <div class="glass-light rounded-lg py-2">
                    <p class="text-[10px] text-white/30 uppercase tracking-wide">Vídeos</p>
                    <p class="text-sm font-bold text-white/90">{{ c.video_count }}</p>
                </div>
                <div class="glass-light rounded-lg py-2">
                    <p class="text-[10px] text-white/30 uppercase tracking-wide">Score</p>
                    <p class="text-sm font-bold text-brand-300">{{ c.avg_viral_score }}</p>
                </div>
                <div class="glass-light rounded-lg py-2">
                    <p class="text-[10px] text-white/30 uppercase tracking-wide">Engage</p>
                    <p class="text-sm font-bold text-accent-green">{{ "%.1f"|format(c.avg_engagement) }}%</p>
                </div>
            </div>

            <!-- Best Video -->
            {% if c.best_video %}
            <div class="px-4 pb-2">
                <p class="text-[10px] text-white/30 uppercase tracking-wide mb-1">Melhor vídeo (Score {{ c.best_video.viral_score }})</p>
                <a href="{{ c.best_video.url }}" target="_blank" rel="noopener" class="text-xs text-brand-300 hover:text-brand-200 truncate block transition">
                    {{ c.best_video.title }}
                </a>
            </div>
            {% endif %}

            <!-- Actions -->
            <div class="p-4 pt-2 flex gap-2">
                <button onclick="toggleTrack({{ c.id }})"
                        class="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium rounded-xl transition
                        {% if c.tracked %}bg-green-500/15 text-green-400 hover:bg-green-500/25{% else %}glass-light text-white/60 hover:text-white/80{% endif %}">
                    <i data-lucide="{% if c.tracked %}check{% else %}plus{% endif %}" class="w-3.5 h-3.5"></i>
                    {% if c.tracked %}Monitorando{% else %}Monitorar{% endif %}
                </button>
                <button onclick="viewCreatorVideos({{ c.id }}, '{{ c.username }}')"
                        class="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium rounded-xl gradient-brand text-white hover:opacity-90 transition">
                    <i data-lucide="video" class="w-3.5 h-3.5"></i> Ver Vídeos
                </button>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}
    <div class="flex flex-col items-center justify-center py-20 text-center">
        <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
            <i data-lucide="users" class="w-10 h-10 text-white/20"></i>
        </div>
        <h3 class="text-lg font-bold text-white/60 mb-2">Nenhum criador encontrado</h3>
        <p class="text-sm text-white/30 max-w-md">Criadores são salvos automaticamente ao coletar vídeos pelo Scanner.</p>
        <a href="/viral-scanner" class="inline-block mt-4 px-6 py-2.5 rounded-xl gradient-brand text-white text-sm font-semibold">Ir ao Scanner</a>
    </div>
    {% endif %}

    <!-- Creator Videos Modal -->
    <div x-show="showVideos" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
         @click.self="showVideos = false" @keydown.escape.window="showVideos = false"
         x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
        <div class="glass rounded-2xl w-full max-w-3xl max-h-[80vh] overflow-y-auto" @click.stop>
            <div class="p-5 border-b border-white/5 flex items-center justify-between sticky top-0 glass z-10 rounded-t-2xl">
                <h2 class="text-lg font-bold text-white/90">Vídeos de <span x-text="selectedCreator" class="text-brand-300"></span></h2>
                <button @click="showVideos = false" class="p-1.5 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-5 h-5"></i></button>
            </div>
            <div class="p-5">
                <template x-if="creatorVideos.length === 0">
                    <p class="text-center text-white/40 py-8">Nenhum vídeo encontrado.</p>
                </template>
                <div class="space-y-3">
                    <template x-for="v in creatorVideos" :key="v.id">
                        <div class="flex items-center gap-3 p-3 rounded-xl glass-light hover:border-brand-500/20 transition">
                            <img :src="v.thumbnail_url" class="w-20 h-14 rounded-lg object-cover bg-dark-800"
                                 onerror="this.style.display='none'">
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-medium text-white/80 truncate" x-text="v.title"></p>
                                <div class="flex gap-3 text-xs text-white/40 mt-1">
                                    <span x-text="formatNumber(v.views) + ' views'"></span>
                                    <span class="text-brand-300" x-text="v.viral_score + ' score'"></span>
                                    <span class="text-accent-green" x-text="v.engagement_rate + '% engage'"></span>
                                </div>
                            </div>
                            <a :href="v.url" target="_blank" rel="noopener" class="px-3 py-1.5 rounded-lg text-xs font-medium text-brand-300 hover:bg-brand-500/10 transition">Abrir</a>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function creatorsApp() {
    return {
        showVideos: false,
        selectedCreator: '',
        creatorVideos: [],
    };
}

async function toggleTrack(creatorId) {
    try {
        const data = await apiCall(`/api/creators/${creatorId}/track`, 'POST');
        showToast(data.tracked ? `Monitorando @${data.username}` : `Parou de monitorar @${data.username}`, 'success');
        setTimeout(() => window.location.reload(), 500);
    } catch (e) { showToast('Erro ao monitorar criador', 'error'); }
}

async function viewCreatorVideos(creatorId, username) {
    const app = document.querySelector('[x-data]').__x.$data;
    app.selectedCreator = '@' + username;
    try {
        const data = await apiCall(`/api/creators/${creatorId}/videos`);
        app.creatorVideos = data.videos || [];
        app.showVideos = true;
    } catch (e) { showToast('Erro ao carregar videos', 'error'); }
}
</script>
{% endblock %}
