<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/views/pages/saas/SaasWhatsappPage.vue
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import { supabase } from '@/lib/supabase/client';
import { tenantSchemaName } from '@/lib/supabase/tenantClient';

const toast = useToast();
const confirm = useConfirm();

// ── Tenants ───────────────────────────────────────────────────
const tenants = ref([]);
const tenantMap = ref({});
const tenantSlugMap = ref({}); // { tenant_id: slug }
const loadingTenants = ref(false);
const selectedTenantId = ref(null);

// Slug do tenant selecionado — necessário pra montar o schema (tenant_<slug>),
// já que notification_channels/whatsapp_connection_incidents vivem no schema do tenant.
const selectedTenantSlug = computed(() => (selectedTenantId.value ? tenantSlugMap.value[selectedTenantId.value] || null : null));

// Client apontando pro schema do tenant selecionado. Lança se faltar slug —
// chamada a tabela tenant sem schema é sempre bug. RLS dos schemas permite is_saas_admin().
function selectedTenantDb() {
    const schema = tenantSchemaName(selectedTenantSlug.value);
    if (!schema) throw new Error('Tenant selecionado sem slug válido — não foi possível resolver o schema.');
    return supabase.schema(schema);
}

async function loadTenants() {
    loadingTenants.value = true;
    try {
        const { data, error } = await supabase.from('tenants').select('id, name, kind, slug').order('name', { ascending: true });
        if (error) throw error;

        const list = data || [];
        tenantMap.value = Object.fromEntries(list.map((t) => [t.id, t.name || t.id]));
        tenantSlugMap.value = Object.fromEntries(list.map((t) => [t.id, t.slug]));
        tenants.value = list.map((t) => ({
            value: t.id,
            label: `${t.name} (${t.kind ?? 'tenant'})`
        }));
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao carregar tenants', detail: e?.message, life: 4000 });
    } finally {
        loadingTenants.value = false;
    }
}

// ── Canal WhatsApp do tenant selecionado ──────────────────────
const channel = ref(null);
const credentials = ref({ api_url: '', api_key: '', instance_name: '' });
const hasCredentials = ref(false);
const loadingChannel = ref(false);
const savingCredentials = ref(false);

// Status de conexão
const connectionStatus = ref(null);
const connectionLoading = ref(false);

// QR Code
const qrDialog = ref(false);
const qrCodeBase64 = ref(null);
const qrLoading = ref(false);
const qrCountdown = ref(0);
let qrTimer = null;
let isMounted = true;

const connectionTag = computed(() => {
    if (!hasCredentials.value) return { label: 'Não configurado', severity: 'secondary' };
    if (channel.value && !channel.value.is_active) return { label: 'Desativado', severity: 'secondary' };
    if (connectionLoading.value) return { label: 'Verificando...', severity: 'secondary' };
    switch (connectionStatus.value) {
        case 'open':
            return { label: 'Conectado', severity: 'success' };
        case 'connecting':
            return { label: 'Conectando...', severity: 'warn' };
        default:
            return { label: 'Desconectado', severity: 'danger' };
    }
});

const selectedTenantName = computed(() => {
    if (!selectedTenantId.value) return '';
    return tenantMap.value[selectedTenantId.value] || selectedTenantId.value;
});

// Ao selecionar um tenant, carregar canal
async function onTenantSelect() {
    resetChannelState();
    if (!selectedTenantId.value) return;
    await loadChannel();
}

function resetChannelState() {
    channel.value = null;
    credentials.value = { api_url: '', api_key: '', instance_name: '' };
    hasCredentials.value = false;
    connectionStatus.value = null;
    clearQrTimer();
    qrCodeBase64.value = null;
}

const softDeletedChannel = ref(null);  // canal soft-deleted detectado p/ reativação

