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

import { tenantDb } from '@/lib/supabase/tenantClient';
const toast = useToast();
const confirm = useConfirm();

// ── Constantes ────────────────────────────────────────────────
const AVATAR_BUCKET = 'avatars';

const TIPO_OPTIONS = ['MEI', 'ME', 'EPP', 'EIRELI', 'SLU', 'LTDA', 'S/A', 'Associação', 'Fundação', 'Cooperativa', 'Outro'];

const REDES_OPTIONS = [
    { label: 'Instagram', value: 'instagram' },
    { label: 'Facebook', value: 'facebook' },
    { label: 'LinkedIn', value: 'linkedin' },
    { label: 'X / Twitter', value: 'twitter' },
    { label: 'YouTube', value: 'youtube' },
    { label: 'TikTok', value: 'tiktok' },
    { label: 'WhatsApp', value: 'whatsapp' },
    { label: 'Telegram', value: 'telegram' },
    { label: 'Pinterest', value: 'pinterest' },
    { label: 'Outro', value: 'outro' }
];

const REDE_ICONS = {
    instagram: 'pi-instagram',
    facebook: 'pi-facebook',
    linkedin: 'pi-linkedin',
    twitter: 'pi-twitter',
    youtube: 'pi-youtube',
    whatsapp: 'pi-whatsapp',
    tiktok: 'pi-tiktok',
    telegram: 'pi-send',
    pinterest: 'pi-heart',
    outro: 'pi-link'
};

const ESTADOS = ['AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO'];

// ── Estado ────────────────────────────────────────────────────
const tenantId = ref(null);
const recordId = ref(null);
const loading = ref(true);
const saving = ref(false);
const loadingCep = ref(false);

const form = ref({
    nome_fantasia: '',
    razao_social: '',
    tipo_empresa: null,
    cnpj: '',
    ie: '',
    im: '',
    cep: '',
    logradouro: '',
    numero: '',
    complemento: '',
    bairro: '',
    cidade: '',
    estado: null,
    email: '',
    telefone: '',
    site: '',
    logo_url: '',
    redes_sociais: []
});

// ── Computed preview ──────────────────────────────────────────
const logoDisplay = computed(() => logoPreview.value || form.value.logo_url || null);

const enderecoLinhas = computed(() => {
    const f = form.value;
    const lines = [];
    if (f.logradouro) {
        let l = f.logradouro;
        if (f.numero) l += `, ${f.numero}`;
        if (f.complemento) l += ` — ${f.complemento}`;
        lines.push(l);
    }
    if (f.bairro) lines.push(f.bairro);
    const ce = [f.cidade, f.estado].filter(Boolean).join(' / ');
    if (ce) lines.push(ce);
    if (f.cep) lines.push(`CEP ${f.cep}`);
    return lines;
});

const redesValidas = computed(() => form.value.redes_sociais.filter((r) => r.rede && r.url));

const temDados = computed(() => !!(form.value.nome_fantasia || form.value.razao_social || logoDisplay.value));

// ── Logo upload ───────────────────────────────────────────────
const logoInputRef = ref(null);
const logoPreview = ref(null);
const logoFile = ref(null);
const uploadingLogo = ref(false);

function onLogoClick() {
    logoInputRef.value?.click();
}

function onLogoChange(e) {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml'].includes(file.type)) {
        toast.add({ severity: 'warn', summary: 'Formato inválido', detail: 'Use JPG, PNG, WEBP ou SVG.', life: 3000 });
        return;
    }
    logoFile.value = file;
    logoPreview.value = URL.createObjectURL(file);
}

function removeLogo() {
    logoFile.value = null;
    logoPreview.value = null;
    form.value.logo_url = '';
    if (logoInputRef.value) logoInputRef.value.value = '';
}

async function uploadLogo() {
    if (!logoFile.value || !tenantId.value) return form.value.logo_url;
    const ext = logoFile.value.name.split('.').pop().toLowerCase();
    const path = `${tenantId.value}/company-logo-${Date.now()}.${ext}`;
    uploadingLogo.value = true;
    try {
        const { error } = await supabase.storage.from(AVATAR_BUCKET).upload(path, logoFile.value, { upsert: true, contentType: logoFile.value.type });
        if (error) throw error;
        const { data } = supabase.storage.from(AVATAR_BUCKET).getPublicUrl(path);
        return data?.publicUrl || '';
    } finally {
        uploadingLogo.value = false;
    }
}

