<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/views/pages/saas/SaasTwilioWhatsappPage.vue
| Data: 2026
|--------------------------------------------------------------------------
| Painel SaaS Admin — Gerenciamento de subcontas Twilio WhatsApp.
|   Aba 1 — Visão geral: todos os tenants provisionados + KPIs do mês
|   Aba 2 — Provisionar: criar subconta para um tenant
|   Aba 3 — Consumo: relatório de uso e margem por período
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import { useTwilioWhatsappStore } from '@/stores/twilioWhatsappStore';
import { supabase } from '@/lib/supabase/client';

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

// ── Card de setup ──────────────────────────────────────────────────────────
const showSetupCard = ref(true);

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

// ── Tenants ────────────────────────────────────────────────────────────────
const tenants        = ref([]);
const tenantMap      = ref({});
const loadingTenants = ref(false);

async function loadTenants() {
    loadingTenants.value = true;
    try {
        const { data, error } = await supabase.from('tenants').select('id, name, kind').order('name');
        if (error) throw error;
        tenantMap.value = Object.fromEntries((data ?? []).map(t => [t.id, t.name || t.id]));
        tenants.value   = (data ?? []).map(t => ({ value: t.id, label: `${t.name} (${t.kind ?? 'tenant'})` }));
    } finally {
        loadingTenants.value = false;
    }
}

// ── Provisionar ────────────────────────────────────────────────────────────
const provisionForm = ref({
    tenant_id:            null,
    phone_number:         '',
    country:              'BR',
    display_name:         '',
    cost_per_message_usd: '0.005',
    price_per_message_brl: '',
});
const showNumberSearch = ref(false);

function calcDefaultPrice() {
    const cost = parseFloat(provisionForm.value.cost_per_message_usd) || 0;
    const usdBrl = 5.5;
    const margin = 1.4;
    provisionForm.value.price_per_message_brl = (cost * usdBrl * margin).toFixed(4);
}

async function doProvision() {
    if (!provisionForm.value.tenant_id) {
        toast.add({ severity: 'warn', summary: 'Selecione um tenant', life: 3000 });
        return;
    }
    try {
        const opts = {
            country:               provisionForm.value.country,
            display_name:          provisionForm.value.display_name || undefined,
            cost_per_message_usd:  provisionForm.value.cost_per_message_usd,
            price_per_message_brl: provisionForm.value.price_per_message_brl,
        };
        if (provisionForm.value.phone_number) opts.phone_number = provisionForm.value.phone_number;

        const result = await store.provision(provisionForm.value.tenant_id, opts);
        toast.add({
            severity: 'success',
            summary:  'Subconta provisionada',
            detail:   result.message,
            life:     5000,
        });
        activeTab.value = 0;
        resetProvisionForm();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao provisionar', detail: e.message, life: 6000 });
    }
}

function resetProvisionForm() {
    provisionForm.value = {
        tenant_id: null, phone_number: '', country: 'BR',
        display_name: '', cost_per_message_usd: '0.005', price_per_message_brl: '',
    };
}

async function searchNumbers() {
    showNumberSearch.value = true;
    try {
        await store.loadAvailableNumbers(provisionForm.value.country);
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao buscar números', detail: e.message, life: 4000 });
    }
}

function selectNumber(num) {
    provisionForm.value.phone_number = num.phone_number;
    showNumberSearch.value = false;
}

// ── Ações sobre canais existentes ─────────────────────────────────────────

function confirmSuspend(ch) {
    confirm.require({
        message: `Suspender WhatsApp de "${tenantMap.value[ch.tenant_id] || ch.tenant_id}"? O tenant não poderá mais enviar mensagens.`,
        header:  'Suspender subconta',
        icon:    'pi pi-exclamation-triangle',
        acceptClass: 'p-button-warning',
        accept: async () => {
            try {
                await store.suspend(ch.channel_id);
                toast.add({ severity: 'success', summary: 'Subconta suspensa', life: 3000 });
            } catch (e) {
                toast.add({ severity: 'error', summary: 'Erro', detail: e.message, life: 4000 });
            }
        },
    });
}