async function loadChannel() {
    if (!selectedTenantId.value) return;
    loadingChannel.value = true;
    softDeletedChannel.value = null;
    try {
        const tdb = selectedTenantDb();
        // 1) Tenta canal ativo (evolution_api) — schema do tenant já isola, sem .eq('tenant_id')
        const { data: active, error: activeErr } = await tdb
            .from('notification_channels')
            .select('*')
            .eq('channel', 'whatsapp')
            .eq('provider', 'evolution_api')
            .is('deleted_at', null)
            .maybeSingle();
        if (activeErr) throw activeErr;

        if (active) {
            channel.value = active;
            if (active.credentials) {
                credentials.value = {
                    api_url: active.credentials.api_url || '',
                    api_key: active.credentials.api_key || '',
                    instance_name: active.credentials.instance_name || ''
                };
                hasCredentials.value = true;
                if (active.is_active) await checkConnectionStatus();
            }
            return;
        }

        // 2) Não tem ativo — busca soft-deleted (evolution_api) pra poder reativar
        const { data: deleted } = await tdb
            .from('notification_channels')
            .select('*')
            .eq('channel', 'whatsapp')
            .eq('provider', 'evolution_api')
            .not('deleted_at', 'is', null)
            .order('created_at', { ascending: false })
            .limit(1)
            .maybeSingle();

        if (deleted) {
            softDeletedChannel.value = deleted;
            channel.value = null;   // UI vai mostrar estado de reativação
            if (deleted.credentials) {
                credentials.value = {
                    api_url: deleted.credentials.api_url || '',
                    api_key: deleted.credentials.api_key || '',
                    instance_name: deleted.credentials.instance_name || ''
                };
            }
        } else {
            channel.value = null;
        }
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao carregar canal', detail: e.message, life: 4000 });
    } finally {
        loadingChannel.value = false;
    }
}

// ── Salvar credenciais ────────────────────────────────────────
async function saveCredentials() {
    if (!selectedTenantId.value || savingCredentials.value) return;
    if (!credentials.value.api_url || !credentials.value.api_key || !credentials.value.instance_name) {
        toast.add({ severity: 'warn', summary: 'Preencha todos os campos', life: 3000 });
        return;
    }
    // Validação básica de URL
    try {
        new URL(credentials.value.api_url);
    } catch {
        toast.add({ severity: 'warn', summary: 'URL inválida', detail: 'A URL deve começar com http:// ou https://', life: 4000 });
        return;
    }
    savingCredentials.value = true;
    try {
        const tdb = selectedTenantDb();
        // Buscar o owner_id (dono do tenant) — tenant_members é GLOBAL (public)
        const { data: members, error: memErr } = await supabase.from('tenant_members').select('user_id').eq('tenant_id', selectedTenantId.value).in('role', ['tenant_admin', 'admin']).limit(1).single();
        if (memErr) throw memErr;

        const ownerId = members.user_id;
        const creds = { ...credentials.value };
        // Remover barra final da URL
        creds.api_url = creds.api_url.replace(/\/+$/, '');

        if (channel.value?.id) {
            // Canal ativo — só atualizar creds
            const { error } = await tdb
                .from('notification_channels')
                .update({
                    credentials: creds,
                    display_name: `WhatsApp — ${selectedTenantName.value}`,
                    is_active: true
                })
                .eq('id', channel.value.id);
            if (error) throw error;
        } else if (softDeletedChannel.value?.id) {
            // Soft-deleted — reativa via edge (bypass RLS + garante exclusividade)
            const { data: reactData, error: reactErr } = await supabase.functions.invoke('reactivate-notification-channel', {
                body: { channel_id: softDeletedChannel.value.id }
            });
            if (reactErr || !reactData?.ok) throw new Error(reactErr?.message || reactData?.error || 'reactivation_failed');

            // Depois de reativado, atualiza creds + display_name
            const { error: updErr } = await tdb
                .from('notification_channels')
                .update({
                    credentials: creds,
                    display_name: `WhatsApp — ${selectedTenantName.value}`
                })
                .eq('id', softDeletedChannel.value.id);
            if (updErr) throw updErr;

            toast.add({
                severity: 'success',
                summary: 'Canal reativado',
                detail: reactData.deactivated_others > 0
                    ? `Canal anterior foi reativado. ${reactData.deactivated_others} outro(s) canal(is) desativado(s).`
                    : 'Canal soft-deleted foi restaurado.',
                life: 4000
            });
        } else {
            // Novo — recarregar para evitar duplicata por race condition.
            // owner_id permanece (existe no schema) pra desambiguar canal por dono.
            const { data: existing } = await tdb.from('notification_channels').select('id').eq('owner_id', ownerId).eq('channel', 'whatsapp').is('deleted_at', null).maybeSingle();

            if (existing?.id) {
                // Já existe ativo (outro provider) — atualizar convertendo para evolution_api
                const { error } = await tdb
                    .from('notification_channels')
                    .update({
                        credentials: creds,
                        display_name: `WhatsApp — ${selectedTenantName.value}`,
                        is_active: true,
                        provider: 'evolution_api'
                    })
                    .eq('id', existing.id);
                if (error) throw error;
            } else {
                const { data, error } = await tdb
                    .from('notification_channels')
                    .insert({
                        owner_id: ownerId,
                        channel: 'whatsapp',
                        provider: 'evolution_api',
                        is_active: true,
                        display_name: `WhatsApp — ${selectedTenantName.value}`,
                        credentials: creds
                    })
                    .select('*')
                    .single();
                if (error) throw error;
                channel.value = data;
            }
        }

        hasCredentials.value = true;
        if (!softDeletedChannel.value) {
            toast.add({ severity: 'success', summary: 'Credenciais salvas', detail: `WhatsApp configurado para ${selectedTenantName.value}`, life: 3000 });
        }
        // Recarregar canal para sincronizar estado
        await loadChannel();
        // Atualiza lista da aba "Visão geral"
        loadAllChannels();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao salvar', detail: e.message, life: 5000 });
    } finally {
        savingCredentials.value = false;
    }
}