// ── CEP ───────────────────────────────────────────────────────
async function buscarCep() {
    const cep = form.value.cep.replace(/\D/g, '');
    if (cep.length !== 8) return;
    loadingCep.value = true;
    try {
        const res = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
        const data = await res.json();
        if (data.erro) {
            toast.add({ severity: 'warn', summary: 'CEP não encontrado', life: 3000 });
            return;
        }
        form.value.logradouro = data.logradouro || '';
        form.value.bairro = data.bairro || '';
        form.value.cidade = data.localidade || '';
        form.value.estado = data.uf || null;
    } catch {
        toast.add({ severity: 'error', summary: 'Erro ao buscar CEP', life: 3000 });
    } finally {
        loadingCep.value = false;
    }
}

// ── Redes sociais ─────────────────────────────────────────────
function addRede() {
    form.value.redes_sociais.push({ rede: null, url: '' });
}
function removeRede(i) {
    const rede = form.value.redes_sociais[i];
    const label = REDES_OPTIONS.find((o) => o.value === rede?.rede)?.label || rede?.rede || 'esta rede social';
    confirm.require({
        message: `Deseja remover ${label}?`,
        header: 'Remover rede social',
        icon: 'pi pi-exclamation-triangle',
        rejectLabel: 'Cancelar',
        acceptLabel: 'Remover',
        acceptClass: 'p-button-danger',
        accept: () => form.value.redes_sociais.splice(i, 1)
    });
}

// ── Load / Save ───────────────────────────────────────────────
async function load() {
    loading.value = true;
    try {
        const {
            data: { user }
        } = await supabase.auth.getUser();
        if (!user) return;
        tenantId.value = user.id;
        const { data } = await tenantDb().from('company_profiles').select('*').maybeSingle();
        if (data) {
            recordId.value = data.id;
            Object.keys(form.value).forEach((k) => {
                if (data[k] !== undefined && data[k] !== null) form.value[k] = data[k];
            });
            if (data.logo_url) logoPreview.value = data.logo_url;
        }
    } finally {
        loading.value = false;
    }
}

async function save() {
    const {
        data: { user }
    } = await supabase.auth.getUser();
    if (!user) {
        toast.add({ severity: 'error', summary: 'Sessão expirada', detail: 'Faça login novamente.', life: 4000 });
        return;
    }
    tenantId.value = user.id;
    saving.value = true;
    try {
        if (logoFile.value) form.value.logo_url = await uploadLogo();

        const payload = {
            nome_fantasia: form.value.nome_fantasia || null,
            razao_social: form.value.razao_social || null,
            tipo_empresa: form.value.tipo_empresa || null,
            cnpj: form.value.cnpj || null,
            ie: form.value.ie || null,
            im: form.value.im || null,
            cep: form.value.cep || null,
            logradouro: form.value.logradouro || null,
            numero: form.value.numero || null,
            complemento: form.value.complemento || null,
            bairro: form.value.bairro || null,
            cidade: form.value.cidade || null,
            estado: form.value.estado || null,
            email: form.value.email || null,
            telefone: form.value.telefone || null,
            site: form.value.site || null,
            logo_url: form.value.logo_url || null,
            redes_sociais: form.value.redes_sociais.filter((r) => r.rede && r.url)
        };

        if (recordId.value) {
            const { error } = await tenantDb().from('company_profiles').update(payload).eq('id', recordId.value);
            if (error) throw error;
        } else {
            const { data, error } = await tenantDb().from('company_profiles').insert(payload).select('id').single();
            if (error) throw error;
            recordId.value = data.id;
        }

        logoFile.value = null;
        toast.add({ severity: 'success', summary: 'Dados salvos com sucesso', life: 3000 });
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao salvar', detail: e.message, life: 5000 });
    } finally {
        saving.value = false;
    }
}

