<script setup>
/*
 * MelissaNegocio — Pagina nativa Melissa pra "Meu Negocio".
 *
 * Substitui o embed cfg-negocio que vivia dentro do MelissaConfiguracoes.
 * Layout 2-col (espelha MelissaPerfil):
 *   - COL 1 (sidebar) — Card "Sua presença" (gamificação 7 niveis +
 *     badges + dicas) + Card "Logomarca" (preview/upload/remover)
 *     + Footer (Sair sem salvar -> emit close)
 *   - COL 2 (main) — Identidade + Dados Fiscais + Endereço (com
 *     fetch ViaCEP) + Contato + Redes Sociais
 *
 * Logica de load/save espelhada do Negociopage.vue (tabela
 * company_profiles + bucket logos), compativel com /account/negocio.
 */
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick } from 'vue';
import MelissaConfigList from './MelissaConfigList.vue';
import { useToast } from 'primevue/usetoast';
import { supabase } from '@/lib/supabase/client';
import { tenantDb } from '@/lib/supabase/tenantClient';
import { useTenantStore } from '@/stores/tenantStore';
// InputText/Select/Textarea/InputMask/Skeleton/Tag: auto via PrimeVueResolver

const emit = defineEmits(['close']);

const toast = useToast();
const tenantStore = useTenantStore();

const LOGO_BUCKET = 'logos';

// ── Breakpoints + drawer ───────────────────────────────────
const drawerOpen = ref(false);
const isMobile = ref(false);
const isWideDesktop = ref(false); // >= 1340px — preview vira painel flutuante fora do fake dialog
let _mqMobile = null;
let _mqWide = null;
function _onMqMobileChange(e) {
    isMobile.value = e.matches;
    if (!e.matches) drawerOpen.value = false;
}
function _onMqWideChange(e) { isWideDesktop.value = e.matches; }
function toggleDrawer() { drawerOpen.value = !drawerOpen.value; }

// Onde o card de Pre-visualizacao e renderizado:
//   - mobile: dentro da sidebar (que e teleportada pro drawer)
//   - mid-desktop (1024-1339): dentro da sidebar inline
//   - wide-desktop (>=1340): painel flutuante fora do fake dialog
const previewTarget = computed(() => (
    isWideDesktop.value && !isMobile.value
        ? '#mng-floating-preview-target'
        : '#mng-sidebar-preview-target'
));
function fecharDrawer() { drawerOpen.value = false; }

// Toggle entre cards (default) e lista de configs (alterna inline na sidebar)
const cfgOpen = ref(false);
function toggleCfg() { cfgOpen.value = !cfgOpen.value; }
function fecharCfg() { cfgOpen.value = false; }

// ── Estado ─────────────────────────────────────────────────
const loading = ref(true);
const saving = ref(false);
const dirty = ref(false);
const silentApplying = ref(true);

const tenantId = ref('');
const recordId = ref('');
const logoInput = ref(null);

const ui = reactive({
    logoPreview: '',
    logoFile: null,
    logoFilePreviewUrl: ''
});

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

const fieldErrors = reactive({
    nome_fantasia: '',
    tipo_empresa: ''
});

function clearErr(field) { fieldErrors[field] = ''; }
function markDirty() {
    if (silentApplying.value) return;
    dirty.value = true;
}

function validateRequired() {
    fieldErrors.nome_fantasia = form.nome_fantasia?.trim() ? '' : 'Nome do negócio é obrigatório.';
    fieldErrors.tipo_empresa = form.tipo_empresa?.trim() ? '' : 'Selecione o tipo de negócio.';
    return !fieldErrors.nome_fantasia && !fieldErrors.tipo_empresa;
}

const businessTypes = [
    { value: 'consultorio', label: 'Consultório' },
    { value: 'clinica', label: 'Clínica' },
    { value: 'instituicao', label: 'Instituição' },
    { value: 'empresa', label: 'Empresa' },
    { value: 'autonomo', label: 'Autônomo' },
    { value: 'cooperativa', label: 'Cooperativa' },
    { value: 'ong', label: 'ONG' },
    { value: 'outro', label: 'Outro' }
];

const ufOptions = [
    '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'
].map((uf) => ({ label: uf, value: uf }));

const negocioInitials = computed(() => {
    const name = form.nome_fantasia || '';
    const parts = String(name).trim().split(/\s+/).filter(Boolean);
    const a = parts[0]?.[0] || 'N';
    const b = parts.length > 1 ? parts[1][0] : '';
    return (a + b).toUpperCase();
});

// ── Preview live (cartao de visita) ────────────────────────
const logoDisplay = computed(() => ui.logoPreview || form.logo_url || null);
const enderecoLinhas = computed(() => {
    const lines = [];
    if (form.logradouro) {
        let l = form.logradouro;
        if (form.numero) l += `, ${form.numero}`;
        if (form.complemento) l += ` — ${form.complemento}`;
        lines.push(l);
    }
    if (form.bairro) lines.push(form.bairro);
    const ce = [form.cidade, form.estado].filter(Boolean).join(' / ');
    if (ce) lines.push(ce);
    if (form.cep) lines.push(`CEP ${form.cep}`);
    return lines;
});
const redesValidas = computed(() => form.redes_sociais.filter((r) => (r.name || r.rede) && r.url));
const temDados = computed(() => !!(form.nome_fantasia || form.razao_social || logoDisplay.value));

// Tenta detectar a plataforma pelo nome digitado pra escolher o icone certo.
// Funciona com strings freeform tipo "Instagram", "linkedin", "WhatsApp" etc.
function redeIcon(rede) {
    const k = String(rede?.name || rede?.rede || '').trim().toLowerCase();
    if (!k) return 'pi-link';
    if (k.includes('instagram')) return 'pi-instagram';
    if (k.includes('facebook')) return 'pi-facebook';
    if (k.includes('linkedin')) return 'pi-linkedin';
    if (k.includes('twitter') || k === 'x') return 'pi-twitter';
    if (k.includes('youtube')) return 'pi-youtube';
    if (k.includes('whatsapp') || k.includes('wpp')) return 'pi-whatsapp';
    if (k.includes('tiktok')) return 'pi-tiktok';
    if (k.includes('telegram')) return 'pi-send';
    return 'pi-link';
}

// ── Gamificação / Progresso ────────────────────────────────
const progressFields = computed(() => [
    { key: 'nome',     filled: !!form.nome_fantasia?.trim(),                            icon: 'pi pi-building',   text: 'Preencha o nome do negócio' },
    { key: 'tipo',     filled: !!form.tipo_empresa?.trim(),                             icon: 'pi pi-briefcase',  text: 'Selecione o tipo de negócio' },
    { key: 'cnpj',     filled: !!form.cnpj?.replace(/[^0-9]/g, ''),                     icon: 'pi pi-file-edit',  text: 'Informe o CNPJ' },
    { key: 'endereco', filled: !!(form.cep && form.logradouro && form.cidade),          icon: 'pi pi-map-marker', text: 'Complete o endereço' },
    { key: 'contato',  filled: !!(form.telefone?.replace(/[^0-9]/g, '') || form.email), icon: 'pi pi-phone',      text: 'Adicione um contato' },
    { key: 'logo',     filled: !!(form.logo_url?.trim() || ui.logoFile),                icon: 'pi pi-image',      text: 'Adicione a logomarca' },
    { key: 'redes',    filled: form.redes_sociais.length > 0 || !!form.site?.trim(),    icon: 'pi pi-share-alt',  text: 'Adicione uma rede social' }
]);

const progress = computed(() => {
    const filled = progressFields.value.filter((f) => f.filled).length;
    return Math.round((filled / progressFields.value.length) * 100);
});

const progressSuggestions = computed(() => progressFields.value.filter((f) => !f.filled));

const progressColor = computed(() => {
    if (progress.value >= 80) return '#10b981';
    if (progress.value >= 50) return '#f59e0b';
    return '#ef4444';
});