// ── Desativar WhatsApp do tenant ──────────────────────────────
function confirmDeactivate() {
    confirm.require({
        message: `Desativar o WhatsApp de "${selectedTenantName.value}"? O terapeuta não poderá mais enviar mensagens.`,
        header: 'Desativar WhatsApp',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        accept: async () => {
            try {
                const { error } = await selectedTenantDb().from('notification_channels').update({ is_active: false }).eq('id', channel.value.id);
                if (error) throw error;
                toast.add({ severity: 'success', summary: 'WhatsApp desativado', life: 3000 });
                await loadChannel();
            } catch (e) {
                toast.add({ severity: 'error', summary: 'Erro', detail: e.message, life: 4000 });
            }
        }
    });
}

// ── Status da conexão via Evolution API ───────────────────────
async function checkConnectionStatus() {
    if (!hasCredentials.value) return;
    connectionLoading.value = true;
    try {
        const res = await fetch(`${credentials.value.api_url}/instance/fetchInstances`, {
            headers: { apikey: credentials.value.api_key }
        });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const instances = await res.json();
        // Evolution v1: [{ instance: { instanceName, status } }] · v2: [{ instanceName, connectionStatus/state }]
        const arr = Array.isArray(instances) ? instances : [];
        const inst = arr.find((i) => {
            const name = i?.instance?.instanceName ?? i?.instanceName ?? i?.name;
            return name === credentials.value.instance_name;
        });
        const rawState = inst?.instance?.status ?? inst?.instance?.state ?? inst?.connectionStatus ?? inst?.state ?? inst?.status;
        connectionStatus.value = rawState || 'close';

        // Persiste no DB pra a tabela ficar em sync (mapeia pra valores que channelStatusTag entende)
        if (channel.value?.id) {
            const dbStatus = rawState === 'open' ? 'connected' : rawState === 'connecting' ? 'connecting' : 'disconnected';
            if (channel.value.connection_status !== dbStatus) {
                await selectedTenantDb()
                    .from('notification_channels')
                    .update({ connection_status: dbStatus, last_health_check: new Date().toISOString() })
                    .eq('id', channel.value.id);
                channel.value.connection_status = dbStatus;
                // Atualiza lista da tabela (sem bloquear)
                loadAllChannels();
            }
        }
    } catch (e) {
        connectionStatus.value = 'close';
        toast.add({
            severity: 'warn',
            summary: 'Não foi possível conectar à Evolution API',
            detail: 'Verifique a URL e a chave de API.',
            life: 5000
        });
    } finally {
        connectionLoading.value = false;
    }
}