// ── Dados de exemplo ──────────────────────────────────────────
function preencherExemplo() {
    form.value.nome_fantasia = 'Clínica Mente Sã';
    form.value.razao_social = 'Mente Sã Serviços de Psicologia Ltda';
    form.value.tipo_empresa = 'LTDA';
    form.value.cnpj = '12.345.678/0001-90';
    form.value.ie = '123.456.789.110';
    form.value.im = '98765-4';
    form.value.cep = '13561-260';
    form.value.logradouro = 'Rua Episcopal';
    form.value.numero = '738';
    form.value.complemento = 'Sala 12 — 2º andar';
    form.value.bairro = 'Centro';
    form.value.cidade = 'São Carlos';
    form.value.estado = 'SP';
    form.value.email = 'contato@mentesa.com.br';
    form.value.telefone = '(16) 99123-4567';
    form.value.site = 'https://www.mentesa.com.br';
    form.value.redes_sociais = [
        { rede: 'instagram', url: 'https://instagram.com/mentesa' },
        { rede: 'facebook', url: 'https://facebook.com/mentesa' },
        { rede: 'linkedin', url: 'https://linkedin.com/company/mentesa' },
        { rede: 'whatsapp', url: 'https://wa.me/5516991234567' }
    ];
}

onMounted(load);
</script>