const bizLevels = [
    { min: 0,  max: 14,  label: 'Cadastro Básico', icon: '🏗️', color: '#94a3b8' },
    { min: 15, max: 28,  label: 'Em Formação',     icon: '📋', color: '#60a5fa' },
    { min: 29, max: 42,  label: 'Estabelecido',    icon: '🏢', color: '#f59e0b' },
    { min: 43, max: 57,  label: 'Consolidado',     icon: '📈', color: '#f97316' },
    { min: 58, max: 71,  label: 'Profissional',    icon: '💼', color: '#a78bfa' },
    { min: 72, max: 85,  label: 'Referência',      icon: '🏆', color: '#10b981' },
    { min: 86, max: 100, label: 'Excelência',      icon: '⭐', color: '#eab308' }
];

const currentBizLevel = computed(() =>
    bizLevels.find((l) => progress.value >= l.min && progress.value <= l.max) || bizLevels[0]
);
const nextBizLevel = computed(() => {
    const i = bizLevels.indexOf(currentBizLevel.value);
    return i < bizLevels.length - 1 ? bizLevels[i + 1] : null;
});
const xpToNext = computed(() => (nextBizLevel.value ? nextBizLevel.value.min - progress.value : 0));

const bizBadges = computed(() => [
    { key: 'nome',     earned: !!form.nome_fantasia?.trim(),                              icon: '🏢', label: 'Nomeado'      },
    { key: 'tipo',     earned: !!form.tipo_empresa?.trim(),                               icon: '📌', label: 'Categorizado' },
    { key: 'cnpj',     earned: !!form.cnpj?.replace(/[^0-9]/g, ''),                       icon: '📄', label: 'Regularizado' },
    { key: 'endereco', earned: !!(form.cep && form.logradouro && form.cidade),            icon: '📍', label: 'Localizado'   },
    { key: 'contato',  earned: !!(form.telefone?.replace(/[^0-9]/g, '') || form.email),   icon: '📞', label: 'Acessível'    },
    { key: 'logo',     earned: !!(form.logo_url?.trim() || ui.logoFile),                  icon: '🎨', label: 'Identificado' },
    { key: 'redes',    earned: form.redes_sociais.length > 0 || !!form.site?.trim(),      icon: '🌐', label: 'Online'       }
]);