// ── QR Code ───────────────────────────────────────────────────
async function fetchQrCode() {
    if (!isMounted) return;
    qrLoading.value = true;
    qrCodeBase64.value = null;
    clearQrTimer();
    try {
        const res = await fetch(`${credentials.value.api_url}/instance/connect/${credentials.value.instance_name}`, { headers: { apikey: credentials.value.api_key } });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const data = await res.json();
        // Evolution v1: data.qrcode.base64 · v2: data.base64 · variantes: data.code/qr/qrCode
        const base64 =
            data?.base64 ||
            data?.qrcode?.base64 ||
            data?.qrCode?.base64 ||
            data?.qr?.base64 ||
            data?.qr ||
            data?.code ||
            null;
        if (!base64) {
            const openState =
                data?.instance?.status === 'open' ||
                data?.instance?.state === 'open' ||
                data?.state === 'open' ||
                data?.status === 'open';
            if (openState) {
                connectionStatus.value = 'open';
                toast.add({ severity: 'success', summary: 'WhatsApp já está conectado!', life: 3000 });
                qrDialog.value = false;
                return;
            }
            console.error('[QR] Resposta inesperada da Evolution:', data);
            throw new Error('QR Code não retornado pela API. Veja o console (F12) pra debug.');
        }
        qrCodeBase64.value = base64.startsWith('data:') ? base64 : `data:image/png;base64,${base64}`;
        startQrCountdown();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao gerar QR Code', detail: e.message, life: 5000 });
    } finally {
        qrLoading.value = false;
    }
}

function startQrCountdown() {
    qrCountdown.value = 30;
    qrTimer = setInterval(() => {
        qrCountdown.value--;
        if (qrCountdown.value <= 0) {
            clearQrTimer();
            fetchQrCode();
        }
    }, 1000);
}

function clearQrTimer() {
    if (qrTimer) {
        clearInterval(qrTimer);
        qrTimer = null;
    }
    qrCountdown.value = 0;
}

function openQrDialog() {
    qrDialog.value = true;
    fetchQrCode();
}

function closeQrDialog() {
    qrDialog.value = false;
    clearQrTimer();
    qrCodeBase64.value = null;
    checkConnectionStatus();
}

// ── Visão geral: todos os canais WhatsApp ─────────────────────
const allChannels = ref([]);
const loadingAll = ref(false);
const openIncidentsByChannel = ref({});     // { channel_id: incident_row }
const incidents7dByChannel = ref({});       // { channel_id: count }
const heartbeatRunning = ref(false);

async function loadAllChannels() {
    loadingAll.value = true;
    try {
        // Overview cross-tenant: RPC agrega notification_channels + incidente aberto
        // de TODOS os schemas tenant_* (substitui os 3 selects em public, que sumiram
        // com a migração schema-per-tenant). Retorno é jsonb array direto.
        const { data, error } = await supabase.rpc('saas_list_all_whatsapp_channels');
        if (error) throw error;
        allChannels.value = data || [];

        // open_incident já vem por canal (kind do incidente aberto, ou null).
        // Reconstrói o mapa que a UI consome (chaveado por channel.id).
        const openMap = {};
        for (const ch of allChannels.value) {
            if (ch.open_incident) openMap[ch.id] = { kind: ch.open_incident };
        }
        openIncidentsByChannel.value = openMap;

        // TODO(schema-per-tenant): a RPC não expõe contagem de incidents nos últimos 7d
        // (o 3º select cross-tenant deixou de existir). Coluna "Incidents 7d" agora
        // mostra sempre 0. Adicionar agregação na RPC se a métrica voltar a ser útil.
        incidents7dByChannel.value = {};
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao carregar canais', detail: e.message, life: 4000 });
    } finally {
        loadingAll.value = false;
    }
}