<template>
    <ConfirmDialog />
    <div class="flex flex-col gap-4">
        <!-- ══ SKELETON ══════════════════════════════════════════════ -->
        <template v-if="loading">
            <div class="flex gap-4 items-start">
                <!-- Esqueleto formulário -->
                <div class="form-col flex flex-col gap-4">
                    <div v-for="n in 3" :key="n" class="cfg-card">
                        <div class="cfg-card__head">
                            <Skeleton width="1rem" height="1rem" border-radius="4px" />
                            <Skeleton :width="n === 1 ? '7rem' : n === 2 ? '9rem' : '8rem'" height="12px" />
                        </div>
                        <div class="flex flex-col gap-3 p-4">
                            <div class="grid grid-cols-2 gap-3">
                                <Skeleton height="2.5rem" border-radius="6px" />
                                <Skeleton height="2.5rem" border-radius="6px" />
                            </div>
                            <Skeleton height="2.5rem" border-radius="6px" />
                        </div>
                    </div>
                </div>
                <!-- Esqueleto preview -->
                <div class="preview-col">
                    <Skeleton height="320px" border-radius="12px" />
                </div>
            </div>
            <AppLoadingPhrases action="Carregando dados da empresa..." containerClass="py-6" />
        </template>

        <!-- Corpo: formulário + preview -->
        <template v-else>
            <div class="flex gap-4 items-start">
                <!-- ── Formulário (60%) ───────────────────────────────── -->
                <div class="form-col">
                    <!-- Logomarca -->
                    <div class="cfg-card">
                        <div class="cfg-card__head">
                            <i class="pi pi-image text-xs opacity-50" />
                            <span>Logomarca</span>
                        </div>
                        <div class="flex items-center gap-5 px-4 py-4">
                            <div class="logo-upload-preview" :class="{ empty: !logoDisplay }" @click="onLogoClick">
                                <img v-if="logoDisplay" :src="logoDisplay" alt="Logo" class="w-full h-full object-contain p-1" />
                                <div v-else class="flex flex-col items-center gap-1 opacity-40">
                                    <i class="pi pi-image text-2xl" />
                                    <span class="text-[0.65rem]">Clique para adicionar</span>
                                </div>
                            </div>
                            <input ref="logoInputRef" type="file" accept="image/*" class="hidden" @change="onLogoChange" />
                            <div class="flex flex-col gap-2">
                                <Button label="Carregar imagem" icon="pi pi-upload" size="small" outlined @click="onLogoClick" :loading="uploadingLogo" />
                                <Button v-if="logoDisplay" label="Remover" icon="pi pi-trash" size="small" severity="danger" text @click="removeLogo" />
                                <p class="text-[0.7rem] text-[var(--text-color-secondary)] m-0">JPG, PNG, WEBP ou SVG.<br />Recomendado: fundo transparente.</p>
                            </div>
                        </div>
                    </div>

                    <!-- Identificação -->
                    <div class="cfg-card mt-4">
                        <div class="cfg-card__head">
                            <i class="pi pi-id-card text-xs opacity-50" />
                            <span>Identificação</span>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3 px-4 py-4">
                            <div class="flex flex-col gap-1">
                                <label class="cfg-label">Nome fantasia</label>
                                <InputText v-model="form.nome_fantasia" placeholder="Nome comercial da empresa" class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1">
                                <label class="cfg-label">Razão social</label>
                                <InputText v-model="form.razao_social" placeholder="Razão social completa" class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1">
                                <label class="cfg-label">Tipo de empresa</label>
                                <Select v-model="form.tipo_empresa" :options="TIPO_OPTIONS" placeholder="Selecione" class="w-full" show-clear />
                            </div>
                            <div class="flex flex-col gap-1">
                                <label class="cfg-label">CNPJ</label>
                                <InputText v-model="form.cnpj" placeholder="00.000.000/0001-00" class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1">
                                <label class="cfg-label">Inscrição Estadual (IE)</label>
                                <InputText v-model="form.ie" placeholder="Inscrição Estadual" class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1">
                                <label class="cfg-label">Inscrição Municipal (IM)</label>
                                <InputText v-model="form.im" placeholder="Inscrição Municipal" class="w-full" />
                            </div>
                        </div>
                    </div>

                    <!-- Endereço -->
                    <div class="cfg-card mt-4">
                        <div class="cfg-card__head">
                            <i class="pi pi-map-marker text-xs opacity-50" />
                            <span>Endereço</span>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-6 gap-3 px-4 py-4">
                            <div class="flex flex-col gap-1 md:col-span-2">
                                <label class="cfg-label">CEP</label>
                                <div class="flex gap-2">
                                    <InputText v-model="form.cep" placeholder="00000-000" class="w-full" @blur="buscarCep" @keydown.enter.prevent="buscarCep" />
                                    <Button icon="pi pi-search" severity="secondary" outlined :loading="loadingCep" @click="buscarCep" v-tooltip="'Buscar CEP'" />
                                </div>
                            </div>
                            <div class="flex flex-col gap-1 md:col-span-3">
                                <label class="cfg-label">Logradouro</label>
                                <InputText v-model="form.logradouro" placeholder="Rua, Avenida..." class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1 md:col-span-1">
                                <label class="cfg-label">Número</label>
                                <InputText v-model="form.numero" placeholder="Nº" class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1 md:col-span-2">
                                <label class="cfg-label">Complemento</label>
                                <InputText v-model="form.complemento" placeholder="Sala, apto..." class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1 md:col-span-2">
                                <label class="cfg-label">Bairro</label>
                                <InputText v-model="form.bairro" placeholder="Bairro" class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1 md:col-span-2">
                                <label class="cfg-label">Cidade</label>
                                <InputText v-model="form.cidade" placeholder="Cidade" class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1 md:col-span-2">
                                <label class="cfg-label">Estado</label>
                                <Select v-model="form.estado" :options="ESTADOS" placeholder="UF" class="w-full" show-clear />
                            </div>
                        </div>
                    </div>

                    <!-- Contato -->
                    <div class="cfg-card mt-4">
                        <div class="cfg-card__head">
                            <i class="pi pi-globe text-xs opacity-50" />
                            <span>Contato e Presença Digital</span>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-3 px-4 py-4">
                            <div class="flex flex-col gap-1">
                                <label class="cfg-label">E-mail da empresa</label>
                                <InputText v-model="form.email" placeholder="contato@empresa.com.br" class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1">
                                <label class="cfg-label">Telefone / WhatsApp</label>
                                <InputText v-model="form.telefone" placeholder="(00) 00000-0000" class="w-full" />
                            </div>
                            <div class="flex flex-col gap-1">
                                <label class="cfg-label">Site</label>
                                <InputText v-model="form.site" placeholder="https://www.empresa.com.br" class="w-full" />
                            </div>
                        </div>
                    </div>

                    <!-- Redes Sociais -->
                    <div class="cfg-card mt-4">
                        <div class="cfg-card__head">
                            <i class="pi pi-share-alt text-xs opacity-50" />
                            <span>Redes Sociais</span>
                            <Button label="Adicionar" icon="pi pi-plus" size="small" severity="secondary" outlined class="ml-auto" @click="addRede" />
                        </div>
                        <div class="px-4 py-3 flex flex-col gap-2">
                            <p v-if="form.redes_sociais.length === 0" class="text-sm text-[var(--text-color-secondary)] italic m-0 py-2">Nenhuma rede social adicionada.</p>
                            <div v-for="(item, i) in form.redes_sociais" :key="i" class="flex gap-2 items-center">
                                <Select v-model="item.rede" :options="REDES_OPTIONS" option-label="label" option-value="value" placeholder="Rede" class="w-40 shrink-0" />
                                <InputText v-model="item.url" :placeholder="item.rede ? `URL do ${item.rede}` : 'URL do perfil'" class="flex-1" />
                                <Button icon="pi pi-trash" severity="danger" text rounded size="small" @click="removeRede(i)" />
                            </div>
                        </div>
                    </div>

                    <!-- Salvar -->
                    <div class="flex justify-end mt-4 pb-2">
                        <Button label="Salvar dados da empresa" icon="pi pi-check" :loading="saving" @click="save" />
                    </div>

                    <LoadedPhraseBlock />
                </div>

                <!-- ── Preview (40%) ──────────────────────────────────── -->
                <div class="preview-col">
                    <div class="preview-card">
                        <!-- Placeholder vazio -->
                        <div v-if="!temDados" class="preview-empty">
                            <i class="pi pi-building text-3xl opacity-20" />
                            <p class="text-xs opacity-40 mt-2 text-center">Preencha os dados<br />para ver o preview</p>
                        </div>

                        <template v-else>
                            <!-- Logo -->
                            <div class="preview-logo-wrap">
                                <img v-if="logoDisplay" :src="logoDisplay" alt="Logo" class="preview-logo" />
                                <div v-else class="preview-logo-placeholder">
                                    <i class="pi pi-building text-xl opacity-30" />
                                </div>
                            </div>

                            <!-- Nome + tipo -->
                            <div class="preview-name-block">
                                <h2 v-if="form.nome_fantasia" class="preview-name">{{ form.nome_fantasia }}</h2>
                                <p v-if="form.razao_social" class="preview-razao">{{ form.razao_social }}</p>
                                <span v-if="form.tipo_empresa" class="preview-tipo">{{ form.tipo_empresa }}</span>
                            </div>

                            <!-- Documentos -->
                            <div v-if="form.cnpj || form.ie || form.im" class="preview-section">
                                <div class="preview-divider" />
                                <div class="preview-docs">
                                    <div v-if="form.cnpj" class="preview-doc-row">
                                        <span class="preview-doc-label">CNPJ</span>
                                        <span class="preview-doc-value">{{ form.cnpj }}</span>
                                    </div>
                                    <div v-if="form.ie" class="preview-doc-row">
                                        <span class="preview-doc-label">IE</span>
                                        <span class="preview-doc-value">{{ form.ie }}</span>
                                    </div>
                                    <div v-if="form.im" class="preview-doc-row">
                                        <span class="preview-doc-label">IM</span>
                                        <span class="preview-doc-value">{{ form.im }}</span>
                                    </div>
                                </div>
                            </div>

                            <!-- Endereço -->
                            <div v-if="enderecoLinhas.length" class="preview-section">
                                <div class="preview-divider" />
                                <div class="preview-info-row">
                                    <i class="pi pi-map-marker preview-info-icon" />
                                    <div class="flex flex-col gap-0.5">
                                        <span v-for="(linha, i) in enderecoLinhas" :key="i" class="preview-info-text">{{ linha }}</span>
                                    </div>
                                </div>
                            </div>

                            <!-- Contato -->
                            <div v-if="form.email || form.telefone || form.site" class="preview-section">
                                <div class="preview-divider" />
                                <div class="flex flex-col gap-1.5">
                                    <div v-if="form.email" class="preview-info-row">
                                        <i class="pi pi-envelope preview-info-icon" />
                                        <span class="preview-info-text">{{ form.email }}</span>
                                    </div>
                                    <div v-if="form.telefone" class="preview-info-row">
                                        <i class="pi pi-phone preview-info-icon" />
                                        <span class="preview-info-text">{{ form.telefone }}</span>
                                    </div>
                                    <div v-if="form.site" class="preview-info-row">
                                        <i class="pi pi-globe preview-info-icon" />
                                        <span class="preview-info-text truncate">{{ form.site }}</span>
                                    </div>
                                </div>
                            </div>

                            <!-- Redes sociais -->
                            <div v-if="redesValidas.length" class="preview-section">
                                <div class="preview-divider" />
                                <div class="flex flex-wrap gap-2">
                                    <a v-for="(r, i) in redesValidas" :key="i" :href="r.url" target="_blank" class="preview-rede" :title="r.rede">
                                        <i :class="`pi ${REDE_ICONS[r.rede] || 'pi-link'}`" />
                                        <span>{{ REDES_OPTIONS.find((o) => o.value === r.rede)?.label ?? r.rede }}</span>
                                    </a>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </template>
    </div>