// ── Ancoras: badge/dica leva pra sessao do form ────────────
const SECTION_BY_FIELD = {
    nome:     'identidade',
    tipo:     'identidade',
    cnpj:     'fiscal',
    endereco: 'endereco',
    contato:  'contato',
    logo:     'logomarca',
    redes:    'redes'
};
function scrollToSection(field) {
    const sec = SECTION_BY_FIELD[field];
    if (!sec) return;
    const isLogo = sec === 'logomarca';
    if (isMobile.value && !isLogo) drawerOpen.value = false;
    nextTick(() => {
        const target = document.getElementById('mng-sec-' + sec);
        if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
}

// ── Logomarca ──────────────────────────────────────────────
function pickLogo() { logoInput.value?.click(); }

function clearLogoFile() {
    ui.logoFile = null;
    if (ui.logoFilePreviewUrl) {
        try { URL.revokeObjectURL(ui.logoFilePreviewUrl); } catch { /* ignore */ }
    }
    ui.logoFilePreviewUrl = '';
    if (logoInput.value) logoInput.value.value = '';
}

function onLogoChange(ev) {
    const file = ev?.target?.files?.[0];
    if (!file) return;
    if (!file.type?.startsWith('image/')) {
        toast.add({ severity: 'warn', summary: 'Arquivo inválido', detail: 'Escolha uma imagem (PNG/SVG/JPG/WebP).', life: 3500 });
        clearLogoFile();
        return;
    }
    if (file.size > 2 * 1024 * 1024) {
        toast.add({ severity: 'warn', summary: 'Arquivo grande', detail: 'Máximo recomendado: 2 MB.', life: 3500 });
        clearLogoFile();
        return;
    }
    ui.logoFile = file;
    if (ui.logoFilePreviewUrl) {
        try { URL.revokeObjectURL(ui.logoFilePreviewUrl); } catch { /* ignore */ }
    }
    ui.logoFilePreviewUrl = URL.createObjectURL(file);
    ui.logoPreview = ui.logoFilePreviewUrl;
    markDirty();
}

function removeLogo() {
    form.logo_url = '';
    ui.logoPreview = '';
    clearLogoFile();
    markDirty();
}

function extFromMime(mime) {
    if (!mime) return 'png';
    if (mime.includes('svg')) return 'svg';
    if (mime.includes('png')) return 'png';
    if (mime.includes('jpeg')) return 'jpg';
    if (mime.includes('webp')) return 'webp';
    return 'png';
}

async function uploadLogoIfNeeded() {
    if (!ui.logoFile || !tenantId.value) return null;
    const file = ui.logoFile;
    const ext = extFromMime(file.type);
    const path = `${tenantId.value}/logo-${Date.now()}.${ext}`;
    const { error: upErr } = await supabase.storage
        .from(LOGO_BUCKET)
        .upload(path, file, { upsert: true, contentType: file.type });
    if (upErr) throw upErr;
    const { data } = supabase.storage.from(LOGO_BUCKET).getPublicUrl(path);
    const url = data?.publicUrl;
    if (!url) throw new Error('Upload ok, mas não consegui obter a URL pública.');
    return url;
}

// ── CEP (ViaCEP) ───────────────────────────────────────────
const fetchingCep = ref(false);
async function onCepBlur() {
    const digits = (form.cep || '').replace(/[^0-9]/g, '');
    if (digits.length !== 8) return;
    fetchingCep.value = true;
    try {
        const res = await fetch(`https://viacep.com.br/ws/${digits}/json/`);
        const data = await res.json();
        if (data?.erro) return;
        form.logradouro = data.logradouro || form.logradouro;
        form.bairro = data.bairro || form.bairro;
        form.cidade = data.localidade || form.cidade;
        form.estado = data.uf || form.estado;
        markDirty();
    } catch { /* ignore */ }
    finally { fetchingCep.value = false; }
}

// ── Redes sociais customizadas ─────────────────────────────
function addRede() { form.redes_sociais.push({ name: '', url: '' }); markDirty(); }
function removeRede(idx) { form.redes_sociais.splice(idx, 1); markDirty(); }

// ── Carregar / Salvar ──────────────────────────────────────
async function loadNegocio() {
    silentApplying.value = true;
    loading.value = true;
    try {
        const { data: u, error: uErr } = await supabase.auth.getUser();
        if (uErr) throw uErr;
        const uid = u?.user?.id;
        if (!uid) throw new Error('Você precisa estar logado.');

        const { data: member, error: mErr } = await supabase
            .from('tenant_members')
            .select('tenant_id')
            .eq('user_id', uid)
            .eq('status', 'active')
            .order('created_at', { ascending: true })
            .limit(1)
            .maybeSingle();
        if (mErr) throw mErr;
        if (!member?.tenant_id) throw new Error('Nenhum tenant associado à sua conta.');

        tenantId.value = member.tenant_id;

        const { data: co, error: coErr } = await tenantDb().from('company_profiles')
            .select('*')
            
            .maybeSingle();
        if (coErr) throw coErr;

        if (co) {
            recordId.value = co.id;
            form.nome_fantasia = co.nome_fantasia ?? '';
            form.razao_social = co.razao_social ?? '';
            form.tipo_empresa = co.tipo_empresa ?? '';
            form.cnpj = co.cnpj ?? '';
            form.ie = co.ie ?? '';
            form.im = co.im ?? '';
            form.cep = co.cep ?? '';
            form.logradouro = co.logradouro ?? '';
            form.numero = co.numero ?? '';
            form.complemento = co.complemento ?? '';
            form.bairro = co.bairro ?? '';
            form.cidade = co.cidade ?? '';
            form.estado = co.estado ?? '';
            form.telefone = co.telefone ?? '';
            form.email = co.email ?? '';
            form.site = co.site ?? '';
            form.logo_url = co.logo_url ?? '';
            ui.logoPreview = form.logo_url;
            // Normaliza schemas legados: o antigo cfg-empresa salvava { rede, url }
            // (rede = enum), enquanto MelissaNegocio usa { name, url } (name = freeform).
            // Mapeia rede -> name quando name vier vazio pra dados antigos nao perderem.
            const REDE_LABELS = { instagram: 'Instagram', facebook: 'Facebook', linkedin: 'LinkedIn', twitter: 'X / Twitter', youtube: 'YouTube', tiktok: 'TikTok', whatsapp: 'WhatsApp', telegram: 'Telegram', pinterest: 'Pinterest', outro: 'Outro' };
            form.redes_sociais = (Array.isArray(co.redes_sociais) ? co.redes_sociais : []).map((r) => ({
                name: r.name || REDE_LABELS[r.rede] || r.rede || '',
                url:  r.url || ''
            }));
        }
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Não consegui carregar os dados do negócio.', life: 6000 });
    } finally {
        loading.value = false;
        silentApplying.value = false;
        dirty.value = false;
    }
}

async function saveAll() {
    if (!validateRequired()) {
        toast.add({
            severity: 'warn',
            summary: 'Campos obrigatórios',
            detail: 'Preencha o nome e o tipo do negócio antes de salvar.',
            life: 4000
        });
        nextTick(() => {
            document.getElementById('mng-sec-identidade')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        });
        return;
    }
    saving.value = true;
    try {
        if (ui.logoFile) {
            try {
                const uploadedUrl = await uploadLogoIfNeeded();
                if (uploadedUrl) {
                    form.logo_url = uploadedUrl;
                    ui.logoPreview = uploadedUrl;
                }
            } catch (e) {
                toast.add({
                    severity: 'warn',
                    summary: 'Logo não subiu',
                    detail: `Não consegui enviar o arquivo (bucket "${LOGO_BUCKET}"). (${e?.message || 'erro'})`,
                    life: 6500
                });
            }
        }

        const payload = {
            nome_fantasia: String(form.nome_fantasia || '').trim() || null,
            razao_social: String(form.razao_social || '').trim() || null,
            tipo_empresa: String(form.tipo_empresa || '').trim() || null,
            cnpj: String(form.cnpj || '').trim() || null,
            ie: String(form.ie || '').trim() || null,
            im: String(form.im || '').trim() || null,
            cep: String(form.cep || '').trim() || null,
            logradouro: String(form.logradouro || '').trim() || null,
            numero: String(form.numero || '').trim() || null,
            complemento: String(form.complemento || '').trim() || null,
            bairro: String(form.bairro || '').trim() || null,
            cidade: String(form.cidade || '').trim() || null,
            estado: String(form.estado || '').trim() || null,
            telefone: String(form.telefone || '').trim() || null,
            email: String(form.email || '').trim() || null,
            site: String(form.site || '').trim() || null,
            logo_url: String(form.logo_url || '').trim() || null,
            redes_sociais: form.redes_sociais.filter((r) => r.name || r.url),
            updated_at: new Date().toISOString()
        };

        const { error } = await tenantDb().from('company_profiles')
            .upsert(payload, { onConflict: 'singleton' });
        if (error) throw error;

        clearLogoFile();
        dirty.value = false;
        toast.add({ severity: 'success', summary: 'Salvo', detail: 'Dados do negócio atualizados.', life: 2500 });
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao salvar', detail: e?.message || 'Não consegui salvar.', life: 6000 });
    } finally {
        saving.value = false;
    }
}

// ── Lifecycle ──────────────────────────────────────────────
onMounted(async () => {
    if (typeof window !== 'undefined' && window.matchMedia) {
        _mqMobile = window.matchMedia('(max-width: 1023px)');
        isMobile.value = _mqMobile.matches;
        try { _mqMobile.addEventListener('change', _onMqMobileChange); }
        catch { _mqMobile.addListener(_onMqMobileChange); }

        _mqWide = window.matchMedia('(min-width: 1340px)');
        isWideDesktop.value = _mqWide.matches;
        try { _mqWide.addEventListener('change', _onMqWideChange); }
        catch { _mqWide.addListener(_onMqWideChange); }
    }
    await tenantStore.ensureLoaded();
    await loadNegocio();
});

onBeforeUnmount(() => {
    if (_mqMobile) {
        try { _mqMobile.removeEventListener('change', _onMqMobileChange); }
        catch { _mqMobile.removeListener(_onMqMobileChange); }
    }
    if (_mqWide) {
        try { _mqWide.removeEventListener('change', _onMqWideChange); }
        catch { _mqWide.removeListener(_onMqWideChange); }
    }
    clearLogoFile();
});
</script>

<template>
    <Transition name="mng-drawer-fade">
        <div
            v-show="isMobile && drawerOpen"
            class="mng-mobile-drawer"
            :class="{ 'is-open': drawerOpen }"
        >
            <div id="mng-mobile-drawer-target" class="mng-mobile-drawer__scroll" />
        </div>
    </Transition>
    <Transition name="mng-drawer-fade">
        <div
            v-show="isMobile && drawerOpen"
            class="mng-mobile-drawer__backdrop"
            @click="fecharDrawer"
        />
    </Transition>

    <!-- Painel flutuante do Preview (wide-desktop >=1340px). Vive FORA do
         fake dialog, ancorado a sua right edge + 14px gap. Em mobile/mid-
         desktop, este painel fica oculto via CSS e o preview teleporta pra
         dentro da sidebar via #mng-sidebar-preview-target. -->
    <aside id="mng-floating-preview-target" class="mng-floating-preview" aria-label="Pré-visualização do negócio"></aside>

    <section class="mng-page">
        <header class="mng-page__head">
            <button
                class="mng-menu-btn mng-menu-btn--mobile-only"
                v-tooltip.bottom="'Presença & Logomarca'"
                @click="toggleDrawer"
            >
                <i class="pi pi-bars" />
                <span>Menu Negócio</span>
            </button>
            <div class="mng-page__title">
                <i class="pi pi-briefcase mng-page__title-icon" />
                <span>Meu Negócio</span>
                <span class="mng-page__count">{{ progress }}%</span>
            </div>
            <div class="mng-page__actions">
                <button
                    class="mng-act-btn mng-act-btn--primary"
                    v-tooltip.bottom="'Salvar alterações'"
                    :disabled="!dirty || saving"
                    @click="saveAll"
                >
                    <i :class="saving ? 'pi pi-spin pi-spinner' : 'pi pi-check'" />
                    <span>Salvar</span>
                </button>
                <button class="mng-close" v-tooltip.bottom="'Voltar (Esc)'" @click="emit('close')">
                    <i class="pi pi-times" />
                </button>
            </div>
        </header>

        <div class="mng-subheader">
            <i class="pi pi-info-circle mng-subheader__icon" />
            <span class="mng-subheader__text">
                Dados da sua empresa, consultório ou clínica. Quanto mais
                preenchido, mais alto o nível da sua presença.
            </span>
        </div>

        <div class="mng-body">
            <Teleport to="#mng-mobile-drawer-target" :disabled="!isMobile">
                <aside class="mng-side">
                    <button class="mng-cfg-btn" :class="{ 'is-open': cfgOpen }" @click="toggleCfg">
                        <i :class="cfgOpen ? 'pi pi-arrow-left' : 'pi pi-cog'" />
                        <span>{{ cfgOpen ? 'Voltar' : 'Configurações' }}</span>
                        <i v-if="!cfgOpen" class="pi pi-chevron-down mng-cfg-btn__chev" />
                    </button>
                    <div v-if="cfgOpen" class="mng-side__scroll mng-side__scroll--cfg">
                        <MelissaConfigList @select="fecharCfg" />
                    </div>
                    <div v-else class="mng-side__scroll">
                        <!-- Card: Sua presença -->
                        <div class="mng-w mng-w--side">
                            <div class="mng-w__head">
                                <div class="mng-w__icon"><i class="pi pi-star" /></div>
                                <div class="mng-w__title">
                                    <div class="mng-w__title-text">Sua presença</div>
                                    <div class="mng-w__sub">Nível, conquistas e pendências</div>
                                </div>
                            </div>

                            <div class="mng-w__body">
                                <div class="mng-level">
                                    <div
                                        class="mng-level__icon"
                                        :style="{
                                            backgroundColor: currentBizLevel.color + '22',
                                            borderColor: currentBizLevel.color + '55',
                                            color: currentBizLevel.color
                                        }"
                                        v-tooltip.top="currentBizLevel.label"
                                    >{{ currentBizLevel.icon }}</div>
                                    <div class="mng-level__text">
                                        <div class="mng-level__name">
                                            {{ currentBizLevel.label }}
                                            <span
                                                class="mng-level__num"
                                                :style="{
                                                    backgroundColor: currentBizLevel.color + '20',
                                                    color: currentBizLevel.color
                                                }"
                                            >Nível {{ bizLevels.indexOf(currentBizLevel) + 1 }}</span>
                                        </div>
                                        <div class="mng-level__pct" :style="{ color: progressColor }">
                                            {{ progress }}% completo
                                        </div>
                                    </div>
                                </div>

                                <div class="mng-progress">
                                    <div
                                        class="mng-progress__bar"
                                        :style="{
                                            width: progress + '%',
                                            backgroundColor: currentBizLevel.color
                                        }"
                                    />
                                </div>

                                <p class="mng-progress__hint">
                                    <span v-if="nextBizLevel" :style="{ color: nextBizLevel.color }">
                                        {{ xpToNext }}% até {{ nextBizLevel.label }} {{ nextBizLevel.icon }}
                                    </span>
                                    <span v-else style="color: #10b981">🎉 Cadastro 100% completo!</span>
                                </p>

                                <div class="mng-badges-head">Conquistas</div>
                                <div class="mng-badges">
                                    <button
                                        v-for="badge in bizBadges"
                                        :key="badge.key"
                                        type="button"
                                        class="mng-badge"
                                        :class="badge.earned ? 'is-earned' : 'is-locked'"
                                        v-tooltip.top="badge.earned ? badge.label : 'Bloqueado — ' + badge.label"
                                        @click="scrollToSection(badge.key)"
                                    >
                                        <span class="mng-badge__icon">{{ badge.icon }}</span>
                                        <span class="mng-badge__label">{{ badge.label }}</span>
                                    </button>
                                </div>

                                <div v-if="progressSuggestions.length" class="mng-tips">
                                    <div class="mng-tips__head">O que falta</div>
                                    <button
                                        v-for="(tip, i) in progressSuggestions"
                                        :key="i"
                                        type="button"
                                        class="mng-tip"
                                        @click="scrollToSection(tip.key)"
                                    >
                                        <i :class="tip.icon" />
                                        {{ tip.text }}
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Card: Logomarca -->
                        <div id="mng-sec-logomarca" class="mng-w mng-w--side">
                            <div class="mng-w__head">
                                <div class="mng-w__icon"><i class="pi pi-image" /></div>
                                <div class="mng-w__title">
                                    <div class="mng-w__title-text">Logomarca</div>
                                    <div class="mng-w__sub">Imagem que representa o negócio</div>
                                </div>
                            </div>
                            <div class="mng-w__body">
                                <div class="mng-logo">
                                    <div class="mng-logo__preview">
                                        <img v-if="ui.logoPreview" :src="ui.logoPreview" alt="Logomarca" />
                                        <span v-else class="mng-logo__initials">{{ negocioInitials }}</span>
                                    </div>
                                    <div class="mng-logo__actions">
                                        <button class="mng-btn mng-btn--primary" @click="pickLogo">
                                            <i class="pi pi-upload" />
                                            <span>{{ ui.logoPreview ? 'Trocar' : 'Enviar' }}</span>
                                        </button>
                                        <button
                                            v-if="ui.logoPreview"
                                            class="mng-btn mng-btn--danger"
                                            @click="removeLogo"
                                        >
                                            <i class="pi pi-times" />
                                            <span>Remover</span>
                                        </button>
                                    </div>
                                    <input
                                        ref="logoInput"
                                        type="file"
                                        accept="image/*"
                                        hidden
                                        @change="onLogoChange"
                                    />
                                    <div class="mng-logo__hint">PNG, SVG, JPG ou WebP. Máximo 2 MB.</div>
                                </div>
                            </div>
                        </div>

                        <!-- Target do Teleport do Preview pra modo sidebar (mobile + mid-desktop).
                             No wide-desktop (>=1340px) o preview teleporta pro #mng-floating-preview-target. -->
                        <div id="mng-sidebar-preview-target" class="mng-side-preview-target" />
                    </div>
                </aside>
            </Teleport>

            <div class="mng-main">
                <template v-if="loading">
                    <div class="mng-w" v-for="n in 4" :key="`sk-${n}`">
                        <div class="mng-w__body">
                            <Skeleton width="40%" height="20px" class="mb-3" />
                            <Skeleton v-for="m in 3" :key="`sk-${n}-${m}`" width="100%" height="40px" class="mb-2" />
                        </div>
                    </div>
                </template>

                <template v-else>
                    <!-- ── Identidade ── -->
                    <div id="mng-sec-identidade" class="mng-w">
                        <div class="mng-w__head">
                            <div class="mng-w__icon"><i class="pi pi-building" /></div>
                            <div class="mng-w__title">
                                <div class="mng-w__title-text">Identidade</div>
                                <div class="mng-w__sub">Nome fantasia, razão social e tipo</div>
                            </div>
                        </div>
                        <div class="mng-w__body">
                            <div class="mng-grid">
                                <div class="mng-field mng-field--full">
                                    <FloatLabel variant="on">
                                        <InputText
                                            id="mng_nome"
                                            v-model="form.nome_fantasia"
                                            class="w-full"
                                            :invalid="!!fieldErrors.nome_fantasia"
                                            @input="markDirty(); clearErr('nome_fantasia')"
                                        />
                                        <label for="mng_nome">Nome fantasia *</label>
                                    </FloatLabel>
                                    <small v-if="fieldErrors.nome_fantasia" class="mng-err">{{ fieldErrors.nome_fantasia }}</small>
                                    <small v-else class="mng-hint">Como o público conhece seu negócio.</small>
                                </div>

                                <div class="mng-field mng-field--full">
                                    <FloatLabel variant="on">
                                        <InputText
                                            id="mng_razao"
                                            v-model="form.razao_social"
                                            class="w-full"
                                            @input="markDirty"
                                        />
                                        <label for="mng_razao">Razão social</label>
                                    </FloatLabel>
                                    <small class="mng-hint">Nome jurídico da empresa (opcional).</small>
                                </div>

                                <div class="mng-field mng-field--full">
                                    <FloatLabel variant="on">
                                        <Select
                                            id="mng_tipo"
                                            v-model="form.tipo_empresa"
                                            :options="businessTypes"
                                            optionLabel="label"
                                            optionValue="value"
                                            class="w-full"
                                            :invalid="!!fieldErrors.tipo_empresa"
                                            @change="markDirty(); clearErr('tipo_empresa')"
                                        />
                                        <label for="mng_tipo">Tipo de negócio *</label>
                                    </FloatLabel>
                                    <small v-if="fieldErrors.tipo_empresa" class="mng-err">{{ fieldErrors.tipo_empresa }}</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- ── Dados Fiscais ── -->
                    <div id="mng-sec-fiscal" class="mng-w">
                        <div class="mng-w__head">
                            <div class="mng-w__icon"><i class="pi pi-file-edit" /></div>
                            <div class="mng-w__title">
                                <div class="mng-w__title-text">Dados Fiscais</div>
                                <div class="mng-w__sub">CNPJ e inscrições</div>
                            </div>
                        </div>
                        <div class="mng-w__body">
                            <div class="mng-grid">
                                <div class="mng-field mng-field--full">
                                    <FloatLabel variant="on">
                                        <InputMask
                                            id="mng_cnpj"
                                            v-model="form.cnpj"
                                            mask="99.999.999/9999-99"
                                            class="w-full"
                                            @input="markDirty"
                                        />
                                        <label for="mng_cnpj">CNPJ</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <InputText id="mng_ie" v-model="form.ie" class="w-full" @input="markDirty" />
                                        <label for="mng_ie">Inscrição Estadual</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <InputText id="mng_im" v-model="form.im" class="w-full" @input="markDirty" />
                                        <label for="mng_im">Inscrição Municipal</label>
                                    </FloatLabel>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- ── Endereço ── -->
                    <div id="mng-sec-endereco" class="mng-w">
                        <div class="mng-w__head">
                            <div class="mng-w__icon"><i class="pi pi-map-marker" /></div>
                            <div class="mng-w__title">
                                <div class="mng-w__title-text">Endereço</div>
                                <div class="mng-w__sub">CEP preenche o resto via ViaCEP</div>
                            </div>
                            <span v-if="fetchingCep" class="mng-w__hint">
                                <i class="pi pi-spin pi-spinner" /> Buscando...
                            </span>
                        </div>
                        <div class="mng-w__body">
                            <div class="mng-grid">
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <InputMask
                                            id="mng_cep"
                                            v-model="form.cep"
                                            mask="99999-999"
                                            class="w-full"
                                            @blur="onCepBlur"
                                            @input="markDirty"
                                        />
                                        <label for="mng_cep">CEP</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--full">
                                    <FloatLabel variant="on">
                                        <InputText id="mng_log" v-model="form.logradouro" class="w-full" @input="markDirty" />
                                        <label for="mng_log">Logradouro</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <InputText id="mng_num" v-model="form.numero" class="w-full" @input="markDirty" />
                                        <label for="mng_num">Número</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <InputText id="mng_comp" v-model="form.complemento" class="w-full" @input="markDirty" />
                                        <label for="mng_comp">Complemento</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <InputText id="mng_bairro" v-model="form.bairro" class="w-full" @input="markDirty" />
                                        <label for="mng_bairro">Bairro</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <InputText id="mng_cid" v-model="form.cidade" class="w-full" @input="markDirty" />
                                        <label for="mng_cid">Cidade</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <Select
                                            id="mng_uf"
                                            v-model="form.estado"
                                            :options="ufOptions"
                                            optionLabel="label"
                                            optionValue="value"
                                            class="w-full"
                                            @change="markDirty"
                                        />
                                        <label for="mng_uf">UF</label>
                                    </FloatLabel>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- ── Contato ── -->
                    <div id="mng-sec-contato" class="mng-w">
                        <div class="mng-w__head">
                            <div class="mng-w__icon"><i class="pi pi-phone" /></div>
                            <div class="mng-w__title">
                                <div class="mng-w__title-text">Contato</div>
                                <div class="mng-w__sub">Telefone, e-mail e site</div>
                            </div>
                        </div>
                        <div class="mng-w__body">
                            <div class="mng-grid">
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <InputMask
                                            id="mng_tel"
                                            v-model="form.telefone"
                                            mask="(99) 99999-9999"
                                            class="w-full"
                                            @input="markDirty"
                                        />
                                        <label for="mng_tel">Telefone / WhatsApp</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--half">
                                    <FloatLabel variant="on">
                                        <InputText
                                            id="mng_email"
                                            v-model="form.email"
                                            class="w-full"
                                            placeholder=" "
                                            @input="markDirty"
                                        />
                                        <label for="mng_email">E-mail</label>
                                    </FloatLabel>
                                </div>
                                <div class="mng-field mng-field--full">
                                    <FloatLabel variant="on">
                                        <InputText id="mng_site" v-model="form.site" class="w-full" @input="markDirty" />
                                        <label for="mng_site">Site</label>
                                    </FloatLabel>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- ── Redes Sociais ── -->
                    <div id="mng-sec-redes" class="mng-w">
                        <div class="mng-w__head">
                            <div class="mng-w__icon"><i class="pi pi-share-alt" /></div>
                            <div class="mng-w__title">
                                <div class="mng-w__title-text">Redes Sociais</div>
                                <div class="mng-w__sub">Adicione todos os perfis públicos</div>
                            </div>
                            <button class="mng-w__action" @click="addRede">
                                <i class="pi pi-plus" />
                                <span>Adicionar</span>
                            </button>
                        </div>
                        <div class="mng-w__body">
                            <div v-if="!form.redes_sociais.length" class="mng-empty">
                                <i class="pi pi-share-alt" />
                                <span>Nenhuma rede cadastrada. Click em <strong>Adicionar</strong>.</span>
                            </div>
                            <div v-else class="mng-redes">
                                <div
                                    v-for="(r, idx) in form.redes_sociais"
                                    :key="`r-${idx}`"
                                    class="mng-rede"
                                >
                                    <FloatLabel variant="on" class="flex-1">
                                        <InputText
                                            :id="`r_name_${idx}`"
                                            v-model="r.name"
                                            class="w-full"
                                            @input="markDirty"
                                        />
                                        <label :for="`r_name_${idx}`">Nome (Instagram, LinkedIn...)</label>
                                    </FloatLabel>
                                    <FloatLabel variant="on" class="flex-1">
                                        <InputText
                                            :id="`r_url_${idx}`"
                                            v-model="r.url"
                                            class="w-full"
                                            @input="markDirty"
                                        />
                                        <label :for="`r_url_${idx}`">URL</label>
                                    </FloatLabel>
                                    <button
                                        class="mng-btn mng-btn--danger mng-btn--icon"
                                        v-tooltip.left="'Remover'"
                                        @click="removeRede(idx)"
                                    >
                                        <i class="pi pi-trash" />
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </section>

    <!-- ── Card de Pre-visualizacao (Teleport). O target alterna conforme o
         viewport (sidebar embutida vs painel flutuante fora do fake dialog). -->
    <Teleport :to="previewTarget">
        <div id="mng-sec-preview" class="mng-w mng-w--side mng-w--preview">
            <div class="mng-w__head">
                <div class="mng-w__icon"><i class="pi pi-id-card" /></div>
                <div class="mng-w__title">
                    <div class="mng-w__title-text">Pré-visualização</div>
                    <div class="mng-w__sub">Como seu negócio aparece</div>
                </div>
            </div>
            <div class="mng-w__body">
                <div class="mng-preview">
                    <div v-if="!temDados" class="mng-preview__empty">
                        <i class="pi pi-building" />
                        <p>Preencha os dados<br />pra ver o preview</p>
                    </div>
                    <template v-else>
                        <div class="mng-preview__logo-wrap">
                            <img v-if="logoDisplay" :src="logoDisplay" alt="Logo" class="mng-preview__logo" />
                            <div v-else class="mng-preview__logo-placeholder">
                                <i class="pi pi-building" />
                            </div>
                        </div>
                        <div class="mng-preview__name-block">
                            <h2 v-if="form.nome_fantasia" class="mng-preview__name">{{ form.nome_fantasia }}</h2>
                            <p v-if="form.razao_social" class="mng-preview__razao">{{ form.razao_social }}</p>
                            <span v-if="form.tipo_empresa" class="mng-preview__tipo">{{ businessTypes.find((t) => t.value === form.tipo_empresa)?.label || form.tipo_empresa }}</span>
                        </div>
                        <div v-if="form.cnpj || form.ie || form.im" class="mng-preview__section">
                            <div class="mng-preview__divider" />
                            <div class="mng-preview__docs">
                                <div v-if="form.cnpj" class="mng-preview__doc-row">
                                    <span class="mng-preview__doc-label">CNPJ</span>
                                    <span class="mng-preview__doc-value">{{ form.cnpj }}</span>
                                </div>
                                <div v-if="form.ie" class="mng-preview__doc-row">
                                    <span class="mng-preview__doc-label">IE</span>
                                    <span class="mng-preview__doc-value">{{ form.ie }}</span>
                                </div>
                                <div v-if="form.im" class="mng-preview__doc-row">
                                    <span class="mng-preview__doc-label">IM</span>
                                    <span class="mng-preview__doc-value">{{ form.im }}</span>
                                </div>
                            </div>
                        </div>
                        <div v-if="enderecoLinhas.length" class="mng-preview__section">
                            <div class="mng-preview__divider" />
                            <div class="mng-preview__info-row">
                                <i class="pi pi-map-marker mng-preview__info-icon" />
                                <div class="mng-preview__info-stack">
                                    <span v-for="(linha, i) in enderecoLinhas" :key="i" class="mng-preview__info-text">{{ linha }}</span>
                                </div>
                            </div>
                        </div>
                        <div v-if="form.email || form.telefone || form.site" class="mng-preview__section">
                            <div class="mng-preview__divider" />
                            <div class="mng-preview__info-stack">
                                <div v-if="form.email" class="mng-preview__info-row">
                                    <i class="pi pi-envelope mng-preview__info-icon" />
                                    <span class="mng-preview__info-text">{{ form.email }}</span>
                                </div>
                                <div v-if="form.telefone" class="mng-preview__info-row">
                                    <i class="pi pi-phone mng-preview__info-icon" />
                                    <span class="mng-preview__info-text">{{ form.telefone }}</span>
                                </div>
                                <div v-if="form.site" class="mng-preview__info-row">
                                    <i class="pi pi-globe mng-preview__info-icon" />
                                    <span class="mng-preview__info-text mng-preview__info-text--truncate">{{ form.site }}</span>
                                </div>
                            </div>
                        </div>
                        <div v-if="redesValidas.length" class="mng-preview__section">
                            <div class="mng-preview__divider" />
                            <div class="mng-preview__redes">
                                <a
                                    v-for="(r, i) in redesValidas"
                                    :key="i"
                                    :href="r.url"
                                    target="_blank"
                                    rel="noopener"
                                    class="mng-preview__rede"
                                    :title="r.name || r.rede"
                                >
                                    <i :class="`pi ${redeIcon(r)}`" />
                                    <span>{{ r.name || r.rede }}</span>
                                </a>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </Teleport>