function confirmReactivate(ch) {
    confirm.require({
        message: `Reativar WhatsApp de "${tenantMap.value[ch.tenant_id] || ch.tenant_id}"?`,
        header:  'Reativar subconta',
        icon:    'pi pi-check-circle',
        accept: async () => {
            try {
                await store.reactivate(ch.channel_id);
                toast.add({ severity: 'success', summary: 'Subconta reativada', life: 3000 });
            } catch (e) {
                toast.add({ severity: 'error', summary: 'Erro', detail: e.message, life: 4000 });
            }
        },
    });
}

function confirmDeprovision(ch) {
    confirm.require({
        message: `ATENÇÃO: Isso encerrará permanentemente a subconta Twilio de "${tenantMap.value[ch.tenant_id] || ch.tenant_id}" e liberará o número. Esta ação não pode ser desfeita.`,
        header:  'Encerrar subconta',
        icon:    'pi pi-times-circle',
        acceptClass: 'p-button-danger',
        accept: async () => {
            try {
                await store.deprovision(ch.channel_id);
                toast.add({ severity: 'success', summary: 'Subconta encerrada', life: 3000 });
            } catch (e) {
                toast.add({ severity: 'error', summary: 'Erro', detail: e.message, life: 4000 });
            }
        },
    });
}

// ── Teste de envio ─────────────────────────────────────────────────────────
const testDialog   = ref(false);
const testChannel  = ref(null);
const testToNumber = ref('');
const testMessage  = ref('Mensagem de teste — AgenciaPsi ✓');

function openTestDialog(ch) {
    testChannel.value  = ch;
    testToNumber.value = '';
    testDialog.value   = true;
}

async function doTestSend() {
    if (!testToNumber.value) {
        toast.add({ severity: 'warn', summary: 'Informe o número destino', life: 3000 });
        return;
    }
    try {
        const result = await store.testSendMessage(testChannel.value.channel_id, testToNumber.value, testMessage.value);
        toast.add({
            severity: 'success',
            summary:  'Mensagem enviada',
            detail:   `SID: ${result.message_sid}`,
            life:     5000,
        });
        testDialog.value = false;
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro no envio', detail: e.message, life: 5000 });
    }
}

// ── Precificação inline ────────────────────────────────────────────────────
const editingPricingId = ref(null);
const editPricing      = ref({ cost_per_message_usd: '', price_per_message_brl: '' });

function startEditPricing(ch) {
    editingPricingId.value = ch.channel_id;
    editPricing.value = {
        cost_per_message_usd:  ch.cost_per_message_usd ?? '',
        price_per_message_brl: ch.price_per_message_brl ?? '',
    };
}

async function savePricing(ch) {
    try {
        await store.updatePricing(ch.channel_id, {
            cost_per_message_usd:  parseFloat(editPricing.value.cost_per_message_usd) || 0,
            price_per_message_brl: parseFloat(editPricing.value.price_per_message_brl) || 0,
        });
        editingPricingId.value = null;
        toast.add({ severity: 'success', summary: 'Precificação atualizada', life: 3000 });
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e.message, life: 4000 });
    }
}

// ── Consumo ────────────────────────────────────────────────────────────────
async function loadUsage() {
    try {
        await store.loadUsageReport({ months: 3 });
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao carregar consumo', detail: e.message, life: 4000 });
    }
}

async function syncAll() {
    try {
        const result = await store.syncUsageAll();
        toast.add({ severity: 'success', summary: 'Consumo sincronizado', detail: `${result.synced?.length ?? 0} canal(is) atualizados`, life: 3000 });
    } catch (e) {
        toast.add({
            severity: 'warn',
            summary: 'Não foi possível sincronizar',
            detail: e.message,
            life: 6000
        });
    }
}

// ── Helpers ────────────────────────────────────────────────────────────────
function statusTag(ch) {
    if (!ch.twilio_subaccount_sid) return { label: 'Não provisionado', severity: 'secondary' };
    if (!ch.is_active) return { label: 'Suspenso', severity: 'warn' };
    switch (ch.connection_status) {
        case 'connected':    return { label: 'Ativo', severity: 'success' };
        case 'disconnected': return { label: 'Desconectado', severity: 'danger' };
        case 'error':        return { label: 'Erro', severity: 'danger' };
        default:             return { label: 'Ativo', severity: 'success' };
    }
}