</template>

<style scoped>
/* ── Layout colunas ────────────────────────────────────────── */
.preview-col {
    width: 40%;
    flex-shrink: 0;
    position: sticky;
    top: calc(var(--layout-sticky-top, 56px) + 58px);
    align-self: flex-start;
}
.form-col {
    flex: 1;
    min-width: 0;
}

/* ── Preview card ──────────────────────────────────────────── */
.preview-card {
    border: 1px solid var(--surface-border);
    border-radius: 12px;
    background: var(--surface-card);
    overflow: hidden;
    padding: 1.5rem;
    display: flex;
    flex-direction: column;
    gap: 0;
}
.preview-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 200px;
    color: var(--text-color-secondary);
}
.preview-logo-wrap {
    display: flex;
    justify-content: center;
    margin-bottom: 1rem;
}
.preview-logo {
    max-width: 120px;
    max-height: 72px;
    object-fit: contain;
}
.preview-logo-placeholder {
    width: 72px;
    height: 72px;
    border-radius: 8px;
    background: var(--surface-ground);
    border: 2px dashed var(--surface-border);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text-color-secondary);
}
.preview-name-block {
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
}
.preview-name {
    font-size: 1.15rem;
    font-weight: 800;
    letter-spacing: -0.02em;
    color: var(--text-color);
    margin: 0;
}
.preview-razao {
    font-size: 0.75rem;
    color: var(--text-color-secondary);
    margin: 0;
}
.preview-tipo {
    display: inline-block;
    margin-top: 4px;
    padding: 2px 10px;
    border-radius: 999px;
    background: color-mix(in srgb, var(--primary-color, #6366f1) 12%, transparent);
    border: 1px solid color-mix(in srgb, var(--primary-color, #6366f1) 25%, transparent);
    color: var(--primary-color, #6366f1);
    font-size: 0.7rem;
    font-weight: 700;
}
.preview-section {
    margin-top: 0.75rem;
}
.preview-divider {
    height: 1px;
    background: var(--surface-border);
    margin-bottom: 0.75rem;
}
.preview-docs {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.preview-doc-row {
    display: flex;
    gap: 8px;
    align-items: baseline;
}
.preview-doc-label {
    font-size: 0.65rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-color-secondary);
    opacity: 0.6;
    width: 28px;
    flex-shrink: 0;
}
.preview-doc-value {
    font-size: 0.8rem;
    color: var(--text-color);
    font-family: monospace;
}

.preview-info-row {
    display: flex;
    align-items: flex-start;
    gap: 8px;
}
.preview-info-icon {
    font-size: 0.75rem;
    color: var(--primary-color, #6366f1);
    opacity: 0.7;
    margin-top: 2px;
    flex-shrink: 0;
}
.preview-info-text {
    font-size: 0.8rem;
    color: var(--text-color);
    line-height: 1.4;
}

.preview-rede {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 10px;
    border-radius: 999px;
    border: 1px solid var(--surface-border);
    background: var(--surface-ground);
    color: var(--text-color);
    font-size: 0.72rem;
    font-weight: 600;
    text-decoration: none;
    transition:
        border-color 0.15s,
        background 0.15s;
}
.preview-rede:hover {
    border-color: color-mix(in srgb, var(--primary-color, #6366f1) 40%, transparent);
    background: color-mix(in srgb, var(--primary-color, #6366f1) 6%, var(--surface-card));
}
.preview-rede i {
    font-size: 0.75rem;
}

/* ── Form cards ────────────────────────────────────────────── */
.cfg-card {
    border: 1px solid var(--surface-border);
    border-radius: 8px;
    background: var(--surface-card);
    overflow: hidden;
}
.cfg-card__head {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.65rem 1rem;
    border-bottom: 1px solid var(--surface-border);
    background: var(--surface-ground);
    font-size: 0.82rem;
    font-weight: 700;
}
.cfg-label {
    font-size: 0.75rem;
    font-weight: 600;
    color: var(--text-color-secondary);
}
.logo-upload-preview {
    width: 120px;
    height: 80px;
    border: 2px dashed var(--surface-border);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-shrink: 0;
    background: var(--surface-ground);
    transition: border-color 0.15s;
    overflow: hidden;
}
.logo-upload-preview:hover {
    border-color: var(--primary-color, #6366f1);
}
.logo-upload-preview.empty {
    color: var(--text-color-secondary);
}
</style>