</template>

<style scoped>
/* ═══════ Page chrome (mesmo pattern do MelissaPerfil) ═══════ */
.mng-page {
    position: absolute;
    inset: 6px 6px calc(var(--m-dock-h, 76px) + 6px) var(--m-config-aside-left, 6px);
    z-index: 40;
    display: flex;
    flex-direction: column;
    background: var(--m-bg-medium);
    backdrop-filter: blur(32px) saturate(160%);
    -webkit-backdrop-filter: blur(32px) saturate(160%);
    border: 1px solid var(--m-border);
    border-radius: 18px;
    box-shadow: 0 16px 48px rgba(0, 0, 0, 0.4);
    overflow: hidden;
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
    color: var(--m-text);
    animation: mng-page-enter 240ms cubic-bezier(0.2, 0.7, 0.3, 1);
}
@keyframes mng-page-enter {
    from { opacity: 0; transform: scale(0.985); }
    to   { opacity: 1; transform: scale(1); }
}

.mng-page__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 18px;
    border-bottom: 1px solid var(--m-border);
    flex-shrink: 0;
    gap: 10px;
}
.mng-page__title {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1rem;
    font-weight: 700;
    color: var(--m-text);
}
.mng-page__title-icon { color: var(--p-primary-color); font-size: 1.05rem; }
.mng-page__count {
    margin-left: auto;
    background: color-mix(in srgb, var(--p-primary-color) 18%, transparent);
    color: var(--p-primary-color);
    border-radius: 999px;
    padding: 3px 10px;
    font-size: 0.74rem;
    font-weight: 700;
}
.mng-page__actions { display: flex; align-items: center; gap: 6px; }