async function runHeartbeatNow() {
    heartbeatRunning.value = true;
    try {
        const { data, error } = await supabase.functions.invoke('whatsapp-heartbeat-check', { body: {} });
        if (error) throw error;
        toast.add({
            severity: 'success',
            summary: 'Heartbeat executado',
            detail: `${data?.checked || 0} canais: ${data?.ok || 0} ok · ${data?.opened || 0} novos incidents · ${data?.resolved || 0} resolvidos`,
            life: 4500
        });
        await loadAllChannels();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e.message || 'Falha ao invocar heartbeat', life: 5000 });
    } finally {
        heartbeatRunning.value = false;
    }
}

function channelStatusTag(ch) {
    if (!ch.is_active) return { label: 'Desativado', severity: 'secondary' };
    switch (ch.connection_status) {
        case 'connected':
            return { label: 'Conectado', severity: 'success' };
        case 'connecting':
            return { label: 'Conectando', severity: 'warn' };
        case 'qr_pending':
            return { label: 'Aguardando QR', severity: 'warn' };
        case 'error':
            return { label: 'Erro', severity: 'danger' };
        default:
            return { label: 'Desconectado', severity: 'danger' };
    }
}

function formatDate(dt) {
    if (!dt) return '—';
    const d = new Date(dt);
    return d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' }) + ' ' + d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
}

function selectTenantFromTable(tenantId) {
    selectedTenantId.value = tenantId;
    activeTab.value = 1;
    onTenantSelect();
}

// ── Tabs ──────────────────────────────────────────────────────
const activeTab = ref(0);

// ── Inicialização ─────────────────────────────────────────────
onMounted(async () => {
    await Promise.all([loadTenants(), loadAllChannels()]);
});

onBeforeUnmount(() => {
    isMounted = false;
    clearQrTimer();
});
</script>