function fmtBrl(v) {
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(v ?? 0);
}

function fmtUsd(v) {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(v ?? 0);
}

function fmtDate(dt) {
    if (!dt) return '—';
    return new Date(dt).toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' });
}

function fmtPeriod(dt) {
    if (!dt) return '—';
    return new Date(dt + 'T12:00:00').toLocaleDateString('pt-BR', { month: 'short', year: 'numeric' });
}

const countryCodes = [
    { label: 'Brasil (+55)', value: 'BR' },
    { label: 'EUA (+1)',     value: 'US' },
    { label: 'Portugal (+351)', value: 'PT' },
];

// ── Init ───────────────────────────────────────────────────────────────────
onMounted(async () => {
    await Promise.all([
        store.loadAllChannels(),
        loadTenants(),
    ]);
});
</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-whatsapp" /></div>
            <div class="min-w-0">
                <div class="cfg-subheader__title">WhatsApp Twilio — Subcontas</div>
                <div class="cfg-subheader__sub">Provisione e gerencie subcontas Twilio com número WhatsApp dedicado por tenant</div>
            </div>
        </div>

        <!-- Card de configuração inicial ──────────────────────────────── -->
        <div class="setup-card" v-if="showSetupCard">
            <!-- Faixa topo colorida -->
            <div class="setup-card__stripe" />

            <div class="setup-card__body">
                <!-- Título + fechar -->
                <div class="flex items-start justify-between gap-3">
                    <div class="flex items-center gap-3">
                        <div class="setup-card__icon">
                            <i class="pi pi-key text-xl" />
                        </div>
                        <div>
                            <div class="setup-card__title">Configuração de variáveis de ambiente</div>
                            <div class="setup-card__sub">Obrigatório para que as Edge Functions Twilio funcionem</div>
                        </div>
                    </div>
                    <Button icon="pi pi-times" text rounded size="small" severity="secondary" class="shrink-0 mt-0.5" v-tooltip.left="'Ocultar'" @click="showSetupCard = false" />
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4">
                    <!-- Bloco local -->
                    <div class="setup-block">
                        <div class="setup-block__header">
                            <i class="pi pi-desktop text-sm" />
                            <span>Ambiente local — <code class="setup-code-inline">.env</code> na raiz do projeto</span>
                        </div>
                        <pre class="setup-pre">TWILIO_ACCOUNT_SID=<span class="setup-pre__placeholder">ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</span>