.mng-act-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 7px 12px;
    border-radius: 8px;
    border: 1px solid var(--m-border);
    background: var(--m-bg-soft);
    color: var(--m-text);
    cursor: pointer;
    font-size: 0.82rem;
    font-weight: 600;
    transition: background-color 120ms ease, border-color 120ms ease, opacity 120ms ease;
}
.mng-act-btn:hover { background: var(--m-bg-soft-hover); }
.mng-act-btn--primary {
    background: var(--p-primary-color);
    border-color: var(--p-primary-color);
    color: var(--p-primary-contrast-color, #fff);
}
.mng-act-btn--primary:hover {
    background: color-mix(in srgb, var(--p-primary-color) 88%, black);
}
.mng-act-btn:disabled { opacity: 0.45; cursor: not-allowed; }

.mng-close {
    width: 32px;
    height: 32px;
    display: grid;
    place-items: center;
    background: transparent;
    border: 1px solid var(--m-border);
    color: var(--m-text-muted);
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 120ms ease, color 120ms ease;
}
.mng-close:hover { background: var(--m-bg-soft-hover); color: var(--m-text); }

.mng-menu-btn {
    display: none;
    align-items: center;
    gap: 6px;
    padding: 7px 12px;
    border-radius: 8px;
    border: 1px solid var(--m-border);
    background: var(--m-bg-soft);
    color: var(--m-text);
    cursor: pointer;
    font-size: 0.82rem;
    font-weight: 600;
    flex-shrink: 0;
}
.mng-menu-btn:hover { background: var(--m-bg-soft-hover); }

.mng-subheader {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    padding: 10px 18px;
    background: var(--m-bg-soft);
    border-bottom: 1px solid var(--m-border);
    color: var(--m-text-muted);
    font-size: 0.78rem;
    flex-shrink: 0;
}
.mng-subheader__icon {
    color: var(--p-primary-color);
    font-size: 0.85rem;
    margin-top: 2px;
    flex-shrink: 0;
}

/* ═══════ Body 2-col ═══════ */
.mng-body {
    flex: 1;
    min-height: 0;
    display: flex;
    overflow: hidden;
}
.mng-side {
    width: 320px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    background: var(--m-bg-soft);
    border-right: 1px solid var(--m-border);
    overflow: hidden;
}
.mng-side__scroll {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mng-side__scroll::-webkit-scrollbar { width: 5px; }
.mng-side__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

/* Botao "Configuracoes" no topo da .mng-side. Click alterna entre
   cards (default) e lista de configs (estado is-open: vira "Voltar"). */
.mng-cfg-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    width: calc(100% - 24px);
    margin: 12px 12px 0;
    padding: 10px 12px;
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    border-radius: 9px;
    color: var(--m-text);
    cursor: pointer;
    font-family: inherit;
    font-size: 0.84rem;
    font-weight: 600;
    text-align: left;
    transition: background-color 120ms ease, border-color 120ms ease, color 120ms ease;
    flex-shrink: 0;
}
.mng-cfg-btn:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
}
.mng-cfg-btn.is-open {
    background: color-mix(in srgb, var(--p-primary-color) 14%, transparent);
    border-color: color-mix(in srgb, var(--p-primary-color) 38%, transparent);
    color: var(--p-primary-color);
}
.mng-cfg-btn > i:first-child {
    color: var(--p-primary-color);
    font-size: 0.92rem;
}
.mng-cfg-btn > span { flex: 1; }
.mng-cfg-btn__chev {
    color: var(--m-text-muted);
    font-size: 0.7rem;
}
.mng-side__scroll--cfg {
    padding: 8px;
    gap: 0;
}

