{% extends "base.html" %}
{% block title %}AgencyHub - Viral Social Pro{% endblock %}
{% block nav_agency %}active{% endblock %}
{% block page_title %}AgencyHub{% endblock %}
{% block page_subtitle %}Plataforma White-Label para Agencias{% endblock %}

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

    <!-- TABS -->
    <div class="flex gap-2 mb-6 overflow-x-auto pb-1">
        <button class="tab-btn" :class="activeTab === 'workspaces' && 'active'" @click="activeTab = 'workspaces'; loadWorkspaces()">
            <i data-lucide="briefcase" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Workspaces
        </button>
        <button class="tab-btn" :class="activeTab === 'team' && 'active'" @click="activeTab = 'team'">
            <i data-lucide="users" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Team & Roles
        </button>
        <button class="tab-btn" :class="activeTab === 'approvals' && 'active'" @click="activeTab = 'approvals'; loadApprovals()">
            <i data-lucide="check-circle" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Approvals
        </button>
        <button class="tab-btn" :class="activeTab === 'branding' && 'active'" @click="activeTab = 'branding'">
            <i data-lucide="palette" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Branding
        </button>
        <button class="tab-btn" :class="activeTab === 'onboarding' && 'active'" @click="activeTab = 'onboarding'; loadOnboardings()">
            <i data-lucide="rocket" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Onboarding
        </button>
        <button class="tab-btn" :class="activeTab === 'reports' && 'active'" @click="activeTab = 'reports'; loadReports()">
            <i data-lucide="file-bar-chart" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Reports & SLA
        </button>
        <button class="tab-btn" :class="activeTab === 'stats' && 'active'" @click="activeTab = 'stats'; loadStats()">
            <i data-lucide="bar-chart-3" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Stats
        </button>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: WORKSPACES                                                -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'workspaces'" x-transition>

        <!-- Create Workspace Form -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                <i data-lucide="plus-circle" class="w-5 h-5 text-brand-400"></i> Novo Workspace
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Nome do Workspace</label>
                    <input type="text" x-model="newWsName" placeholder="Ex: Campanha Verao 2026"
                           class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Nome do Cliente</label>
                    <input type="text" x-model="newWsClient" placeholder="Ex: Empresa XYZ"
                           class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                </div>
                <div class="flex items-end">
                    <button @click="createWorkspace()" :disabled="!newWsName || !newWsClient"
                            class="w-full px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-40 disabled:cursor-not-allowed">
                        <i data-lucide="plus" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Criar Workspace
                    </button>
                </div>
            </div>
        </div>

        <!-- Filter -->
        <div class="flex items-center gap-3 mb-4">
            <label class="text-xs text-white/50">Status:</label>
            <select x-model="wsStatusFilter" @change="loadWorkspaces()"
                    class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                <option value="">Todos</option>
                <option value="active">Ativos</option>
                <option value="paused">Pausados</option>
                <option value="archived">Arquivados</option>
            </select>
            <button @click="loadWorkspaces()" class="px-3 py-2 rounded-xl glass-card text-xs text-white/60 hover:text-white transition">
                <i data-lucide="refresh-cw" class="w-3.5 h-3.5 inline-block mr-1"></i> Atualizar
            </button>
        </div>

        <!-- Loading -->
        <template x-if="workspacesLoading">
            <div class="grid-cards">
                <template x-for="i in 6">
                    <div class="skeleton h-44 rounded-2xl"></div>
                </template>
            </div>
        </template>

        <!-- Workspaces Grid -->
        <template x-if="!workspacesLoading">
            <div>
                <div x-show="workspaces.length === 0" class="text-center py-16">
                    <i data-lucide="briefcase" class="w-16 h-16 text-white/10 mx-auto mb-4"></i>
                    <p class="text-white/30 text-sm">Nenhum workspace encontrado. Crie um acima.</p>
                </div>
                <div class="grid-cards">
                    <template x-for="ws in workspaces" :key="ws.id">
                        <div class="glass-card rounded-2xl p-5 cursor-pointer" @click="selectWorkspace(ws)">
                            <div class="flex items-start justify-between mb-3">
                                <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="briefcase" class="w-5 h-5"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-bold text-white/90 text-sm" x-text="ws.name"></h4>
                                        <p class="text-xs text-white/40" x-text="ws.client_name"></p>
                                    </div>
                                </div>
                                <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold uppercase"
                                      :class="{
                                          'bg-accent-green/15 text-accent-green border border-accent-green/20': ws.status === 'active',
                                          'bg-yellow-500/15 text-yellow-400 border border-yellow-500/20': ws.status === 'paused',
                                          'bg-white/5 text-white/30 border border-white/10': ws.status === 'archived'
                                      }"
                                      x-text="ws.status || 'active'"></span>
                            </div>
                            <div class="grid grid-cols-3 gap-3 mt-4">
                                <div class="glass-light rounded-xl p-2.5 text-center">
                                    <p class="text-sm font-bold text-white" x-text="ws.channels?.length || 0"></p>
                                    <p class="text-[10px] text-white/30">Canais</p>
                                </div>
                                <div class="glass-light rounded-xl p-2.5 text-center">
                                    <p class="text-sm font-bold text-brand-300" x-text="ws.team_count || 0"></p>
                                    <p class="text-[10px] text-white/30">Team</p>
                                </div>
                                <div class="glass-light rounded-xl p-2.5 text-center">
                                    <p class="text-sm font-bold text-accent-cyan" x-text="ws.content_count || 0"></p>
                                    <p class="text-[10px] text-white/30">Conteudos</p>
                                </div>
                            </div>
                            <p class="text-[10px] text-white/20 mt-3" x-text="'Criado: ' + (ws.created_at ? new Date(ws.created_at).toLocaleDateString('pt-BR') : '--')"></p>
                        </div>
                    </template>
                </div>
            </div>
        </template>

        <!-- Workspace Detail Modal -->
        <div x-show="selectedWorkspace" x-cloak
             class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
             @click.self="selectedWorkspace = null" @keydown.escape.window="selectedWorkspace = null"
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
             x-transition:leave="transition ease-in duration-150" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0">
            <div class="glass rounded-2xl w-full max-w-2xl max-h-[85vh] overflow-y-auto" @click.stop>
                <div class="p-5 border-b border-white/5 flex items-center justify-between">
                    <div>
                        <h3 class="font-bold text-white/90 text-lg" x-text="selectedWorkspace?.name"></h3>
                        <p class="text-xs text-white/40" x-text="selectedWorkspace?.client_name"></p>
                    </div>
                    <button @click="selectedWorkspace = null" class="p-2 rounded-lg hover:bg-white/10">
                        <i data-lucide="x" class="w-5 h-5"></i>
                    </button>
                </div>
                <div class="p-5 space-y-4">
                    <!-- Edit Name -->
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="text-xs text-white/40 mb-1 block">Nome</label>
                            <input type="text" x-model="selectedWorkspace.name"
                                   class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        </div>
                        <div>
                            <label class="text-xs text-white/40 mb-1 block">Cliente</label>
                            <input type="text" x-model="selectedWorkspace.client_name"
                                   class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        </div>
                    </div>

                    <!-- Add Channel -->
                    <div class="glass-light rounded-xl p-4">
                        <h4 class="text-sm font-bold text-white/70 mb-3 flex items-center gap-2">
                            <i data-lucide="link" class="w-4 h-4 text-brand-400"></i> Adicionar Canal
                        </h4>
                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                            <select x-model="channelPlatform"
                                    class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                                <option value="tiktok">TikTok</option>
                                <option value="instagram">Instagram</option>
                                <option value="youtube">YouTube</option>
                                <option value="twitter">Twitter/X</option>
                            </select>
                            <input type="text" x-model="channelUsername" placeholder="@username"
                                   class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                            <button @click="addChannel()" :disabled="!channelUsername"
                                    class="px-4 py-2 rounded-xl gradient-brand text-white font-semibold text-xs hover:opacity-90 transition disabled:opacity-40">
                                <i data-lucide="plus" class="w-3.5 h-3.5 inline-block mr-1"></i> Adicionar
                            </button>
                        </div>
                    </div>

                    <!-- Channels List -->
                    <div x-show="selectedWorkspace?.channels?.length > 0">
                        <h4 class="text-xs text-white/40 mb-2">Canais Vinculados</h4>
                        <div class="space-y-2">
                            <template x-for="ch in selectedWorkspace?.channels || []" :key="ch.platform + ch.username">
                                <div class="flex items-center justify-between glass-light rounded-xl px-4 py-2.5">
                                    <div class="flex items-center gap-2">
                                        <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold uppercase"
                                              :class="{
                                                  'badge-tiktok': ch.platform === 'tiktok',
                                                  'badge-youtube': ch.platform === 'youtube',
                                                  'badge-instagram': ch.platform === 'instagram',
                                                  'bg-blue-500/15 text-blue-400 border border-blue-500/20': ch.platform === 'twitter'
                                              }"
                                              x-text="ch.platform"></span>
                                        <span class="text-sm text-white/70" x-text="ch.username"></span>
                                    </div>
                                    <a :href="ch.url" target="_blank" rel="noopener" class="text-brand-400 hover:text-brand-300 transition" x-show="ch.url">
                                        <i data-lucide="external-link" class="w-3.5 h-3.5"></i>
                                    </a>
                                </div>
                            </template>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="flex gap-3 pt-2">
                        <button @click="updateWorkspace()" class="flex-1 px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition">
                            <i data-lucide="save" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Salvar Alteracoes
                        </button>
                        <button @click="deleteWorkspace(selectedWorkspace.id)" class="px-4 py-2.5 rounded-xl bg-accent-red/10 border border-accent-red/20 text-accent-red font-semibold text-sm hover:bg-accent-red/20 transition">
                            <i data-lucide="trash-2" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Excluir
                        </button>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: TEAM & ROLES                                              -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'team'" x-transition>

        <!-- Workspace Selector -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                <i data-lucide="users" class="w-5 h-5 text-brand-400"></i> Gerenciar Equipe
            </h3>
            <div class="flex items-center gap-4 mb-4">
                <div class="flex-1">
                    <label class="text-xs text-white/40 mb-1 block">Selecionar Workspace</label>
                    <select x-model="teamWorkspaceId" @change="loadTeam()"
                            class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="">-- Selecione --</option>
                        <template x-for="ws in workspaces" :key="ws.id">
                            <option :value="ws.id" x-text="ws.name + ' (' + ws.client_name + ')'"></option>
                        </template>
                    </select>
                </div>
            </div>

            <!-- Invite Form -->
            <div x-show="teamWorkspaceId" x-transition class="glass-light rounded-xl p-4">
                <h4 class="text-sm font-bold text-white/70 mb-3 flex items-center gap-2">
                    <i data-lucide="user-plus" class="w-4 h-4 text-accent-green"></i> Convidar Membro
                </h4>
                <div class="grid grid-cols-1 sm:grid-cols-4 gap-3">
                    <input type="email" x-model="inviteEmail" placeholder="email@exemplo.com"
                           class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                    <input type="text" x-model="inviteName" placeholder="Nome completo"
                           class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                    <select x-model="inviteRole"
                            class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="owner">Owner</option>
                        <option value="admin">Admin</option>
                        <option value="manager">Manager</option>
                        <option value="editor">Editor</option>
                        <option value="viewer">Viewer</option>
                        <option value="client">Client</option>
                    </select>
                    <button @click="inviteMember()" :disabled="!inviteEmail || !inviteName"
                            class="px-4 py-2 rounded-xl gradient-brand text-white font-semibold text-xs hover:opacity-90 transition disabled:opacity-40">
                        <i data-lucide="send" class="w-3.5 h-3.5 inline-block mr-1"></i> Convidar
                    </button>
                </div>
            </div>
        </div>

        <!-- Team Members List -->
        <div x-show="teamWorkspaceId" x-transition>
            <template x-if="teamMembers.length === 0">
                <div class="text-center py-12">
                    <i data-lucide="users" class="w-12 h-12 text-white/10 mx-auto mb-3"></i>
                    <p class="text-white/30 text-sm">Nenhum membro encontrado neste workspace.</p>
                </div>
            </template>
            <div class="space-y-3">
                <template x-for="member in teamMembers" :key="member.id">
                    <div class="glass-card rounded-2xl p-4 flex items-center justify-between">
                        <div class="flex items-center gap-4">
                            <div class="w-10 h-10 rounded-full gradient-brand flex items-center justify-center text-white font-bold text-sm flex-shrink-0"
                                 x-text="(member.name || 'U').charAt(0).toUpperCase()"></div>
                            <div>
                                <h4 class="font-semibold text-white/90 text-sm" x-text="member.name"></h4>
                                <p class="text-xs text-white/40" x-text="member.email"></p>
                            </div>
                        </div>
                        <div class="flex items-center gap-3">
                            <select :value="member.role" @change="changeRole(member.id, $event.target.value)"
                                    class="bg-dark-700 border border-white/10 rounded-xl px-3 py-1.5 text-xs text-white/80 focus:border-brand-400 focus:outline-none">
                                <option value="owner">Owner</option>
                                <option value="admin">Admin</option>
                                <option value="manager">Manager</option>
                                <option value="editor">Editor</option>
                                <option value="viewer">Viewer</option>
                                <option value="client">Client</option>
                            </select>
                            <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold uppercase"
                                  :class="{
                                      'bg-brand-500/20 text-brand-300 border border-brand-500/30': member.role === 'owner',
                                      'bg-accent-pink/15 text-accent-pink border border-accent-pink/20': member.role === 'admin',
                                      'bg-accent-cyan/15 text-accent-cyan border border-accent-cyan/20': member.role === 'manager',
                                      'bg-accent-green/15 text-accent-green border border-accent-green/20': member.role === 'editor',
                                      'bg-white/5 text-white/40 border border-white/10': member.role === 'viewer',
                                      'bg-accent-orange/15 text-accent-orange border border-accent-orange/20': member.role === 'client'
                                  }"
                                  x-text="member.role"></span>
                            <button @click="removeMember(member.id)" class="p-1.5 rounded-lg hover:bg-accent-red/10 text-white/30 hover:text-accent-red transition" title="Remover membro">
                                <i data-lucide="user-minus" class="w-4 h-4"></i>
                            </button>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <div x-show="!teamWorkspaceId" class="text-center py-16">
            <i data-lucide="arrow-up-circle" class="w-16 h-16 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/30 text-sm">Selecione um workspace acima para gerenciar a equipe.</p>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: APPROVALS                                                 -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'approvals'" x-transition>

        <!-- Filters -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                <i data-lucide="check-circle" class="w-5 h-5 text-brand-400"></i> Fila de Aprovacao
            </h3>
            <div class="flex flex-wrap items-center gap-4">
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Workspace</label>
                    <select x-model="approvalFilter" @change="loadApprovals()"
                            class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="">Todos</option>
                        <template x-for="ws in workspaces" :key="ws.id">
                            <option :value="ws.id" x-text="ws.name"></option>
                        </template>
                    </select>
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Status</label>
                    <select x-model="approvalStatus" @change="loadApprovals()"
                            class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="">Todos</option>
                        <option value="pending">Pendente</option>
                        <option value="approved">Aprovado</option>
                        <option value="rejected">Rejeitado</option>
                        <option value="revision">Revisao</option>
                    </select>
                </div>
                <div class="flex items-end">
                    <button @click="loadApprovals()" class="px-3 py-2 rounded-xl glass-card text-xs text-white/60 hover:text-white transition mt-4">
                        <i data-lucide="refresh-cw" class="w-3.5 h-3.5 inline-block mr-1"></i> Atualizar
                    </button>
                </div>
            </div>
        </div>

        <!-- Submit New Approval -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <h4 class="text-sm font-bold text-white/70 mb-3 flex items-center gap-2">
                <i data-lucide="send" class="w-4 h-4 text-accent-cyan"></i> Enviar para Aprovacao
            </h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                <select x-model="submitApprovalWsId"
                        class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    <option value="">Selecionar Workspace</option>
                    <template x-for="ws in workspaces" :key="ws.id">
                        <option :value="ws.id" x-text="ws.name"></option>
                    </template>
                </select>
                <select x-model="submitContentType"
                        class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    <option value="post">Post</option>
                    <option value="video">Video</option>
                    <option value="story">Story</option>
                    <option value="reel">Reel</option>
                    <option value="campaign">Campanha</option>
                </select>
            </div>
            <textarea x-model="submitContent" rows="3" placeholder="Conteudo para aprovacao..."
                      class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-3 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none resize-none mb-3"></textarea>
            <div class="flex items-center gap-3">
                <input type="text" x-model="submitSubmitter" placeholder="Seu nome"
                       class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                <button @click="submitForApproval()" :disabled="!submitApprovalWsId || !submitContent || !submitSubmitter"
                        class="px-4 py-2 rounded-xl gradient-brand text-white font-semibold text-xs hover:opacity-90 transition disabled:opacity-40">
                    <i data-lucide="send" class="w-3.5 h-3.5 inline-block mr-1"></i> Enviar
                </button>
            </div>
        </div>

        <!-- Loading -->
        <template x-if="approvalsLoading">
            <div class="space-y-4">
                <template x-for="i in 3">
                    <div class="skeleton h-40 rounded-2xl"></div>
                </template>
            </div>
        </template>

        <!-- Approvals List -->
        <template x-if="!approvalsLoading">
            <div>
                <div x-show="approvals.length === 0" class="text-center py-12">
                    <i data-lucide="inbox" class="w-12 h-12 text-white/10 mx-auto mb-3"></i>
                    <p class="text-white/30 text-sm">Nenhuma aprovacao encontrada.</p>
                </div>
                <div class="space-y-4">
                    <template x-for="approval in approvals" :key="approval.id">
                        <div class="glass-card rounded-2xl p-5">
                            <div class="flex items-start justify-between mb-3">
                                <div class="flex items-center gap-3">
                                    <div class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0"
                                         :class="{
                                             'bg-yellow-500/15': approval.status === 'pending',
                                             'bg-accent-green/15': approval.status === 'approved',
                                             'bg-accent-red/15': approval.status === 'rejected',
                                             'bg-accent-orange/15': approval.status === 'revision'
                                         }">
                                        <i :data-lucide="approval.status === 'pending' ? 'clock' : approval.status === 'approved' ? 'check' : approval.status === 'rejected' ? 'x' : 'rotate-ccw'"
                                           class="w-5 h-5"
                                           :class="{
                                               'text-yellow-400': approval.status === 'pending',
                                               'text-accent-green': approval.status === 'approved',
                                               'text-accent-red': approval.status === 'rejected',
                                               'text-accent-orange': approval.status === 'revision'
                                           }"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-semibold text-white/90 text-sm flex items-center gap-2">
                                            <span x-text="approval.content_type || 'Post'" class="uppercase text-[10px] px-2 py-0.5 rounded-lg bg-brand-500/15 text-brand-300 border border-brand-500/20"></span>
                                            <span class="text-white/50 text-xs" x-text="'por ' + (approval.submitter || '--')"></span>
                                        </h4>
                                        <p class="text-[10px] text-white/30 mt-0.5" x-text="approval.created_at ? new Date(approval.created_at).toLocaleString('pt-BR') : ''"></p>
                                    </div>
                                </div>
                                <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold uppercase"
                                      :class="{
                                          'bg-yellow-500/15 text-yellow-400 border border-yellow-500/20': approval.status === 'pending',
                                          'bg-accent-green/15 text-accent-green border border-accent-green/20': approval.status === 'approved',
                                          'bg-accent-red/15 text-accent-red border border-accent-red/20': approval.status === 'rejected',
                                          'bg-accent-orange/15 text-accent-orange border border-accent-orange/20': approval.status === 'revision'
                                      }"
                                      x-text="approval.status"></span>
                            </div>

                            <!-- Content Preview -->
                            <div class="glass-light rounded-xl p-3 mb-4 text-sm text-white/60 leading-relaxed max-h-32 overflow-y-auto"
                                 x-text="approval.content"></div>

                            <!-- Existing Feedback -->
                            <div x-show="approval.feedback" class="mb-3 px-3 py-2 rounded-xl bg-brand-500/5 border border-brand-500/10">
                                <p class="text-[10px] text-white/30 mb-1">Feedback de <span class="text-brand-300" x-text="approval.reviewer"></span>:</p>
                                <p class="text-xs text-white/50" x-text="approval.feedback"></p>
                            </div>

                            <!-- Action Buttons (only for pending/revision) -->
                            <div x-show="approval.status === 'pending' || approval.status === 'revision'">
                                <textarea x-model="approval._feedback" rows="2" placeholder="Feedback (opcional para aprovacao, obrigatorio para rejeicao/revisao)..."
                                          class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-xs text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none resize-none mb-3"></textarea>
                                <div class="flex gap-2">
                                    <button @click="reviewApproval(approval.id, 'approved', approval._feedback)"
                                            class="flex-1 px-3 py-2 rounded-xl bg-accent-green/10 border border-accent-green/20 text-accent-green font-semibold text-xs hover:bg-accent-green/20 transition">
                                        <i data-lucide="check" class="w-3.5 h-3.5 inline-block mr-1"></i> Aprovar
                                    </button>
                                    <button @click="reviewApproval(approval.id, 'revision', approval._feedback)"
                                            class="flex-1 px-3 py-2 rounded-xl bg-accent-orange/10 border border-accent-orange/20 text-accent-orange font-semibold text-xs hover:bg-accent-orange/20 transition">
                                        <i data-lucide="rotate-ccw" class="w-3.5 h-3.5 inline-block mr-1"></i> Revisao
                                    </button>
                                    <button @click="reviewApproval(approval.id, 'rejected', approval._feedback)"
                                            class="flex-1 px-3 py-2 rounded-xl bg-accent-red/10 border border-accent-red/20 text-accent-red font-semibold text-xs hover:bg-accent-red/20 transition">
                                        <i data-lucide="x" class="w-3.5 h-3.5 inline-block mr-1"></i> Rejeitar
                                    </button>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </template>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: BRANDING                                                  -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'branding'" x-transition>

        <!-- Workspace Selector -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                <i data-lucide="palette" class="w-5 h-5 text-brand-400"></i> White-Label Branding
            </h3>
            <div class="flex items-center gap-4">
                <div class="flex-1">
                    <label class="text-xs text-white/40 mb-1 block">Selecionar Workspace</label>
                    <select x-model="brandingWsId" @change="loadBranding()"
                            class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="">-- Selecione --</option>
                        <template x-for="ws in workspaces" :key="ws.id">
                            <option :value="ws.id" x-text="ws.name + ' (' + ws.client_name + ')'"></option>
                        </template>
                    </select>
                </div>
            </div>
        </div>

        <div x-show="brandingWsId" x-transition>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <!-- Branding Form -->
                <div class="glass-card rounded-2xl p-5">
                    <h4 class="text-sm font-bold text-white/70 mb-4 flex items-center gap-2">
                        <i data-lucide="settings" class="w-4 h-4 text-accent-cyan"></i> Configuracoes de Marca
                    </h4>
                    <div class="space-y-4">
                        <div>
                            <label class="text-xs text-white/40 mb-1 block">URL do Logo</label>
                            <input type="url" x-model="brandLogo" placeholder="https://exemplo.com/logo.png"
                                   class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="text-xs text-white/40 mb-1 block">Cor Primaria</label>
                                <div class="flex items-center gap-2">
                                    <input type="color" x-model="brandPrimary" class="w-10 h-10 rounded-lg border border-white/10 bg-transparent cursor-pointer">
                                    <input type="text" x-model="brandPrimary"
                                           class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                                </div>
                            </div>
                            <div>
                                <label class="text-xs text-white/40 mb-1 block">Cor Secundaria</label>
                                <div class="flex items-center gap-2">
                                    <input type="color" x-model="brandSecondary" class="w-10 h-10 rounded-lg border border-white/10 bg-transparent cursor-pointer">
                                    <input type="text" x-model="brandSecondary"
                                           class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                                </div>
                            </div>
                        </div>
                        <div>
                            <label class="text-xs text-white/40 mb-1 block">Fonte</label>
                            <select x-model="brandFont"
                                    class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                                <option value="">Padrao (Plus Jakarta Sans)</option>
                                <option value="Inter">Inter</option>
                                <option value="Poppins">Poppins</option>
                                <option value="Roboto">Roboto</option>
                                <option value="Montserrat">Montserrat</option>
                                <option value="Open Sans">Open Sans</option>
                                <option value="Lato">Lato</option>
                                <option value="Nunito">Nunito</option>
                            </select>
                        </div>
                        <div>
                            <label class="text-xs text-white/40 mb-1 block">Dominio Customizado</label>
                            <input type="text" x-model="brandDomain" placeholder="app.seucliente.com"
                                   class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                        </div>
                        <button @click="saveBranding()" class="w-full px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition">
                            <i data-lucide="save" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Salvar Branding
                        </button>
                    </div>
                </div>

                <!-- Preview Card -->
                <div class="glass-card rounded-2xl p-5">
                    <h4 class="text-sm font-bold text-white/70 mb-4 flex items-center gap-2">
                        <i data-lucide="eye" class="w-4 h-4 text-accent-pink"></i> Preview
                    </h4>
                    <div class="rounded-2xl border border-white/10 overflow-hidden" :style="'background: linear-gradient(135deg, ' + brandPrimary + '22, ' + brandSecondary + '22)'">
                        <!-- Preview Header -->
                        <div class="p-4 flex items-center gap-3" :style="'background: ' + brandPrimary + '33; border-bottom: 1px solid ' + brandPrimary + '44'">
                            <div class="w-8 h-8 rounded-lg flex items-center justify-center" :style="'background: ' + brandPrimary">
                                <template x-if="brandLogo">
                                    <img :src="brandLogo" class="w-6 h-6 object-contain" alt="Logo" onerror="this.style.display='none'">
                                </template>
                                <template x-if="!brandLogo">
                                    <i data-lucide="building-2" class="w-4 h-4 text-white"></i>
                                </template>
                            </div>
                            <div>
                                <p class="text-sm font-bold text-white" :style="brandFont ? 'font-family: ' + brandFont : ''"
                                   x-text="workspaces.find(w => w.id == brandingWsId)?.client_name || 'Marca do Cliente'"></p>
                                <p class="text-[10px] text-white/40" x-text="brandDomain || 'app.seucliente.com'"></p>
                            </div>
                        </div>
                        <!-- Preview Content -->
                        <div class="p-4 space-y-3">
                            <div class="rounded-xl p-3" :style="'background: ' + brandPrimary + '15; border: 1px solid ' + brandPrimary + '25'">
                                <p class="text-xs text-white/60" :style="brandFont ? 'font-family: ' + brandFont : ''">Dashboard do cliente com a marca personalizada</p>
                            </div>
                            <div class="flex gap-2">
                                <div class="flex-1 h-2 rounded-full" :style="'background: ' + brandPrimary"></div>
                                <div class="flex-1 h-2 rounded-full" :style="'background: ' + brandSecondary"></div>
                            </div>
                            <div class="grid grid-cols-3 gap-2">
                                <div class="rounded-lg p-2 text-center" :style="'background: ' + brandPrimary + '20'">
                                    <p class="text-xs font-bold text-white">128</p>
                                    <p class="text-[9px] text-white/30">Posts</p>
                                </div>
                                <div class="rounded-lg p-2 text-center" :style="'background: ' + brandSecondary + '20'">
                                    <p class="text-xs font-bold text-white">45.2K</p>
                                    <p class="text-[9px] text-white/30">Reach</p>
                                </div>
                                <div class="rounded-lg p-2 text-center" :style="'background: ' + brandPrimary + '20'">
                                    <p class="text-xs font-bold text-white">8.7%</p>
                                    <p class="text-[9px] text-white/30">Engage</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mt-4 flex flex-wrap gap-2">
                        <div class="flex items-center gap-2 px-3 py-1.5 rounded-lg glass-light">
                            <div class="w-4 h-4 rounded" :style="'background: ' + brandPrimary"></div>
                            <span class="text-[10px] text-white/40" x-text="brandPrimary"></span>
                        </div>
                        <div class="flex items-center gap-2 px-3 py-1.5 rounded-lg glass-light">
                            <div class="w-4 h-4 rounded" :style="'background: ' + brandSecondary"></div>
                            <span class="text-[10px] text-white/40" x-text="brandSecondary"></span>
                        </div>
                        <div class="flex items-center gap-2 px-3 py-1.5 rounded-lg glass-light" x-show="brandFont">
                            <i data-lucide="type" class="w-3 h-3 text-white/30"></i>
                            <span class="text-[10px] text-white/40" x-text="brandFont"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div x-show="!brandingWsId" class="text-center py-16">
            <i data-lucide="palette" class="w-16 h-16 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/30 text-sm">Selecione um workspace para configurar o branding.</p>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: ONBOARDING                                                -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'onboarding'" x-transition>

        <!-- Start Onboarding Form -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                <i data-lucide="rocket" class="w-5 h-5 text-brand-400"></i> Iniciar Novo Onboarding
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Workspace</label>
                    <select x-model="onboardingWsId"
                            class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="">-- Selecione --</option>
                        <template x-for="ws in workspaces" :key="ws.id">
                            <option :value="ws.id" x-text="ws.name"></option>
                        </template>
                    </select>
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Nome do Cliente</label>
                    <input type="text" x-model="onboardClientName" placeholder="Nome completo"
                           class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Email do Cliente</label>
                    <input type="email" x-model="onboardClientEmail" placeholder="cliente@exemplo.com"
                           class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                </div>
                <div class="flex items-end">
                    <button @click="startOnboarding()" :disabled="!onboardingWsId || !onboardClientName || !onboardClientEmail"
                            class="w-full px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-40 disabled:cursor-not-allowed">
                        <i data-lucide="play" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Iniciar
                    </button>
                </div>
            </div>
        </div>

        <!-- Active Onboardings -->
        <div x-show="onboardings.length === 0 && !onboardingsLoading" class="text-center py-12">
            <i data-lucide="rocket" class="w-12 h-12 text-white/10 mx-auto mb-3"></i>
            <p class="text-white/30 text-sm">Nenhum onboarding ativo. Inicie um novo acima.</p>
        </div>

        <template x-if="onboardingsLoading">
            <div class="space-y-4">
                <template x-for="i in 3">
                    <div class="skeleton h-48 rounded-2xl"></div>
                </template>
            </div>
        </template>

        <div class="space-y-4">
            <template x-for="ob in onboardings" :key="ob.id">
                <div class="glass-card rounded-2xl p-5">
                    <div class="flex items-start justify-between mb-4">
                        <div>
                            <h4 class="font-bold text-white/90 text-sm" x-text="ob.client_name"></h4>
                            <p class="text-xs text-white/40" x-text="ob.client_email"></p>
                        </div>
                        <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold uppercase"
                              :class="{
                                  'bg-accent-green/15 text-accent-green border border-accent-green/20': ob.status === 'completed',
                                  'bg-brand-500/15 text-brand-300 border border-brand-500/20': ob.status === 'in_progress',
                                  'bg-yellow-500/15 text-yellow-400 border border-yellow-500/20': ob.status === 'pending'
                              }"
                              x-text="ob.status"></span>
                    </div>

                    <!-- Progress Bar -->
                    <div class="mb-4">
                        <div class="flex items-center justify-between mb-1.5">
                            <span class="text-[10px] text-white/40">Progresso</span>
                            <span class="text-[10px] font-bold text-brand-300" x-text="getOnboardingProgress(ob) + '%'"></span>
                        </div>
                        <div class="w-full h-2 rounded-full bg-white/5">
                            <div class="h-2 rounded-full gradient-brand transition-all duration-500"
                                 :style="'width: ' + getOnboardingProgress(ob) + '%'"></div>
                        </div>
                    </div>

                    <!-- Steps -->
                    <div class="grid grid-cols-7 gap-2">
                        <template x-for="step in 7" :key="step">
                            <div class="text-center">
                                <button @click="updateOnboardingStep(ob.id, step)"
                                        class="w-full aspect-square rounded-xl flex items-center justify-center text-xs font-bold transition-all"
                                        :class="getStepStatus(ob, step) === 'completed' ? 'bg-accent-green/20 text-accent-green border border-accent-green/30' :
                                                getStepStatus(ob, step) === 'in_progress' ? 'bg-brand-500/20 text-brand-300 border border-brand-500/30 animate-pulse-glow' :
                                                'bg-white/5 text-white/20 border border-white/5 hover:border-white/20'"
                                        x-text="step"></button>
                                <p class="text-[8px] text-white/20 mt-1" x-text="getStepLabel(step)"></p>
                            </div>
                        </template>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: REPORTS & SLA                                             -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'reports'" x-transition>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <!-- Generate Report -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <i data-lucide="file-bar-chart" class="w-5 h-5 text-brand-400"></i> Gerar Relatorio
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/40 mb-1 block">Workspace</label>
                        <select x-model="reportWsId"
                                class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                            <option value="">-- Selecione --</option>
                            <template x-for="ws in workspaces" :key="ws.id">
                                <option :value="ws.id" x-text="ws.name"></option>
                            </template>
                        </select>
                    </div>
                    <div>
                        <label class="text-xs text-white/40 mb-1 block">Tipo de Relatorio</label>
                        <div class="flex gap-3">
                            <button @click="reportType = 'weekly'" class="flex-1 px-4 py-2.5 rounded-xl text-sm font-semibold transition"
                                    :class="reportType === 'weekly' ? 'gradient-brand text-white' : 'glass-light text-white/50 hover:text-white/80'">
                                <i data-lucide="calendar" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Semanal
                            </button>
                            <button @click="reportType = 'monthly'" class="flex-1 px-4 py-2.5 rounded-xl text-sm font-semibold transition"
                                    :class="reportType === 'monthly' ? 'gradient-brand text-white' : 'glass-light text-white/50 hover:text-white/80'">
                                <i data-lucide="calendar-range" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Mensal
                            </button>
                        </div>
                    </div>
                    <button @click="generateReport()" :disabled="!reportWsId"
                            class="w-full px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-40">
                        <i data-lucide="file-plus" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Gerar Relatorio
                    </button>
                </div>
            </div>

            <!-- SLA Check -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <i data-lucide="shield-check" class="w-5 h-5 text-accent-green"></i> Compliance SLA
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/40 mb-1 block">Workspace</label>
                        <select x-model="slaWsId"
                                class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                            <option value="">-- Selecione --</option>
                            <template x-for="ws in workspaces" :key="ws.id">
                                <option :value="ws.id" x-text="ws.name"></option>
                            </template>
                        </select>
                    </div>
                    <button @click="checkSLA()" :disabled="!slaWsId"
                            class="w-full px-4 py-2.5 rounded-xl gradient-success text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-40">
                        <i data-lucide="search" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Verificar SLA
                    </button>

                    <!-- SLA Result -->
                    <div x-show="slaResult" x-transition class="space-y-3">
                        <div class="glass-light rounded-xl p-4 text-center">
                            <p class="text-[10px] text-white/30 mb-1">Taxa de Compliance</p>
                            <p class="text-3xl font-extrabold"
                               :class="(slaResult?.compliance_rate || 0) >= 90 ? 'text-accent-green' : (slaResult?.compliance_rate || 0) >= 70 ? 'text-yellow-400' : 'text-accent-red'"
                               x-text="(slaResult?.compliance_rate || 0).toFixed(1) + '%'"></p>
                        </div>
                        <div class="grid grid-cols-2 gap-3">
                            <div class="glass-light rounded-xl p-3 text-center">
                                <p class="text-sm font-bold text-accent-red" x-text="slaResult?.overdue_items || 0"></p>
                                <p class="text-[10px] text-white/30">Itens Atrasados</p>
                            </div>
                            <div class="glass-light rounded-xl p-3 text-center">
                                <p class="text-sm font-bold text-accent-green" x-text="slaResult?.on_time_items || 0"></p>
                                <p class="text-[10px] text-white/30">No Prazo</p>
                            </div>
                        </div>
                        <div x-show="slaResult?.details" class="text-xs text-white/40 leading-relaxed glass-light rounded-xl p-3" x-text="slaResult?.details"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Reports -->
        <div class="glass-card rounded-2xl p-5">
            <h4 class="text-sm font-bold text-white/70 mb-4 flex items-center gap-2">
                <i data-lucide="file-text" class="w-4 h-4 text-accent-cyan"></i> Relatorios Recentes
            </h4>
            <div x-show="reports.length === 0" class="text-center py-8">
                <i data-lucide="file-text" class="w-10 h-10 text-white/10 mx-auto mb-2"></i>
                <p class="text-white/30 text-xs">Nenhum relatorio gerado ainda.</p>
            </div>
            <div class="space-y-3">
                <template x-for="report in reports" :key="report.id">
                    <div class="flex items-center justify-between glass-light rounded-xl px-4 py-3 cursor-pointer hover:border-brand-400/30 transition"
                         @click="viewReport(report.id)">
                        <div class="flex items-center gap-3">
                            <div class="w-9 h-9 rounded-lg flex items-center justify-center"
                                 :class="report.report_type === 'weekly' ? 'bg-brand-500/15' : 'bg-accent-cyan/15'">
                                <i :data-lucide="report.report_type === 'weekly' ? 'calendar' : 'calendar-range'" class="w-4 h-4"
                                   :class="report.report_type === 'weekly' ? 'text-brand-300' : 'text-accent-cyan'"></i>
                            </div>
                            <div>
                                <p class="text-sm font-semibold text-white/80" x-text="(report.report_type === 'weekly' ? 'Semanal' : 'Mensal') + ' - ' + (report.workspace_name || '')"></p>
                                <p class="text-[10px] text-white/30" x-text="report.created_at ? new Date(report.created_at).toLocaleString('pt-BR') : ''"></p>
                            </div>
                        </div>
                        <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold uppercase"
                              :class="{
                                  'bg-accent-green/15 text-accent-green border border-accent-green/20': report.status === 'completed',
                                  'bg-yellow-500/15 text-yellow-400 border border-yellow-500/20': report.status === 'generating',
                                  'bg-accent-red/15 text-accent-red border border-accent-red/20': report.status === 'failed'
                              }"
                              x-text="report.status || 'completed'"></span>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: STATS                                                     -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'stats'" x-transition>

        <!-- Loading -->
        <template x-if="!stats">
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <template x-for="i in 4">
                    <div class="skeleton h-32 rounded-2xl"></div>
                </template>
            </div>
        </template>

        <template x-if="stats">
            <div>
                <!-- KPI Cards -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center">
                                <i data-lucide="briefcase" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Total Workspaces</span>
                        </div>
                        <p class="stat-number text-white" x-text="stats.total_workspaces || 0"></p>
                        <p class="text-xs text-white/30 mt-1">
                            <span class="text-accent-green" x-text="stats.active_workspaces || 0"></span> ativos
                        </p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center">
                                <i data-lucide="users" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Team Members</span>
                        </div>
                        <p class="stat-number text-brand-300" x-text="stats.total_team_members || 0"></p>
                        <p class="text-xs text-white/30 mt-1">em todos os workspaces</p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center">
                                <i data-lucide="clock" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Aprovacoes Pendentes</span>
                        </div>
                        <p class="stat-number text-accent-orange" x-text="stats.pending_approvals || 0"></p>
                        <p class="text-xs text-white/30 mt-1">
                            <span class="text-accent-green" x-text="stats.approved_this_week || 0"></span> aprovados esta semana
                        </p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center">
                                <i data-lucide="shield-check" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Compliance Rate</span>
                        </div>
                        <p class="stat-number"
                           :class="(stats.compliance_rate || 0) >= 90 ? 'text-accent-green' : (stats.compliance_rate || 0) >= 70 ? 'text-yellow-400' : 'text-accent-red'"
                           x-text="(stats.compliance_rate || 0).toFixed(1) + '%'"></p>
                        <p class="text-xs text-white/30 mt-1">SLA compliance geral</p>
                    </div>
                </div>

                <!-- Additional Stats -->
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <!-- Workspace Distribution -->
                    <div class="glass-card rounded-2xl p-5">
                        <h4 class="text-sm font-bold text-white/70 mb-4 flex items-center gap-2">
                            <i data-lucide="pie-chart" class="w-4 h-4 text-brand-400"></i> Distribuicao de Workspaces
                        </h4>
                        <div class="space-y-3">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <div class="w-3 h-3 rounded-full bg-accent-green"></div>
                                    <span class="text-xs text-white/60">Ativos</span>
                                </div>
                                <span class="text-sm font-bold text-white" x-text="stats.active_workspaces || 0"></span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <div class="w-3 h-3 rounded-full bg-yellow-400"></div>
                                    <span class="text-xs text-white/60">Pausados</span>
                                </div>
                                <span class="text-sm font-bold text-white" x-text="stats.paused_workspaces || 0"></span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <div class="w-3 h-3 rounded-full bg-white/20"></div>
                                    <span class="text-xs text-white/60">Arquivados</span>
                                </div>
                                <span class="text-sm font-bold text-white" x-text="stats.archived_workspaces || 0"></span>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Activity -->
                    <div class="glass-card rounded-2xl p-5">
                        <h4 class="text-sm font-bold text-white/70 mb-4 flex items-center gap-2">
                            <i data-lucide="activity" class="w-4 h-4 text-accent-cyan"></i> Atividade Recente
                        </h4>
                        <div x-show="!stats.recent_activity?.length" class="text-center py-6">
                            <p class="text-white/20 text-xs">Sem atividade recente</p>
                        </div>
                        <div class="space-y-2">
                            <template x-for="activity in (stats.recent_activity || []).slice(0, 8)" :key="activity.id || Math.random()">
                                <div class="flex items-center gap-3 py-2 border-b border-white/5 last:border-0">
                                    <div class="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0"
                                         :class="{
                                             'bg-accent-green/15': activity.type === 'approval',
                                             'bg-brand-500/15': activity.type === 'workspace',
                                             'bg-accent-cyan/15': activity.type === 'team',
                                             'bg-accent-orange/15': activity.type === 'report'
                                         }">
                                        <i :data-lucide="activity.type === 'approval' ? 'check-circle' : activity.type === 'workspace' ? 'briefcase' : activity.type === 'team' ? 'user-plus' : 'file-text'"
                                           class="w-3.5 h-3.5"
                                           :class="{
                                               'text-accent-green': activity.type === 'approval',
                                               'text-brand-300': activity.type === 'workspace',
                                               'text-accent-cyan': activity.type === 'team',
                                               'text-accent-orange': activity.type === 'report'
                                           }"></i>
                                    </div>
                                    <div class="flex-1 min-w-0">
                                        <p class="text-xs text-white/60 truncate" x-text="activity.description"></p>
                                        <p class="text-[10px] text-white/20" x-text="activity.time ? timeAgo(activity.time) : ''"></p>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function agencyHub() {
    return {
        activeTab: 'workspaces',

        // Workspaces
        workspaces: [],
        workspacesLoading: false,
        wsStatusFilter: '',
        newWsName: '',
        newWsClient: '',
        selectedWorkspace: null,
        channelPlatform: 'tiktok',
        channelUsername: '',

        // Team
        teamWorkspaceId: '',
        teamMembers: [],
        inviteEmail: '',
        inviteName: '',
        inviteRole: 'editor',

        // Approvals
        approvals: [],
        approvalsLoading: false,
        approvalFilter: '',
        approvalStatus: '',
        reviewFeedback: '',
        submitApprovalWsId: '',
        submitContentType: 'post',
        submitContent: '',
        submitSubmitter: '',

        // Branding
        brandingWsId: '',
        brandingData: null,
        brandLogo: '',
        brandPrimary: '#6366f1',
        brandSecondary: '#8b5cf6',
        brandFont: '',
        brandDomain: '',

        // Onboarding
        onboardings: [],
        onboardingsLoading: false,
        onboardingWsId: '',
        onboardClientName: '',
        onboardClientEmail: '',

        // Reports
        reports: [],
        reportWsId: '',
        reportType: 'weekly',
        slaResult: null,
        slaWsId: '',

        // Stats
        stats: null,

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

        // ── Workspaces ─────────────────────────────────────────────
        async loadWorkspaces() {
            this.workspacesLoading = true;
            try {
                const params = new URLSearchParams();
                if (this.wsStatusFilter) params.set('status', this.wsStatusFilter);
                const data = await apiCall('/api/agency/workspaces?' + params.toString());
                this.workspaces = Array.isArray(data) ? data : (data.workspaces || []);
            } catch (e) {
                showToast('Erro ao carregar workspaces', 'error');
                this.workspaces = [];
            }
            this.workspacesLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async createWorkspace() {
            if (!this.newWsName || !this.newWsClient) return;
            try {
                await apiCall('/api/agency/workspaces', 'POST', {
                    name: this.newWsName,
                    client_name: this.newWsClient,
                    branding: {}
                });
                showToast('Workspace criado com sucesso!', 'success');
                this.newWsName = '';
                this.newWsClient = '';
                await this.loadWorkspaces();
            } catch (e) {
                showToast('Erro ao criar workspace', 'error');
            }
        },

        selectWorkspace(ws) {
            this.selectedWorkspace = JSON.parse(JSON.stringify(ws));
            this.channelPlatform = 'tiktok';
            this.channelUsername = '';
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async updateWorkspace() {
            if (!this.selectedWorkspace) return;
            try {
                await apiCall('/api/agency/workspaces/' + this.selectedWorkspace.id, 'PUT', {
                    name: this.selectedWorkspace.name,
                    client_name: this.selectedWorkspace.client_name
                });
                showToast('Workspace atualizado!', 'success');
                this.selectedWorkspace = null;
                await this.loadWorkspaces();
            } catch (e) {
                showToast('Erro ao atualizar workspace', 'error');
            }
        },

        async deleteWorkspace(wsId) {
            if (!confirm('Tem certeza que deseja excluir este workspace? Esta acao nao pode ser desfeita.')) return;
            try {
                await apiCall('/api/agency/workspaces/' + wsId, 'DELETE');
                showToast('Workspace excluido!', 'success');
                this.selectedWorkspace = null;
                await this.loadWorkspaces();
            } catch (e) {
                showToast('Erro ao excluir workspace', 'error');
            }
        },

        async addChannel() {
            if (!this.selectedWorkspace || !this.channelUsername) return;
            try {
                await apiCall('/api/agency/workspaces/' + this.selectedWorkspace.id + '/channels', 'POST', {
                    platform: this.channelPlatform,
                    username: this.channelUsername,
                    url: ''
                });
                showToast('Canal adicionado!', 'success');
                this.channelUsername = '';
                // Reload workspace details
                const ws = await apiCall('/api/agency/workspaces/' + this.selectedWorkspace.id);
                this.selectedWorkspace = ws;
                await this.loadWorkspaces();
            } catch (e) {
                showToast('Erro ao adicionar canal', 'error');
            }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        // ── Team ────────────────────────────────────────────────────
        async loadTeam() {
            if (!this.teamWorkspaceId) { this.teamMembers = []; return; }
            try {
                const data = await apiCall('/api/agency/workspaces/' + this.teamWorkspaceId + '/team');
                this.teamMembers = Array.isArray(data) ? data : (data.members || []);
            } catch (e) {
                showToast('Erro ao carregar equipe', 'error');
                this.teamMembers = [];
            }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async inviteMember() {
            if (!this.teamWorkspaceId || !this.inviteEmail || !this.inviteName) return;
            try {
                await apiCall('/api/agency/workspaces/' + this.teamWorkspaceId + '/team', 'POST', {
                    email: this.inviteEmail,
                    name: this.inviteName,
                    role: this.inviteRole
                });
                showToast('Convite enviado para ' + this.inviteEmail + '!', 'success');
                this.inviteEmail = '';
                this.inviteName = '';
                this.inviteRole = 'editor';
                await this.loadTeam();
            } catch (e) {
                showToast('Erro ao convidar membro', 'error');
            }
        },

        async changeRole(memberId, newRole) {
            try {
                await apiCall('/api/agency/team/' + memberId + '/role', 'PUT', { role: newRole });
                showToast('Papel atualizado!', 'success');
                await this.loadTeam();
            } catch (e) {
                showToast('Erro ao alterar papel', 'error');
            }
        },

        async removeMember(memberId) {
            if (!confirm('Remover este membro da equipe?')) return;
            try {
                await apiCall('/api/agency/workspaces/' + this.teamWorkspaceId + '/team/' + memberId, 'DELETE');
                showToast('Membro removido!', 'success');
                await this.loadTeam();
            } catch (e) {
                showToast('Erro ao remover membro', 'error');
            }
        },

        // ── Approvals ───────────────────────────────────────────────
        async loadApprovals() {
            this.approvalsLoading = true;
            try {
                const params = new URLSearchParams();
                if (this.approvalFilter) params.set('workspace_id', this.approvalFilter);
                if (this.approvalStatus) params.set('status', this.approvalStatus);
                const data = await apiCall('/api/agency/approvals?' + params.toString());
                this.approvals = (Array.isArray(data) ? data : (data.approvals || [])).map(a => ({ ...a, _feedback: '' }));
            } catch (e) {
                showToast('Erro ao carregar aprovacoes', 'error');
                this.approvals = [];
            }
            this.approvalsLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async submitForApproval() {
            if (!this.submitApprovalWsId || !this.submitContent || !this.submitSubmitter) return;
            try {
                await apiCall('/api/agency/approvals', 'POST', {
                    workspace_id: this.submitApprovalWsId,
                    content_type: this.submitContentType,
                    content: this.submitContent,
                    submitter: this.submitSubmitter
                });
                showToast('Conteudo enviado para aprovacao!', 'success');
                this.submitContent = '';
                this.submitSubmitter = '';
                await this.loadApprovals();
            } catch (e) {
                showToast('Erro ao enviar para aprovacao', 'error');
            }
        },

        async reviewApproval(approvalId, action, feedback) {
            if ((action === 'rejected' || action === 'revision') && !feedback) {
                showToast('Feedback obrigatorio para rejeicao ou revisao', 'warning');
                return;
            }
            try {
                await apiCall('/api/agency/approvals/' + approvalId, 'PUT', {
                    action: action,
                    reviewer: 'Agency Admin',
                    feedback: feedback || ''
                });
                const labels = { approved: 'aprovado', rejected: 'rejeitado', revision: 'enviado para revisao' };
                showToast('Conteudo ' + (labels[action] || action) + '!', 'success');
                await this.loadApprovals();
            } catch (e) {
                showToast('Erro ao revisar aprovacao', 'error');
            }
        },

        // ── Branding ────────────────────────────────────────────────
        async loadBranding() {
            if (!this.brandingWsId) { this.brandingData = null; return; }
            try {
                const data = await apiCall('/api/agency/workspaces/' + this.brandingWsId + '/branding');
                this.brandingData = data;
                this.brandLogo = data.logo_url || '';
                this.brandPrimary = data.primary_color || '#6366f1';
                this.brandSecondary = data.secondary_color || '#8b5cf6';
                this.brandFont = data.font || '';
                this.brandDomain = data.custom_domain || '';
            } catch (e) {
                // No branding yet, use defaults
                this.brandingData = null;
                this.brandLogo = '';
                this.brandPrimary = '#6366f1';
                this.brandSecondary = '#8b5cf6';
                this.brandFont = '';
                this.brandDomain = '';
            }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async saveBranding() {
            if (!this.brandingWsId) return;
            try {
                await apiCall('/api/agency/workspaces/' + this.brandingWsId + '/branding', 'PUT', {
                    logo_url: this.brandLogo,
                    primary_color: this.brandPrimary,
                    secondary_color: this.brandSecondary,
                    font: this.brandFont,
                    custom_domain: this.brandDomain
                });
                showToast('Branding atualizado com sucesso!', 'success');
            } catch (e) {
                showToast('Erro ao salvar branding', 'error');
            }
        },

        // ── Onboarding ──────────────────────────────────────────────
        async loadOnboardings() {
            this.onboardingsLoading = true;
            try {
                const params = new URLSearchParams();
                if (this.onboardingWsId) params.set('workspace_id', this.onboardingWsId);
                const data = await apiCall('/api/agency/onboarding?' + params.toString());
                this.onboardings = Array.isArray(data) ? data : (data.onboardings || []);
            } catch (e) {
                showToast('Erro ao carregar onboardings', 'error');
                this.onboardings = [];
            }
            this.onboardingsLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async startOnboarding() {
            if (!this.onboardingWsId || !this.onboardClientName || !this.onboardClientEmail) return;
            try {
                await apiCall('/api/agency/onboarding', 'POST', {
                    workspace_id: this.onboardingWsId,
                    client_name: this.onboardClientName,
                    client_email: this.onboardClientEmail
                });
                showToast('Onboarding iniciado com sucesso!', 'success');
                this.onboardClientName = '';
                this.onboardClientEmail = '';
                await this.loadOnboardings();
            } catch (e) {
                showToast('Erro ao iniciar onboarding', 'error');
            }
        },

        async updateOnboardingStep(onboardingId, stepNumber) {
            try {
                await apiCall('/api/agency/onboarding/' + onboardingId + '/step/' + stepNumber, 'PUT', {
                    status: 'completed'
                });
                showToast('Etapa ' + stepNumber + ' atualizada!', 'success');
                await this.loadOnboardings();
            } catch (e) {
                showToast('Erro ao atualizar etapa', 'error');
            }
        },

        getOnboardingProgress(ob) {
            if (!ob.steps) return 0;
            const completed = ob.steps.filter(s => s.status === 'completed').length;
            return Math.round((completed / 7) * 100);
        },

        getStepStatus(ob, step) {
            if (!ob.steps) return 'pending';
            const s = ob.steps.find(s => s.step_number === step);
            return s ? s.status : 'pending';
        },

        getStepLabel(step) {
            const labels = {
                1: 'Conta',
                2: 'Canais',
                3: 'Marca',
                4: 'Equipe',
                5: 'Conteudo',
                6: 'Integrar',
                7: 'Lancamento'
            };
            return labels[step] || '';
        },

        // ── Reports ─────────────────────────────────────────────────
        async loadReports() {
            try {
                const params = new URLSearchParams();
                if (this.reportWsId) params.set('workspace_id', this.reportWsId);
                params.set('limit', '20');
                const data = await apiCall('/api/agency/reports?' + params.toString());
                this.reports = Array.isArray(data) ? data : (data.reports || []);
            } catch (e) {
                showToast('Erro ao carregar relatorios', 'error');
                this.reports = [];
            }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async generateReport() {
            if (!this.reportWsId) return;
            try {
                await apiCall('/api/agency/workspaces/' + this.reportWsId + '/report', 'POST', {
                    report_type: this.reportType
                });
                showToast('Relatorio sendo gerado...', 'success');
                await this.loadReports();
            } catch (e) {
                showToast('Erro ao gerar relatorio', 'error');
            }
        },

        async viewReport(reportId) {
            try {
                const report = await apiCall('/api/agency/reports/' + reportId);
                // Open in a simple modal or alert for now
                if (report.content || report.data) {
                    const content = report.content || JSON.stringify(report.data, null, 2);
                    showToast('Relatorio carregado!', 'info');
                    // Could expand to a full modal in the future
                }
            } catch (e) {
                showToast('Erro ao carregar relatorio', 'error');
            }
        },

        async checkSLA() {
            if (!this.slaWsId) return;
            try {
                this.slaResult = await apiCall('/api/agency/sla/' + this.slaWsId);
                showToast('SLA verificado!', 'success');
            } catch (e) {
                showToast('Erro ao verificar SLA', 'error');
                this.slaResult = null;
            }
        },

        // ── Stats ───────────────────────────────────────────────────
        async loadStats() {
            try {
                this.stats = await apiCall('/api/agency/stats');
            } catch (e) {
                showToast('Erro ao carregar estatisticas', 'error');
                this.stats = null;
            }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        }
    };
}
</script>
{% endblock %}