TWILIO_AUTH_TOKEN=<span class="setup-pre__placeholder">xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</span>
TWILIO_WHATSAPP_WEBHOOK=<span class="setup-pre__placeholder">https://&lt;project&gt;.supabase.co/functions/v1/twilio-whatsapp-webhook</span>
USD_BRL_RATE=<span class="setup-pre__placeholder">5.50</span>
MARGIN_MULTIPLIER=<span class="setup-pre__placeholder">1.40</span></pre>
                        <div class="setup-block__tip">
                            <i class="pi pi-info-circle text-xs" />
                            O <code class="setup-code-inline">supabase/config.toml</code> já referencia essas vars via <code class="setup-code-inline">env()</code>.
                        </div>
                    </div>

                    <!-- Bloco produção -->
                    <div class="setup-block setup-block--prod">
                        <div class="setup-block__header">
                            <i class="pi pi-cloud text-sm" />
                            <span>Produção — Supabase Secrets</span>
                        </div>
                        <pre class="setup-pre">supabase secrets set \
  TWILIO_ACCOUNT_SID=<span class="setup-pre__placeholder">ACxxx</span> \
  TWILIO_AUTH_TOKEN=<span class="setup-pre__placeholder">xxx</span> \
  TWILIO_WHATSAPP_WEBHOOK=<span class="setup-pre__placeholder">https://...</span> \
  USD_BRL_RATE=5.50 \
  MARGIN_MULTIPLIER=1.40</pre>
                        <div class="setup-block__tip">
                            <i class="pi pi-info-circle text-xs" />
                            Após setar, faça deploy das 3 Edge Functions:
                            <code class="setup-code-inline">twilio-whatsapp-provision</code>,
                            <code class="setup-code-inline">process-whatsapp-queue</code>,
                            <code class="setup-code-inline">twilio-whatsapp-webhook</code>.
                        </div>
                    </div>
                </div>

                <!-- Canais no menu -->
                <div class="setup-menu-info mt-3">
                    <i class="pi pi-sitemap text-sm shrink-0" />
                    <div class="text-sm">
                        <strong>Menu SaaS — Canais:</strong>
                        <span class="mx-1 text-[var(--text-color-secondary)]">WhatsApp (Evolution API)</span>
                        <i class="pi pi-arrow-right text-xs opacity-40 mx-1" />
                        <span class="font-semibold text-green-600">/saas/whatsapp</span>
                        <span class="mx-2 opacity-30">|</span>
                        <span class="mx-1 text-[var(--text-color-secondary)]">WhatsApp Twilio (Subcontas)</span>
                        <i class="pi pi-arrow-right text-xs opacity-40 mx-1" />
                        <span class="font-semibold text-green-600">/saas/twilio-whatsapp</span>
                        <span class="ml-2 text-xs text-[var(--text-color-secondary)]">(esta página)</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- KPIs do mês ───────────────────────────────────────────────── -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
            <div class="kpi-card">
                <div class="kpi-label">Subcontas ativas</div>
                <div class="kpi-value text-green-600">{{ store.activeCount }}</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-label">Suspensas</div>
                <div class="kpi-value text-orange-500">{{ store.suspendedCount }}</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-label">Custo real (mês)</div>
                <div class="kpi-value text-red-500">{{ fmtBrl(store.totalMonthlyCostBrl) }}</div>
            </div>
            <div class="kpi-card">
                <div class="kpi-label">Margem bruta (mês)</div>
                <div class="kpi-value text-emerald-600">{{ fmtBrl(store.totalMonthlyMarginBrl) }}</div>
            </div>
        </div>

        <!-- Tabs ──────────────────────────────────────────────────────── -->
        <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-plus-circle mr-2" />Provisionar</Tab>
                <Tab :value="2" @click="loadUsage"><i class="pi pi-chart-bar mr-2" />Consumo</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">
                            <span class="text-sm text-[var(--text-color-secondary)]">
                                {{ store.allChannels.length }} subconta(s) Twilio WhatsApp
                            </span>
                            <div class="ml-auto flex gap-2">
                                <Button icon="pi pi-sync" size="small" severity="secondary" outlined label="Sincronizar uso" :loading="store.syncingUsage" @click="syncAll" />
                                <Button icon="pi pi-refresh" size="small" severity="secondary" outlined :loading="store.loadingChannels" @click="store.loadAllChannels" />
                            </div>
                        </div>

                        <DataTable :value="store.allChannels" :loading="store.loadingChannels" striped-rows responsive-layout="scroll" class="text-sm">
                            <!-- Tenant -->
                            <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>

                            <!-- Número -->
                            <Column header="Número WhatsApp" style="min-width: 150px">
                                <template #body="{ data }">
                                    <span v-if="data.twilio_phone_number" class="font-mono text-sm font-semibold">
                                        {{ data.twilio_phone_number }}
                                    </span>
                                    <span v-else class="text-[var(--text-color-secondary)] text-xs">—</span>
                                </template>
                            </Column>

                            <!-- Status -->
                            <Column header="Status" style="min-width: 110px">
                                <template #body="{ data }">
                                    <Tag :value="statusTag(data).label" :severity="statusTag(data).severity" class="text-[0.7rem]" />
                                </template>
                            </Column>

                            <!-- Consumo mês -->
                            <Column header="Msgs (mês)" style="min-width: 90px; text-align: right">
                                <template #body="{ data }">
                                    <div class="text-right">
                                        <span class="font-semibold">{{ data.current_month_sent ?? 0 }}</span>
                                        <span class="text-xs text-[var(--text-color-secondary)] ml-1">
                                            / {{ data.current_month_delivered ?? 0 }} entregues
                                        </span>
                                    </div>
                                </template>
                            </Column>

                            <!-- Custo -->
                            <Column header="Custo real" style="min-width: 100px; text-align: right">
                                <template #body="{ data }">
                                    <span class="text-red-500 font-mono text-xs">
                                        {{ fmtBrl(data.current_month_cost_brl) }}
                                    </span>
                                </template>
                            </Column>

                            <!-- Receita / Margem -->
                            <Column header="Margem" style="min-width: 110px; text-align: right">
                                <template #body="{ data }">
                                    <div class="text-right">
                                        <span class="text-emerald-600 font-mono text-xs font-semibold">
                                            {{ fmtBrl(data.current_month_margin_brl) }}
                                        </span>
                                        <div class="text-[0.65rem] text-[var(--text-color-secondary)]">
                                            receita {{ fmtBrl(data.current_month_revenue_brl) }}
                                        </div>
                                    </div>
                                </template>
                            </Column>

                            <!-- Precificação inline -->
                            <Column header="Preço/msg" style="min-width: 150px">
                                <template #body="{ data }">
                                    <div v-if="editingPricingId === data.channel_id" class="flex gap-1 items-center">
                                        <InputNumber v-model="editPricing.price_per_message_brl" mode="currency" currency="BRL" locale="pt-BR" :min-fraction-digits="4" :max-fraction-digits="4" class="w-24 text-xs" input-class="text-xs p-1" />
                                        <Button icon="pi pi-check" text rounded size="small" severity="success" @click="savePricing(data)" />
                                        <Button icon="pi pi-times" text rounded size="small" severity="secondary" @click="editingPricingId = null" />
                                    </div>
                                    <div v-else class="flex items-center gap-1 cursor-pointer group" @click="startEditPricing(data)">
                                        <span class="font-mono text-xs">{{ fmtBrl(data.price_per_message_brl) }}</span>
                                        <i class="pi pi-pencil text-[0.6rem] opacity-0 group-hover:opacity-50" />
                                    </div>
                                </template>
                            </Column>

                            <!-- Provisionado em -->
                            <Column header="Provisionado" style="min-width: 110px">
                                <template #body="{ data }">
                                    <span class="text-xs">{{ fmtDate(data.provisioned_at) }}</span>
                                </template>
                            </Column>

                            <!-- Ações -->
                            <Column header="" style="width: 130px">
                                <template #body="{ data }">
                                    <div class="flex gap-1 justify-end">
                                        <Button
                                            icon="pi pi-send"
                                            text rounded size="small" severity="info"
                                            v-tooltip.left="'Testar envio'"
                                            :disabled="!data.twilio_subaccount_sid || !data.is_active"
                                            @click="openTestDialog(data)"
                                        />
                                        <Button
                                            v-if="data.is_active"
                                            icon="pi pi-pause"
                                            text rounded size="small" severity="warning"
                                            v-tooltip.left="'Suspender'"
                                            :loading="store.suspending"
                                            @click="confirmSuspend(data)"
                                        />
                                        <Button
                                            v-else-if="data.twilio_subaccount_sid"
                                            icon="pi pi-play"
                                            text rounded size="small" severity="success"
                                            v-tooltip.left="'Reativar'"
                                            :loading="store.reactivating"
                                            @click="confirmReactivate(data)"
                                        />
                                        <Button
                                            icon="pi pi-trash"
                                            text rounded size="small" severity="danger"
                                            v-tooltip.left="'Encerrar subconta'"
                                            :disabled="!data.twilio_subaccount_sid"
                                            :loading="store.deprovisioning"
                                            @click="confirmDeprovision(data)"
                                        />
                                    </div>
                                </template>
                            </Column>

                            <template #empty>
                                <div class="text-center py-8 text-sm text-[var(--text-color-secondary)]">
                                    Nenhuma subconta Twilio WhatsApp provisionada ainda.
                                </div>
                            </template>
                        </DataTable>
                    </div>
                </TabPanel>

                <!-- ══ ABA 2 — Provisionar ═════════════════════════════ -->
                <TabPanel :value="1">
                    <div class="flex flex-col gap-4 pt-3 max-w-2xl">
                        <Message severity="info" :closable="false">
                            <template #messageicon><i class="pi pi-info-circle" /></template>
                            Cada tenant recebe uma subconta Twilio dedicada com número WhatsApp exclusivo.
                            O número precisará ser aprovado pelo WhatsApp Business via Twilio (pode levar alguns dias para números novos).
                        </Message>

                        <!-- Tenant -->
                        <div class="field-group">
                            <label class="field-label">Tenant *</label>
                            <Select
                                v-model="provisionForm.tenant_id"
                                :options="tenants" option-label="label" option-value="value"
                                placeholder="Selecione o tenant..." filter
                                :loading="loadingTenants"
                                class="w-full"
                            />
                        </div>

                        <!-- Nome exibição -->
                        <div class="field-group">
                            <label class="field-label">Nome de exibição</label>
                            <InputText v-model="provisionForm.display_name" placeholder="Ex: WhatsApp — Clínica Bem Estar" class="w-full" />
                        </div>

                        <!-- País + número -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="field-group">
                                <label class="field-label">País *</label>
                                <Select v-model="provisionForm.country" :options="countryCodes" option-label="label" option-value="value" class="w-full" />
                            </div>
                            <div class="field-group">
                                <label class="field-label">Número específico</label>
                                <div class="flex gap-2">
                                    <InputText v-model="provisionForm.phone_number" placeholder="+5511..." class="flex-1" />
                                    <Button icon="pi pi-search" size="small" severity="secondary" outlined v-tooltip.top="'Buscar disponíveis'" :loading="store.loadingNumbers" @click="searchNumbers" />
                                </div>
                                <small class="text-[var(--text-color-secondary)]">Deixe em branco para provisionar automaticamente.</small>
                            </div>
                        </div>

                        <!-- Resultados da busca de números -->
                        <div v-if="showNumberSearch && store.availableNumbers.length" class="border border-[var(--surface-border)] rounded-lg overflow-hidden">
                            <div class="px-3 py-2 bg-[var(--surface-ground)] flex items-center justify-between">
                                <span class="text-xs font-semibold">Números disponíveis</span>
                                <Button icon="pi pi-times" text rounded size="small" @click="showNumberSearch = false" />
                            </div>
                            <div class="max-h-48 overflow-y-auto divide-y divide-[var(--surface-border)]">
                                <div
                                    v-for="num in store.availableNumbers" :key="num.phone_number"
                                    class="px-3 py-2 flex items-center justify-between hover:bg-[var(--surface-ground)] cursor-pointer"
                                    @click="selectNumber(num)"
                                >
                                    <span class="font-mono text-sm font-semibold">{{ num.phone_number }}</span>
                                    <span class="text-xs text-[var(--text-color-secondary)]">{{ num.locality }}, {{ num.region }}</span>
                                </div>
                            </div>
                        </div>

                        <!-- Precificação -->
                        <div class="border border-[var(--surface-border)] rounded-lg overflow-hidden">
                            <div class="px-4 py-3 bg-[var(--surface-ground)] flex items-center gap-2">
                                <i class="pi pi-dollar text-sm opacity-60" />
                                <span class="text-sm font-semibold">Precificação por mensagem</span>
                            </div>
                            <div class="px-4 py-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div class="field-group">
                                    <label class="field-label">Custo Twilio (USD)</label>
                                    <InputText
                                        v-model="provisionForm.cost_per_message_usd"
                                        placeholder="0.005"
                                        class="w-full"
                                        @blur="calcDefaultPrice"
                                    />
                                    <small class="text-[var(--text-color-secondary)]">Custo real da Twilio por mensagem.</small>
                                </div>
                                <div class="field-group">
                                    <label class="field-label">Preço cobrado do tenant (BRL)</label>
                                    <InputText v-model="provisionForm.price_per_message_brl" placeholder="0.0385" class="w-full" />
                                    <small class="text-[var(--text-color-secondary)]">Inclua sua margem (padrão: custo × câmbio × 1,4).</small>
                                </div>
                            </div>
                        </div>

                        <div class="flex justify-end gap-2">
                            <Button label="Limpar" severity="secondary" outlined @click="resetProvisionForm" />
                            <Button
                                label="Provisionar subconta"
                                icon="pi pi-plus"
                                :loading="store.provisioning"
                                :disabled="!provisionForm.tenant_id || store.provisioning"
                                @click="doProvision"
                            />
                        </div>
                    </div>
                </TabPanel>

                <!-- ══ ABA 3 — Consumo ══════════════════════════════════ -->
                <TabPanel :value="2">
                    <div class="flex flex-col gap-3 pt-3">
                        <div class="flex items-center gap-2">
                            <span class="text-sm text-[var(--text-color-secondary)]">Últimos 3 meses por subconta</span>
                            <Button icon="pi pi-refresh" size="small" severity="secondary" outlined :loading="store.loadingUsage" class="ml-auto" @click="loadUsage" />
                        </div>

                        <DataTable :value="store.usageReport" :loading="store.loadingUsage" striped-rows responsive-layout="scroll" class="text-sm">
                            <Column header="Tenant" style="min-width: 160px">
                                <template #body="{ data }">{{ tenantMap[data.tenant_id] || data.tenant_id?.slice(0, 8) }}</template>
                            </Column>
                            <Column header="Período" style="min-width: 100px">
                                <template #body="{ data }">{{ fmtPeriod(data.period_start) }}</template>
                            </Column>
                            <Column header="Enviadas" field="messages_sent" style="min-width: 90px; text-align: right">
                                <template #body="{ data }"><span class="font-semibold">{{ data.messages_sent }}</span></template>
                            </Column>
                            <Column header="Entregues" field="messages_delivered" style="min-width: 90px; text-align: right">
                                <template #body="{ data }"><span class="text-green-600">{{ data.messages_delivered }}</span></template>
                            </Column>
                            <Column header="Falhas" field="messages_failed" style="min-width: 80px; text-align: right">
                                <template #body="{ data }"><span class="text-red-500">{{ data.messages_failed }}</span></template>
                            </Column>
                            <Column header="Custo (BRL)" style="min-width: 110px; text-align: right">
                                <template #body="{ data }"><span class="text-red-500 font-mono text-xs">{{ fmtBrl(data.cost_brl) }}</span></template>
                            </Column>
                            <Column header="Receita (BRL)" style="min-width: 110px; text-align: right">
                                <template #body="{ data }"><span class="text-blue-600 font-mono text-xs">{{ fmtBrl(data.revenue_brl) }}</span></template>
                            </Column>
                            <Column header="Margem" style="min-width: 110px; text-align: right">
                                <template #body="{ data }">
                                    <span class="font-semibold font-mono text-xs" :class="data.margin_brl >= 0 ? 'text-emerald-600' : 'text-red-500'">
                                        {{ fmtBrl(data.margin_brl) }}
                                    </span>
                                </template>
                            </Column>

                            <template #empty>
                                <div class="text-center py-8 text-sm text-[var(--text-color-secondary)]">
                                    Nenhum dado de consumo. Clique em "Sincronizar uso" na aba Visão geral.
                                </div>
                            </template>
                        </DataTable>
                    </div>
                </TabPanel>
            </TabPanels>
        </Tabs>

        <!-- Dialog: Teste de envio ────────────────────────────────────── -->
        <Dialog v-model:visible="testDialog" header="Testar envio WhatsApp" modal :style="{ width: '420px', maxWidth: '96vw' }" :draggable="false">
            <div class="flex flex-col gap-4 py-2">
                <div v-if="testChannel" class="text-sm text-[var(--text-color-secondary)]">
                    Enviando de <strong class="font-mono">{{ testChannel.twilio_phone_number }}</strong>
                    ({{ tenantMap[testChannel.tenant_id] || testChannel.tenant_id?.slice(0, 8) }})
                </div>
                <div class="field-group">
                    <label class="field-label">Número destino (E.164)</label>
                    <InputText v-model="testToNumber" placeholder="+5511999990000" class="w-full" />
                </div>
                <div class="field-group">
                    <label class="field-label">Mensagem</label>
                    <Textarea v-model="testMessage" rows="3" class="w-full" auto-resize />
                </div>
            </div>
            <template #footer>
                <Button label="Cancelar" text @click="testDialog = false" />
                <Button label="Enviar" icon="pi pi-send" :loading="store.testingSend" @click="doTestSend" />
            </template>
        </Dialog>

        <ConfirmDialog />
        <Toast />
    </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;
}
.kpi-card {
    padding: 0.875rem 1rem;
    border: 1px solid var(--surface-border);
    border-radius: 8px;
    background: var(--surface-card);
}
.kpi-label {
    font-size: 0.7rem; color: var(--text-color-secondary);
    text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 4px;
}
.kpi-value {
    font-size: 1.4rem; font-weight: 700; line-height: 1;
}
.field-group {
    display: flex; flex-direction: column; gap: 0.375rem;
}
.field-label {
    font-size: 0.75rem; font-weight: 600;
}