<template>
    <div class="flex flex-col gap-4 p-4">
        <!-- Header -->
        <div class="cfg-subheader">
            <div class="cfg-subheader__icon"><i class="pi pi-comments" /></div>
            <div class="min-w-0">
                <div class="cfg-subheader__title">Gerenciar WhatsApp</div>
                <div class="cfg-subheader__sub">Configure a integração WhatsApp para cada terapeuta ou clínica</div>
            </div>
        </div>

        <!-- Abas -->
        <Tabs :value="activeTab" @update:value="activeTab = $event">
            <TabList>
                <Tab :value="0"><i class="pi pi-list mr-2" />Visão geral</Tab>
                <Tab :value="1"><i class="pi pi-cog mr-2" />Configurar tenant</Tab>
            </TabList>

            <TabPanels>
                <!-- ══ ABA 1 — Visão geral ════════════════════════════════ -->
                <TabPanel :value="0">
                    <div class="flex flex-col gap-3 pt-3">
                        <div class="flex items-center gap-2 flex-wrap">
                            <span class="text-sm text-[var(--text-color-secondary)]">{{ allChannels.length }} canal(is) WhatsApp configurado(s)</span>
                            <span v-if="Object.keys(openIncidentsByChannel).length" class="inline-flex items-center gap-1 text-xs font-semibold text-red-600 bg-red-500/10 px-2 py-0.5 rounded-full">
                                <i class="pi pi-exclamation-circle" />
                                {{ Object.keys(openIncidentsByChannel).length }} incident(s) aberto(s)
                            </span>
                            <Button icon="pi pi-heart-fill" label="Verificar tudo agora" size="small" severity="warn" outlined :loading="heartbeatRunning" class="ml-auto" @click="runHeartbeatNow" />
                            <Button icon="pi pi-refresh" size="small" severity="secondary" outlined :loading="loadingAll" v-tooltip.bottom="'Recarregar'" @click="loadAllChannels" />
                        </div>

                        <DataTable :value="allChannels" :loading="loadingAll" responsive-layout="scroll" striped-rows class="text-sm">
                            <Column header="Tenant" style="min-width: 180px">
                                <template #body="{ data }">
                                    <div class="flex flex-col">
                                        <span class="font-semibold">{{ tenantMap[data.tenant_id] || '—' }}</span>
                                        <span class="text-xs text-[var(--text-color-secondary)] font-mono">{{ data.tenant_id?.slice(0, 8) }}…</span>
                                    </div>
                                </template>
                            </Column>
                            <Column header="Instância" style="min-width: 140px">
                                <template #body="{ data }">
                                    <span class="font-mono text-xs">{{ data.credentials?.instance_name || data.sender_address || data.twilio_phone_number || '—' }}</span>
                                </template>
                            </Column>
                            <Column header="Status" style="min-width: 120px">
                                <template #body="{ data }">
                                    <div class="flex flex-col gap-1">
                                        <Tag :value="channelStatusTag(data).label" :severity="channelStatusTag(data).severity" class="text-[0.7rem]" />
                                        <Tag v-if="openIncidentsByChannel[data.id]" value="Incident aberto" severity="danger" class="text-[0.6rem]" />
                                    </div>
                                </template>
                            </Column>
                            <Column header="Última check" style="min-width: 140px">
                                <template #body="{ data }">
                                    <span class="text-xs font-mono text-[var(--text-color-secondary)]">{{ data.last_health_check ? formatDate(data.last_health_check) : '—' }}</span>
                                </template>
                            </Column>
                            <Column header="Incidents 7d" style="min-width: 100px">
                                <template #body="{ data }">
                                    <span class="text-xs font-mono" :class="(incidents7dByChannel[data.id] || 0) > 0 ? 'text-orange-600 font-bold' : 'text-[var(--text-color-secondary)]'">
                                        {{ incidents7dByChannel[data.id] || 0 }}
                                    </span>
                                </template>
                            </Column>
                            <Column header="Ativo" style="min-width: 80px">
                                <template #body="{ data }">
                                    <Tag :value="data.is_active ? 'Sim' : 'Não'" :severity="data.is_active ? 'success' : 'secondary'" class="text-[0.7rem]" />
                                </template>
                            </Column>
                            <Column header="" style="width: 60px">
                                <template #body="{ data }">
                                    <Button icon="pi pi-pencil" text rounded size="small" severity="secondary" v-tooltip.left="'Configurar'" @click="selectTenantFromTable(data.tenant_id)" />
                                </template>
                            </Column>

                            <template #empty>
                                <div class="text-center py-6 text-sm text-[var(--text-color-secondary)]">Nenhum canal WhatsApp configurado ainda.</div>
                            </template>
                        </DataTable>
                    </div>
                </TabPanel>

                <!-- ══ ABA 2 — Configurar tenant ══════════════════════════ -->
                <TabPanel :value="1">
                    <div class="flex flex-col gap-4 pt-3">
                        <!-- Seletor de tenant -->
                        <div class="border border-[var(--surface-border)] rounded-lg p-4 bg-[var(--surface-card)]">
                            <div class="flex flex-col gap-2">
                                <label class="text-xs font-semibold">Selecionar terapeuta / clínica</label>
                                <div class="flex gap-2">
                                    <Select v-model="selectedTenantId" :options="tenants" option-label="label" option-value="value" placeholder="Escolha um tenant..." filter :loading="loadingTenants" class="flex-1" @change="onTenantSelect" />
                                </div>
                            </div>
                        </div>

                        <!-- Nenhum tenant selecionado -->
                        <div v-if="!selectedTenantId" class="border border-dashed border-[var(--surface-border)] rounded-lg p-6 text-center bg-[var(--surface-ground)]">
                            <i class="pi pi-arrow-up text-2xl text-[var(--text-color-secondary)] opacity-40 mb-2" />
                            <p class="text-sm text-[var(--text-color-secondary)] m-0">Selecione um tenant acima para configurar o WhatsApp.</p>
                        </div>

                        <!-- Loading -->
                        <div v-else-if="loadingChannel" class="flex justify-center py-8">
                            <ProgressSpinner style="width: 40px; height: 40px" />
                        </div>

                        <!-- Painel do tenant selecionado -->
                        <template v-else>
                            <!-- Status da conexão -->
                            <div class="border border-[var(--surface-border)] rounded-lg p-4 bg-[var(--surface-card)]">
                                <div class="flex items-center justify-between gap-3 flex-wrap">
                                    <div class="flex items-center gap-3">
                                        <div class="grid place-items-center w-10 h-10 rounded-full" :class="connectionStatus === 'open' ? 'bg-green-100 text-green-600' : 'bg-gray-100 text-gray-500'">
                                            <i class="pi pi-comments text-lg" />
                                        </div>
                                        <div>
                                            <div class="font-semibold text-sm">{{ selectedTenantName }}</div>
                                            <Tag :value="connectionTag.label" :severity="connectionTag.severity" class="text-xs mt-1" />
                                        </div>
                                    </div>
                                    <div class="flex gap-2">
                                        <Button :label="connectionStatus === 'open' ? 'Reconectar' : 'Conectar'" icon="pi pi-qrcode" size="small" :disabled="!hasCredentials" @click="openQrDialog" />
                                        <Button icon="pi pi-refresh" size="small" severity="secondary" outlined :loading="connectionLoading" :disabled="!hasCredentials" v-tooltip.bottom="'Verificar status'" @click="checkConnectionStatus" />
                                        <Button v-if="hasCredentials && channel?.is_active" icon="pi pi-power-off" size="small" severity="danger" outlined v-tooltip.bottom="'Desativar'" @click="confirmDeactivate" />
                                    </div>
                                </div>
                            </div>

                            <!-- Aviso de canal soft-deleted detectado -->
                            <div v-if="softDeletedChannel" class="rounded-md border border-amber-500/40 bg-amber-500/5 p-3 flex items-start gap-2 text-xs">
                                <i class="pi pi-history text-amber-600 mt-0.5" />
                                <div class="flex-1">
                                    <strong class="text-amber-700 dark:text-amber-400">Canal configurado anteriormente</strong><br>
                                    Este tenant tem um canal Evolution desativado (criado em <strong>{{ formatDate(softDeletedChannel.created_at) }}</strong>). As credenciais foram pré-carregadas abaixo — ajuste se precisar e clique em <strong>"Reativar e salvar"</strong>. Qualquer outro canal WhatsApp ativo será desativado pra manter apenas um por tenant.
                                </div>
                            </div>

                            <!-- Formulário de credenciais -->
                            <div class="border border-[var(--surface-border)] rounded-lg overflow-hidden">
                                <div class="flex items-center gap-2 px-4 py-3 bg-[var(--surface-ground)]">
                                    <i class="pi pi-key text-sm opacity-60" />
                                    <span class="text-sm font-semibold">Credenciais da Evolution API</span>
                                </div>
                                <div class="px-4 py-4 flex flex-col gap-4">
                                    <div class="flex flex-col gap-1.5">
                                        <label class="text-xs font-semibold">URL da Evolution API</label>
                                        <InputText v-model="credentials.api_url" placeholder="https://evolution.seudominio.com" class="w-full" />
                                    </div>
                                    <div class="flex flex-col gap-1.5">
                                        <label class="text-xs font-semibold">API Key</label>
                                        <InputText v-model="credentials.api_key" placeholder="Chave de API da Evolution" class="w-full" type="password" />
                                    </div>
                                    <div class="flex flex-col gap-1.5">
                                        <label class="text-xs font-semibold">Nome da instância</label>
                                        <InputText v-model="credentials.instance_name" placeholder="nome-da-instancia" class="w-full" />
                                    </div>
                                    <div class="flex justify-end">
                                        <Button :label="softDeletedChannel ? 'Reativar e salvar' : 'Salvar credenciais'" :icon="softDeletedChannel ? 'pi pi-refresh' : 'pi pi-save'" size="small" :severity="softDeletedChannel ? 'warn' : undefined" :loading="savingCredentials" :disabled="savingCredentials" @click="saveCredentials" />
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                </TabPanel>
            </TabPanels>
        </Tabs>

        <!-- ── Dialog QR Code ──────────────────────────────────────── -->
        <Dialog v-model:visible="qrDialog" :header="`Conectar WhatsApp — ${selectedTenantName}`" modal :style="{ width: '420px', maxWidth: '96vw' }" :draggable="false" @hide="closeQrDialog">
            <div class="flex flex-col items-center gap-4 py-2">
                <p class="text-sm text-[var(--text-color-secondary)] text-center m-0">Escaneie o QR Code com o WhatsApp do celular do terapeuta para conectar.</p>

                <div v-if="qrLoading" class="flex flex-col items-center gap-3 py-6">
                    <ProgressSpinner style="width: 48px; height: 48px" />
                    <span class="text-xs text-[var(--text-color-secondary)]">Gerando QR Code...</span>
                </div>

                <div v-else-if="qrCodeBase64" class="flex flex-col items-center gap-3">
                    <img :src="qrCodeBase64" alt="QR Code WhatsApp" class="w-64 h-64 rounded-lg border border-[var(--surface-border)]" />
                    <div class="flex items-center gap-2 text-xs text-[var(--text-color-secondary)]">
                        <i class="pi pi-clock" />
                        <span
                            >Atualiza automaticamente em <strong>{{ qrCountdown }}s</strong></span
                        >
                    </div>
                </div>

                <div v-else class="text-center py-6">
                    <i class="pi pi-exclamation-circle text-3xl text-[var(--text-color-secondary)] opacity-40 mb-2" />
                    <p class="text-sm text-[var(--text-color-secondary)] m-0">Não foi possível gerar o QR Code.</p>
                </div>

                <Button label="Atualizar QR Code" icon="pi pi-refresh" size="small" severity="secondary" outlined :loading="qrLoading" @click="fetchQrCode" />
            </div>

            <template #footer>
                <Button label="Fechar" text @click="closeQrDialog" />
            </template>
        </Dialog>

        <ConfirmDialog />
    </div>
