{% extends "base.html" %}
{% block title %}Banco de Ideias - Viral Social Pro{% endblock %}
{% block nav_ideas %}active{% endblock %}
{% block mnav_ideas %}active{% endblock %}
{% block page_title %}Banco de Ideias{% endblock %}
{% block page_subtitle %}Organize suas inspiracoes para criar conteudo{% endblock %}

{% block content %}
<div x-data="ideasApp()" x-init="loadIdeas()" class="space-y-6 animate-fade-up">

    <!-- Stats -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div class="glass-card rounded-2xl p-4 text-center">
            <p class="stat-number text-brand-400" x-text="stats.idea"></p>
            <p class="text-xs text-white/40 mt-1">Ideias</p>
        </div>
        <div class="glass-card rounded-2xl p-4 text-center">
            <p class="stat-number text-accent-cyan" x-text="stats.script"></p>
            <p class="text-xs text-white/40 mt-1">Em Roteiro</p>
        </div>
        <div class="glass-card rounded-2xl p-4 text-center">
            <p class="stat-number text-accent-orange" x-text="stats.production"></p>
            <p class="text-xs text-white/40 mt-1">Em Producao</p>
        </div>
        <div class="glass-card rounded-2xl p-4 text-center">
            <p class="stat-number text-accent-green" x-text="stats.published"></p>
            <p class="text-xs text-white/40 mt-1">Publicados</p>
        </div>
    </div>

    <!-- Kanban Board -->
    <div class="flex gap-4 overflow-x-auto pb-4" style="scroll-snap-type: x mandatory;">
        <template x-for="column in columns" :key="column.id">
            <div class="flex-shrink-0 w-80 md:w-[320px]" style="scroll-snap-align: start;">
                <div class="flex items-center gap-2 mb-3 px-1">
                    <div class="w-3 h-3 rounded-full" :style="'background:'+column.color"></div>
                    <h3 class="text-sm font-bold text-white/80" x-text="column.title"></h3>
                    <span class="text-xs text-white/30 ml-auto" x-text="getColumnIdeas(column.id).length"></span>
                </div>
                <div class="space-y-3 min-h-[200px]">
                    <template x-for="idea in getColumnIdeas(column.id)" :key="idea.id">
                        <div class="glass-card rounded-xl p-4 cursor-pointer" @click="editIdea(idea)">
                            <!-- Thumbnail -->
                            <div x-show="idea.thumbnail_url" class="rounded-lg overflow-hidden mb-3 aspect-video bg-dark-800">
                                <img :src="idea.thumbnail_url" class="w-full h-full object-cover" loading="lazy" onerror="this.parentElement.style.display='none'">
                            </div>
                            <!-- Platform badge -->
                            <div class="flex items-center gap-2 mb-2">
                                <span class="px-1.5 py-0.5 rounded text-[9px] font-bold uppercase" :class="'badge-'+(idea.platform||'')">
                                    <span x-text="idea.platform || 'geral'"></span>
                                </span>
                                <span class="text-[10px] text-white/20" x-text="timeAgo(idea.created_at)"></span>
                            </div>
                            <h4 class="text-sm font-semibold text-white/90 line-clamp-2 mb-2" x-text="idea.title"></h4>
                            <p x-show="idea.notes" class="text-xs text-white/40 line-clamp-2 mb-3" x-text="idea.notes"></p>
                            <!-- Actions -->
                            <div class="flex items-center gap-2">
                                <template x-for="nextCol in getNextColumns(column.id)">
                                    <button @click.stop="moveIdea(idea.id, nextCol.id)"
                                            class="px-2 py-1 rounded-lg text-[10px] font-medium glass-light hover:bg-white/10 transition"
                                            :style="'color:'+nextCol.color" x-text="nextCol.short">
                                    </button>
                                </template>
                                <a x-show="idea.url" :href="idea.url" target="_blank" @click.stop
                                   class="px-2 py-1 rounded-lg text-[10px] font-medium glass-light hover:bg-white/10 text-brand-300 ml-auto">
                                    Abrir
                                </a>
                                <button @click.stop="deleteIdea(idea.id)" class="px-2 py-1 rounded-lg text-[10px] font-medium glass-light hover:bg-red-500/20 text-red-400">
                                    Remover
                                </button>
                            </div>
                        </div>
                    </template>

                    <!-- Add button for Ideas column -->
                    <div x-show="column.id === 'idea'">
                        <button @click="showAddModal = true" class="w-full p-4 rounded-xl border-2 border-dashed border-white/10 hover:border-brand-500/30 text-white/30 hover:text-white/50 transition text-sm">
                            + Adicionar Ideia
                        </button>
                    </div>
                </div>
            </div>
        </template>
    </div>

    <!-- Add/Edit Modal -->
    <div x-show="showAddModal || editingIdea" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm" @click.self="showAddModal=false; editingIdea=null">
        <div class="glass rounded-2xl w-full max-w-lg" @click.stop>
            <div class="p-4 border-b border-white/5 flex items-center justify-between">
                <h3 class="font-bold" x-text="editingIdea ? 'Editar Ideia' : 'Nova Ideia'"></h3>
                <button @click="showAddModal=false; editingIdea=null" 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-4 space-y-4">
                <div>
                    <label class="text-xs text-white/40 block mb-1">Titulo</label>
                    <input type="text" x-model="ideaForm.title" class="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-brand-500" placeholder="Ideia para video...">
                </div>
                <div>
                    <label class="text-xs text-white/40 block mb-1">URL do video original (opcional)</label>
                    <input type="url" x-model="ideaForm.url" class="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-brand-500" placeholder="https://...">
                </div>
                <div>
                    <label class="text-xs text-white/40 block mb-1">Plataforma</label>
                    <select x-model="ideaForm.platform" class="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white outline-none">
                        <option value="">Geral</option>
                        <option value="tiktok">TikTok</option>
                        <option value="youtube">YouTube</option>
                        <option value="instagram">Instagram</option>
                    </select>
                </div>
                <div>
                    <label class="text-xs text-white/40 block mb-1">Anotacoes (como adaptar para seu conteudo)</label>
                    <textarea x-model="ideaForm.notes" rows="3" class="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white outline-none focus:border-brand-500 resize-none" placeholder="Como vou adaptar essa ideia..."></textarea>
                </div>
                <button @click="saveIdeaForm()" class="w-full py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm" x-text="editingIdea ? 'Salvar Alteracoes' : 'Adicionar Ideia'"></button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function ideasApp() {
    return {
        ideas: [],
        showAddModal: false,
        editingIdea: null,
        ideaForm: { title: '', url: '', platform: '', notes: '' },
        stats: { idea: 0, script: 0, production: 0, published: 0 },
        columns: [
            { id: 'idea', title: 'Ideias', color: '#7c3aed', short: 'Ideia' },
            { id: 'script', title: 'Roteiro', color: '#06b6d4', short: 'Roteiro' },
            { id: 'production', title: 'Producao', color: '#f97316', short: 'Producao' },
            { id: 'published', title: 'Publicado', color: '#10b981', short: 'Publicado' },
        ],

        async loadIdeas() {
            try {
                const r = await fetch('/api/ideas');
                this.ideas = await r.json();
                this.updateStats();
            } catch(e) { this.ideas = []; }
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        updateStats() {
            this.stats = { idea: 0, script: 0, production: 0, published: 0 };
            this.ideas.forEach(i => { if (this.stats[i.status] !== undefined) this.stats[i.status]++; });
        },

        getColumnIdeas(status) { return this.ideas.filter(i => i.status === status); },

        getNextColumns(currentId) {
            const idx = this.columns.findIndex(c => c.id === currentId);
            return this.columns.filter((c, i) => i !== idx).slice(0, 2);
        },

        editIdea(idea) {
            this.editingIdea = idea;
            this.ideaForm = { title: idea.title, url: idea.url || '', platform: idea.platform || '', notes: idea.notes || '' };
        },

        async saveIdeaForm() {
            try {
                if (this.editingIdea) {
                    await apiCall(`/api/ideas/${this.editingIdea.id}`, 'PUT', this.ideaForm);
                    showToast('Ideia atualizada!', 'success');
                } else {
                    await apiCall('/api/ideas', 'POST', { ...this.ideaForm, status: 'idea' });
                    showToast('Ideia adicionada!', 'success');
                }
                this.showAddModal = false; this.editingIdea = null;
                this.ideaForm = { title: '', url: '', platform: '', notes: '' };
                this.loadIdeas();
            } catch(e) { showToast('Erro ao salvar', 'error'); }
        },

        async moveIdea(ideaId, newStatus) {
            try {
                await apiCall(`/api/ideas/${ideaId}/move`, 'POST', { status: newStatus });
                const idea = this.ideas.find(i => i.id === ideaId);
                if (idea) idea.status = newStatus;
                this.updateStats();
                showToast('Ideia movida!', 'success');
            } catch(e) { showToast('Erro ao mover', 'error'); }
        },

        async deleteIdea(ideaId) {
            if (!confirm('Remover esta ideia?')) return;
            try {
                await apiCall(`/api/ideas/${ideaId}`, 'DELETE');
                this.ideas = this.ideas.filter(i => i.id !== ideaId);
                this.updateStats();
                showToast('Ideia removida', 'info');
            } catch(e) { showToast('Erro ao remover', 'error'); }
        }
    };
}
</script>
{% endblock %}