/* ── Card de Setup ──────────────────────────────────────────────────────── */
.setup-card {
    border-radius: 10px;
    border: 1px solid color-mix(in srgb, #f59e0b 45%, transparent);
    background: color-mix(in srgb, #fbbf24 6%, var(--surface-card));
    overflow: hidden;
    position: relative;
    box-shadow: 0 2px 12px color-mix(in srgb, #f59e0b 12%, transparent);
}
.setup-card__stripe {
    height: 4px;
    background: linear-gradient(90deg, #f59e0b 0%, #f97316 40%, #ef4444 100%);
}
.setup-card__body {
    padding: 1rem 1.25rem 1.25rem;
}
.setup-card__icon {
    display: grid; place-items: center;
    width: 2.75rem; height: 2.75rem; border-radius: 50%; flex-shrink: 0;
    background: linear-gradient(135deg, #f59e0b, #f97316);
    color: #fff;
    box-shadow: 0 2px 8px color-mix(in srgb, #f59e0b 40%, transparent);
}
.setup-card__title {
    font-size: 0.95rem; font-weight: 700; color: #92400e;
}
.setup-card__sub {
    font-size: 0.75rem; color: #b45309; margin-top: 2px;
}
.setup-block {
    background: color-mix(in srgb, #000 4%, var(--surface-card));
    border: 1px solid color-mix(in srgb, #f59e0b 25%, transparent);
    border-radius: 8px; overflow: hidden;
}
.setup-block--prod {
    border-color: color-mix(in srgb, #6366f1 30%, transparent);
    background: color-mix(in srgb, #6366f1 4%, var(--surface-card));
}
.setup-block__header {
    display: flex; align-items: center; gap: 0.5rem;
    padding: 0.5rem 0.875rem;
    background: color-mix(in srgb, #f59e0b 10%, var(--surface-ground));
    font-size: 0.75rem; font-weight: 600; color: #92400e;
    border-bottom: 1px solid color-mix(in srgb, #f59e0b 20%, transparent);
}
.setup-block--prod .setup-block__header {
    background: color-mix(in srgb, #6366f1 10%, var(--surface-ground));
    color: #4338ca;
    border-color: color-mix(in srgb, #6366f1 20%, transparent);
}
.setup-pre {
    margin: 0; padding: 0.75rem 0.875rem;
    font-family: 'JetBrains Mono', 'Fira Code', 'Courier New', monospace;
    font-size: 0.72rem; line-height: 1.7;
    color: var(--text-color);
    background: transparent;
    white-space: pre-wrap; word-break: break-all;
}
.setup-pre__placeholder {
    color: #9ca3af; font-style: italic;
}
.setup-block__tip {
    display: flex; align-items: flex-start; gap: 0.4rem;
    padding: 0.5rem 0.875rem;
    font-size: 0.72rem; color: var(--text-color-secondary);
    border-top: 1px dashed color-mix(in srgb, #f59e0b 20%, transparent);
    background: color-mix(in srgb, #000 2%, transparent);
}
.setup-code-inline {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.7rem; font-style: normal;
    background: color-mix(in srgb, #6366f1 10%, var(--surface-ground));
    color: #4338ca;
    padding: 0.1em 0.35em; border-radius: 3px;
    border: 1px solid color-mix(in srgb, #6366f1 20%, transparent);
}
.setup-menu-info {
    display: flex; align-items: center; gap: 0.75rem;
    padding: 0.625rem 0.875rem;
    background: color-mix(in srgb, #22c55e 6%, var(--surface-card));
    border: 1px solid color-mix(in srgb, #22c55e 25%, transparent);
    border-radius: 7px; flex-wrap: wrap;
}
</style>