.mng-main {
    flex: 1;
    min-width: 0;
    min-height: 0;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mng-main::-webkit-scrollbar { width: 5px; }
.mng-main::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

/* Desktop (>=1024px): cards 2-col 50/50, min-height 300px, max-height
   100% do container, body com overflow-y: auto pra adicionar redes
   sem quebrar layout. Mesma logica na sidebar (Sua presença, Logomarca). */
@media (min-width: 1024px) {
    /* Fake dialog: largura adaptativa, alinhada a esquerda (apos o
       config-aside global). Espelha pattern de Seguranca/Pagamento/etc:
       - 1024–1012px : full-width (right: 6px) — overlap minimo
       - 1012–2012px : width = 1000px fixo (right cresce com viewport)
       - >= 2012px   : width = ~50% do viewport (right: 50%) */
    .mng-page {
        right: max(6px, min(50%, calc(100% - 1006px)));
    }


    /* Cards do main empilhados em 1-col (era grid 2-col antes).
       .mng-main herda flex-direction: column do base — cards crescem
       com conteudo, sem scroll interno. Espelha pattern de MelissaPerfil/Plano. */
    .mng-main > .mng-w {
        flex-shrink: 0;
        height: auto;
    }
    /* Cards da sidebar (Sua presença + Logomarca): altura natural,
       flex-shrink: 0 evita compressao quando total passa do
       .mng-side__scroll (scroll externo). */
    .mng-side > .mng-side__scroll > .mng-w--side {
        display: flex;
        flex-direction: column;
        flex-shrink: 0;
        height: auto;
    }
}

/* ═══════ Card-base (estilo MelissaPerfil/MelissaFinanceiro) ═══════ */
.mng-w {
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
}
.mng-w--side {
    background: var(--m-bg-medium);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.16);
}
.mng-w__head {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px 14px;
    border-bottom: 1px solid var(--m-border);
}
.mng-w__icon {
    width: 36px;
    height: 36px;
    display: grid;
    place-items: center;
    border-radius: 9px;
    flex-shrink: 0;
    background: color-mix(in srgb, var(--p-primary-color) 15%, transparent);
    color: var(--p-primary-color);
}
.mng-w__icon > i { font-size: 0.95rem; }
.mng-w__title { flex: 1; min-width: 0; }
.mng-w__title-text {
    font-size: 0.92rem;
    font-weight: 700;
    color: var(--m-text);
    line-height: 1.2;
}
.mng-w__sub {
    font-size: 0.74rem;
    color: var(--m-text-muted);
    margin-top: 2px;
    line-height: 1.3;
}
.mng-w__hint {
    font-size: 0.72rem;
    color: var(--m-text-muted);
    display: inline-flex;
    align-items: center;
    gap: 4px;
    flex-shrink: 0;
}
.mng-w__action {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 5px 10px;
    border-radius: 7px;
    border: 1px solid var(--m-border);
    background: var(--m-bg-medium);
    color: var(--m-text);
    cursor: pointer;
    font-size: 0.74rem;
    font-weight: 600;
    flex-shrink: 0;
    transition: background-color 120ms ease;
}
.mng-w__action:hover { background: var(--m-bg-soft-hover); }
.mng-w__action > i { font-size: 0.72rem; color: var(--p-primary-color); }
.mng-w__body {
    padding: 14px;
    display: flex;
    flex-direction: column;
    gap: 12px;
}