</template>

<style scoped>
.cfg-subheader {
    display: flex;
    align-items: center;
    gap: 0.65rem;
    padding: 0.875rem 1rem;
    border-radius: 6px;
    border: 1px solid color-mix(in srgb, var(--primary-color, #6366f1) 30%, transparent);
    background: linear-gradient(135deg, color-mix(in srgb, var(--primary-color, #6366f1) 12%, var(--surface-card)) 0%, color-mix(in srgb, var(--primary-color, #6366f1) 4%, var(--surface-card)) 60%, var(--surface-card) 100%);
    position: relative;
    overflow: hidden;
}
.cfg-subheader::before {
    content: '';
    position: absolute;
    top: -20px;
    right: -20px;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: color-mix(in srgb, var(--primary-color, #6366f1) 15%, transparent);
    filter: blur(20px);
    pointer-events: none;
}
.cfg-subheader__icon {
    display: grid;
    place-items: center;
    width: 2rem;
    height: 2rem;
    border-radius: 6px;
    flex-shrink: 0;
    background: color-mix(in srgb, var(--primary-color, #6366f1) 20%, transparent);
    color: var(--primary-color, #6366f1);
    font-size: 0.85rem;
}
.cfg-subheader__title {
    font-size: 0.95rem;
    font-weight: 700;
    letter-spacing: -0.01em;
    color: var(--primary-color, #6366f1);
}
.cfg-subheader__sub {
    font-size: 0.75rem;
    color: var(--text-color-secondary);
    opacity: 0.85;
}
</style>