/* ═══════ Gamificação (idem MelissaPerfil) ═══════ */
.mng-level {
    display: flex;
    align-items: center;
    gap: 10px;
}
.mng-level__icon {
    width: 44px;
    height: 44px;
    display: grid;
    place-items: center;
    border-radius: 12px;
    border: 1px solid;
    font-size: 1.5rem;
    flex-shrink: 0;
}
.mng-level__text { flex: 1; min-width: 0; }
.mng-level__name {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.92rem;
    font-weight: 700;
    color: var(--m-text);
}
.mng-level__num {
    font-size: 0.66rem;
    font-weight: 700;
    padding: 2px 7px;
    border-radius: 999px;
}
.mng-level__pct {
    font-size: 0.74rem;
    font-weight: 700;
    margin-top: 2px;
}
.mng-progress {
    width: 100%;
    height: 8px;
    border-radius: 999px;
    background: var(--m-bg-soft);
    overflow: hidden;
}
.mng-progress__bar {
    height: 100%;
    border-radius: 999px;
    transition: width 600ms cubic-bezier(0.2, 0.7, 0.3, 1);
}
.mng-progress__hint {
    margin: 0;
    font-size: 0.72rem;
    color: var(--m-text-muted);
    font-weight: 600;
}

.mng-badges-head {
    font-size: 0.66rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: var(--m-text-muted);
}
.mng-badges {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}
.mng-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 8px;
    border-radius: 999px;
    border: 1px solid var(--m-border);
    font-size: 0.7rem;
    font-family: inherit;
    cursor: pointer;
    transition: transform 120ms ease, background-color 120ms ease;
}
.mng-badge:hover { transform: translateY(-1px); }
.mng-badge.is-earned {
    background: color-mix(in srgb, var(--p-primary-color) 14%, transparent);
    border-color: color-mix(in srgb, var(--p-primary-color) 38%, transparent);
    color: var(--p-primary-color);
    font-weight: 600;
}
.mng-badge.is-locked {
    background: var(--m-bg-soft);
    color: var(--m-text-faint);
    opacity: 0.6;
}
.mng-badge__icon { font-size: 0.85rem; line-height: 1; }
.mng-badge__label { line-height: 1; }

.mng-tips {
    display: flex;
    flex-direction: column;
    gap: 5px;
    padding-top: 8px;
    border-top: 1px solid var(--m-border);
}
.mng-tips__head {
    font-size: 0.66rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: var(--m-text-muted);
}
.mng-tip {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 8px;
    border-radius: 6px;
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    color: var(--m-text-muted);
    font-size: 0.72rem;
    font-family: inherit;
    cursor: pointer;
    text-align: left;
    transition: background-color 120ms ease, color 120ms ease, border-color 120ms ease;
}
.mng-tip:hover {
    background: color-mix(in srgb, var(--p-primary-color) 12%, transparent);
    border-color: color-mix(in srgb, var(--p-primary-color) 38%, transparent);
    color: var(--p-primary-color);
}
.mng-tip > i { font-size: 0.7rem; color: var(--p-primary-color); }

/* ═══════ Logomarca ═══════ */
.mng-logo {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    padding: 4px 0 0;
}
.mng-logo__preview {
    width: 96px;
    height: 96px;
    border-radius: 18px;
    border: 1px solid var(--m-border);
    background: var(--m-bg-soft);
    overflow: hidden;
    display: grid;
    place-items: center;
    box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18);
}
.mng-logo__preview > img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    background: var(--m-bg-soft);
}
.mng-logo__initials {
    font-size: 2rem;
    font-weight: 800;
    color: var(--m-text);
}
.mng-logo__actions {
    display: flex;
    gap: 6px;
    width: 100%;
    justify-content: center;
}
.mng-logo__hint {
    font-size: 0.7rem;
    color: var(--m-text-muted);
    text-align: center;
}

/* ═══════ Buttons ═══════ */
.mng-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 7px 12px;
    border-radius: 8px;
    border: 1px solid var(--m-border);
    background: var(--m-bg-soft);
    color: var(--m-text);
    cursor: pointer;
    font-size: 0.78rem;
    font-weight: 600;
    font-family: inherit;
    transition: background-color 120ms ease;
}
.mng-btn:hover { background: var(--m-bg-soft-hover); }
.mng-btn--primary {
    background: var(--p-primary-color);
    border-color: var(--p-primary-color);
    color: var(--p-primary-contrast-color, #fff);
}
.mng-btn--primary:hover {
    background: color-mix(in srgb, var(--p-primary-color) 88%, black);
}
.mng-btn--danger {
    background: rgba(220, 38, 38, 0.12);
    border-color: rgba(220, 38, 38, 0.40);
    color: rgb(220, 38, 38);
}
.mng-btn--danger:hover { background: rgba(220, 38, 38, 0.22); }
.mng-btn--icon {
    padding: 7px 10px;
    flex-shrink: 0;
}

/* ═══════ Form grid ═══════ */
.mng-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 14px 12px;
    margin-top: 4px;
}
.mng-field { min-width: 0; }
.mng-field--full { grid-column: 1 / -1; }
.mng-field--half { grid-column: span 1; }

.mng-hint, .mng-err {
    display: block;
    margin-top: 4px;
    font-size: 0.7rem;
    line-height: 1.3;
}
.mng-hint { color: var(--m-text-muted); }
.mng-err { color: rgb(220, 38, 38); font-weight: 500; }

/* ═══════ Preview (cartao de visita live) ═══════ */
.mng-preview {
    display: flex; flex-direction: column; gap: 10px;
}
.mng-preview__empty {
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    padding: 20px 12px;
    color: var(--m-text-muted);
    text-align: center;
}
.mng-preview__empty > i { font-size: 1.6rem; opacity: 0.4; margin-bottom: 6px; }
.mng-preview__empty > p { font-size: 0.7rem; opacity: 0.6; line-height: 1.3; margin: 0; }

.mng-preview__logo-wrap {
    width: 64px; height: 64px;
    display: grid; place-items: center;
    margin: 0 auto;
    border-radius: 10px;
    overflow: hidden;
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
}
.mng-preview__logo { width: 100%; height: 100%; object-fit: contain; padding: 4px; }
.mng-preview__logo-placeholder { color: var(--m-text-muted); font-size: 1.4rem; }

.mng-preview__name-block { text-align: center; }
.mng-preview__name {
    font-size: 0.95rem; font-weight: 700; color: var(--m-text);
    margin: 0 0 2px;
    word-wrap: break-word;
}
.mng-preview__razao {
    font-size: 0.72rem; color: var(--m-text-muted);
    margin: 0 0 4px;
    word-wrap: break-word;
}
.mng-preview__tipo {
    display: inline-block;
    font-size: 0.65rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em;
    color: var(--p-primary-color);
    background: color-mix(in srgb, var(--p-primary-color) 12%, transparent);
    padding: 2px 8px; border-radius: 999px;
}

.mng-preview__divider {
    height: 1px;
    background: var(--m-border);
    margin: 4px 0;
}
.mng-preview__section { display: flex; flex-direction: column; gap: 6px; }

.mng-preview__docs { display: flex; flex-direction: column; gap: 4px; }
.mng-preview__doc-row {
    display: flex; justify-content: space-between; align-items: center; gap: 8px;
    font-size: 0.72rem;
}
.mng-preview__doc-label {
    font-weight: 600; color: var(--m-text-muted);
    text-transform: uppercase; letter-spacing: 0.04em;
    flex-shrink: 0;
}
.mng-preview__doc-value {
    color: var(--m-text);
    font-family: 'Segoe UI Mono', 'Consolas', monospace;
    text-align: right;
    word-break: break-all;
}

.mng-preview__info-stack { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; }
.mng-preview__info-row {
    display: flex; align-items: flex-start; gap: 8px;
    font-size: 0.72rem;
    color: var(--m-text);
}
.mng-preview__info-icon {
    color: var(--p-primary-color);
    font-size: 0.78rem;
    margin-top: 2px;
    flex-shrink: 0;
}
.mng-preview__info-text { flex: 1; min-width: 0; line-height: 1.3; word-break: break-word; }
.mng-preview__info-text--truncate {
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}

.mng-preview__redes { display: flex; flex-wrap: wrap; gap: 6px; }
.mng-preview__rede {
    display: inline-flex; align-items: center; gap: 5px;
    padding: 4px 9px;
    border-radius: 999px;
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    color: var(--m-text);
    font-size: 0.7rem; font-weight: 500;
    text-decoration: none;
    transition: background-color 120ms ease, border-color 120ms ease;
    max-width: 100%;
}
.mng-preview__rede:hover {
    background: var(--m-bg-soft-hover);
    border-color: color-mix(in srgb, var(--p-primary-color) 35%, var(--m-border));
}
.mng-preview__rede > i { color: var(--p-primary-color); font-size: 0.72rem; }
.mng-preview__rede > span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

/* ═══════ Empty state (Redes) ═══════ */
.mng-empty {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 14px;
    border-radius: 9px;
    background: var(--m-bg-medium);
    border: 1px dashed var(--m-border);
    color: var(--m-text-muted);
    font-size: 0.82rem;
    text-align: left;
}
.mng-empty > i { color: var(--p-primary-color); font-size: 0.92rem; }

/* ═══════ Redes sociais ═══════ */
.mng-redes {
    display: flex;
    flex-direction: column;
    gap: 10px;
}
.mng-rede {
    display: flex;
    gap: 8px;
    align-items: stretch;
}
.mng-rede > .p-floatlabel,
.mng-rede > div { min-width: 0; }

/* ═══════ Mobile drawer ═══════ */
.mng-mobile-drawer {
    position: fixed;
    top: 0; left: 0;
    height: 100vh;
    height: 100dvh;
    width: min(360px, 88vw);
    z-index: 80;
    background: var(--m-bg-medium);
    backdrop-filter: blur(28px) saturate(160%);
    -webkit-backdrop-filter: blur(28px) saturate(160%);
    border-right: 1px solid var(--m-border);
    transform: translateX(-100%);
    transition: transform 250ms cubic-bezier(0.4, 0, 0.2, 1);
    color: var(--m-text);
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
    display: flex;
    flex-direction: column;
}
.mng-mobile-drawer.is-open { transform: translateX(0); }
.mng-mobile-drawer__scroll {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mng-mobile-drawer__scroll::-webkit-scrollbar { width: 5px; }
.mng-mobile-drawer__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}
/* No mobile a .mng-side e teleportada pra dentro do drawer scroll. */
.mng-mobile-drawer__scroll .mng-side {
    width: 100%;
    border-right: none;
}

.mng-mobile-drawer__backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.45);
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
    z-index: 79;
}
.mng-drawer-fade-enter-active,
.mng-drawer-fade-leave-active { transition: opacity 200ms ease; }
.mng-drawer-fade-enter-from,
.mng-drawer-fade-leave-to { opacity: 0; }

/* ═══════ Mobile (<1024px) ═══════ */
@media (max-width: 1023px) {
    .mng-body { flex-direction: column; padding: 0; }
    .mng-body > .mng-side { display: none; }
    .mng-main { width: 100%; padding: 8px; }
    .mng-main .mng-w {
        height: auto;
        flex: 0 0 auto;
        align-self: stretch;
    }
    .mng-grid { grid-template-columns: 1fr; }
    .mng-field--half { grid-column: 1 / -1; }
    .mng-page__title > span:first-of-type { display: none; }
    .mng-page__title-icon { display: none; }
    .mng-menu-btn--mobile-only { display: inline-flex; }
    .mng-rede { flex-direction: column; gap: 8px; }
    .mng-rede .mng-btn--icon { align-self: flex-end; }
}

/* ═══════ Painel flutuante do Preview (wide-desktop >= 1340px) ═══════
   Vive FORA do fake dialog, ancorado a sua right edge + 14px gap.
   Mantem proporcoes proximas ao painel "Personalizar" (w-72 ~ 288px).
   Glass igual ao fake dialog: fundo, blur, borda, radius, sombra. */
.mng-floating-preview {
    display: none; /* default: oculto. Wide-desktop ativa via @media abaixo. */
    position: absolute;
    top: 6px;
    /* height segue o conteudo (sem bottom). max-height limita ao mesmo
       espaco do fake dialog pra forcar scroll se ficar muito alto. */
    max-height: calc(100% - var(--m-dock-h, 76px) - 12px);
    width: 288px;
    z-index: 39; /* abaixo do mng-page (40) — nao concorre por foco */
    overflow-y: auto;
    overflow-x: hidden;
    /* Sem padding aqui: o card .mng-w--preview interno controla o espaco
       e seu __head fica flush com o topo, alinhando com o head do fake dialog. */
    padding: 0;
    background: var(--m-bg-medium);
    backdrop-filter: blur(32px) saturate(160%);
    -webkit-backdrop-filter: blur(32px) saturate(160%);
    border: 1px solid var(--m-border);
    border-radius: 18px;
    box-shadow: 0 16px 48px rgba(0, 0, 0, 0.4);
    color: var(--m-text);
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mng-floating-preview::-webkit-scrollbar { width: 5px; }
.mng-floating-preview::-webkit-scrollbar-thumb { background: var(--m-border-strong); border-radius: 3px; }

/* Placeholder do preview na sidebar/drawer: nao introduz wrapper visivel.
   Os filhos teleportados se posicionam como flex items diretos do parent
   (mng-side ou drawer), herdando o mesmo gap dos outros cards. */
.mng-side-preview-target { display: contents; }

/* Dentro do painel flutuante, o card de preview perde o "card-em-card":
   sem fundo/borda/sombra propria (o glass do painel ja faz esse papel). */
.mng-floating-preview > .mng-w--preview {
    background: transparent;
    border: none;
    box-shadow: none;
    border-radius: 0;
}
/* __head do card alinha com o __head do fake dialog (padding 14px 18px) */
.mng-floating-preview > .mng-w--preview > .mng-w__head {
    border-bottom: 1px solid var(--m-border);
    padding: 14px 18px;
}
.mng-floating-preview > .mng-w--preview > .mng-w__body {
    padding: 14px 18px;
}

/* Wide-desktop: floating ativo, ancorado a right edge do .mng-page + 14px gap.
   .mng-page tem `right: max(6px, min(50%, calc(100% - 1006px)))`, entao seu
   right edge esta a `100% - max(...)` do parent-left. O preview comeca 14px
   apos isso. 1340px e o piso onde page (1006) + gap (14) + preview (288) +
   margem (32) cabem confortavelmente. */
@media (min-width: 1340px) {
    .mng-floating-preview {
        display: block;
        left: calc(100% - max(6px, min(50%, calc(100% - 1006px))) + 14px);
    }
    /* Placeholder some — preview foi pro painel flutuante */
    .mng-side-preview-target { display: none; }
}
</style>
