<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/views/pages/account/NegocioPage.vue
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
-->
<script setup>
import { useToast } from 'primevue/usetoast';
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import InputMask from 'primevue/inputmask';
import Textarea from 'primevue/textarea';

import { supabase } from '@/lib/supabase/client';

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

const LOGO_BUCKET = 'logos';

/* ----------------------------
   Estado geral
----------------------------- */
const loading  = ref(true);
const saving   = ref(false);
const dirty    = ref(false);
const mounted  = ref(false);

const tenantId    = ref('');
const recordId    = ref('');   // id da linha em company_profiles (null = ainda não existe)
const logoInput   = ref(null);

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

/* ----------------------------
   Formulário (espelha a tabela)
----------------------------- */
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:  []   // [{ name, url }]
});

/* ----------------------------
   Validação
----------------------------- */
const fieldErrors = reactive({
    nome_fantasia: '',
    tipo_empresa:  ''
});

function clearErr(field) { fieldErrors[field] = ''; }

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;
}

/* ----------------------------
   Tipos de negócio
----------------------------- */
const businessTypes = [
    { value: 'consultorio',      label: 'Consultório',    icon: 'pi-briefcase'    },
    { value: 'clinica',          label: 'Clínica',        icon: 'pi-building'     },
    { value: 'instituicao',      label: 'Instituição',    icon: 'pi-sitemap'      },
    { value: 'empresa',          label: 'Empresa',        icon: 'pi-chart-bar'    },
    { value: 'autonomo',         label: 'Autônomo',       icon: 'pi-user'         },
    { value: 'cooperativa',      label: 'Cooperativa',    icon: 'pi-users'        },
    { value: 'ong',              label: 'ONG',            icon: 'pi-heart'        },
    { value: 'outro',            label: 'Outro',          icon: 'pi-ellipsis-h'   }
];

/* ----------------------------
   Seções (sidebar nav)
----------------------------- */
const sections = [
    { id: 'identidade',  label: 'Identidade',    icon: 'pi pi-building'    },
    { id: 'fiscal',      label: 'Dados Fiscais',  icon: 'pi pi-file-edit'   },
    { id: 'endereco',    label: 'Endereço',       icon: 'pi pi-map-marker'  },
    { id: 'contato',     label: 'Contato',        icon: 'pi pi-phone'       },
    { id: 'redes',       label: 'Redes Sociais',  icon: 'pi pi-share-alt'   },
    { id: 'logomarca',   label: 'Logomarca',      icon: 'pi pi-image'       }
];

const activeSection = ref('identidade');

/* ----------------------------
   Progresso / Gamificação
----------------------------- */
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'        }
]);

/* ----------------------------
   Initials (para logo placeholder)
----------------------------- */
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();
});

function markDirty() { dirty.value = true; }

/* ----------------------------
   Hero / sticky
----------------------------- */
const heroMenuRef      = ref(null);
const heroEl           = ref(null);
const heroSentinelRef  = ref(null);
const heroStuck        = ref(false);

const heroMenuItems = computed(() => [
    { label: 'Voltar',           icon: 'pi pi-arrow-left', command: () => router.back()  },
    { label: 'Salvar alterações',icon: 'pi pi-check',      command: () => saveAll(), disabled: !dirty.value },
    { separator: true },
    { label: 'Seções', items: sections.map((s) => ({ label: s.label, icon: s.icon, command: () => scrollTo(s.id) })) }
]);

let disconnectStickyObserver = null;
let disconnectObserver       = null;

function scrollTo(id) {
    activeSection.value = id;
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function observeSections() {
    const els = sections.map((s) => document.getElementById(s.id)).filter(Boolean);
    const io  = new IntersectionObserver(
        (entries) => {
            const visible = entries.filter((e) => e.isIntersecting).sort((a, b) => (b.intersectionRatio || 0) - (a.intersectionRatio || 0))[0];
            if (visible?.target?.id) activeSection.value = visible.target.id;
        },
        { root: null, threshold: [0.2, 0.35, 0.5], rootMargin: '-15% 0px -70% 0px' }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
}

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

function triggerLogoUpload() { logoInput.value?.click(); }

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).', 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 {} }
    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
----------------------------- */
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 {} 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(); }

/* ----------------------------
   Load
----------------------------- */
async function loadNegocio() {
    loading.value = true;
    try {
        // Pegar tenant_id do usuário logado
        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;

        // Carregar dados da empresa
        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;
            form.redes_sociais  = Array.isArray(co.redes_sociais) ? co.redes_sociais : [];
        }
    } 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;
        dirty.value   = false;
    }
}

/* ----------------------------
   Save
----------------------------- */
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 });
        document.getElementById('identidade')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        return;
    }

    saving.value = true;
    try {
        // Upload logo se necessário
        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: `Erro no upload: ${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 () => {
    try {
        await loadNegocio();
        mounted.value    = true;
        disconnectObserver = observeSections();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Erro ao carregar.', life: 6000 });
    }

    const sentinel = heroSentinelRef.value;
    if (sentinel) {
        const io = new IntersectionObserver(
            ([entry]) => { heroStuck.value = !entry.isIntersecting; },
            { rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px` }
        );
        io.observe(sentinel);
        disconnectStickyObserver = () => io.disconnect();
    }
});

onBeforeUnmount(() => {
    try { disconnectObserver?.();       } catch {}
    try { disconnectStickyObserver?.(); } catch {}
    clearLogoFile();
});
</script>

<template>
    <!-- ── HERO ─────────────────────────────────────────────── -->
    <div ref="heroSentinelRef" class="p-2" />
    <div
        ref="heroEl"
        class="sticky mx-3 md:mx-4 mb-4 z-20 overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-2"
        :style="{ top: 'var(--layout-sticky-top, 55px)' }"
        :class="{ 'rounded-tl-none rounded-tr-none': heroStuck }"
    >
        <!-- Fundo empresarial: tons de âmbar/laranja em vez dos gradientes pessoais -->
        <div class="absolute inset-0 pointer-events-none overflow-hidden" aria-hidden="true">
            <div class="absolute rounded-full blur-[70px] w-80 h-80 -top-20 -right-16 bg-amber-500/[0.13]" />
            <div class="absolute rounded-full blur-[70px] w-[22rem] h-[22rem] top-4 -left-20 bg-orange-400/[0.09]" />
            <div class="absolute rounded-full blur-[70px] w-64 h-64 -bottom-12 right-20 bg-yellow-500/[0.07]" />
        </div>

        <div class="relative z-10 flex items-center gap-5 flex-wrap">
            <div class="flex items-center gap-4 flex-1 min-w-0">
                <!-- Logo / initials -->
                <div class="relative shrink-0">
                    <div class="w-16 h-16 rounded-[1.125rem] border-2 border-[var(--surface-border)] bg-[var(--surface-ground)] overflow-hidden grid place-items-center">
                        <img v-if="ui.logoPreview" :src="ui.logoPreview" class="w-full h-full object-cover" alt="logo" />
                        <span v-else class="text-[1.1rem] font-extrabold text-amber-500">{{ negocioInitials }}</span>
                    </div>
                    <!-- Badge empresarial -->
                    <span class="absolute -bottom-1 -right-1 w-5 h-5 rounded-full bg-amber-500 border-2 border-[var(--surface-card)] flex items-center justify-center">
                        <i class="pi pi-building text-white" style="font-size: 0.55rem" />
                    </span>
                </div>

                <div class="min-w-0">
                    <div class="flex items-center gap-2">
                        <div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)] leading-snug truncate">{{ form.nome_fantasia || 'Meu Negócio' }}</div>
                        <!-- Tag empresarial -->
                        <span class="hidden sm:inline-flex shrink-0 items-center gap-1 text-[0.65rem] font-bold px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-500 border border-amber-500/20">
                            <i class="pi pi-building" style="font-size:0.6rem" /> Empresa
                        </span>
                    </div>
                    <div class="text-[1rem] text-[var(--text-color-secondary)] mt-0.5 truncate">{{ form.tipo_empresa || 'Gerencie os dados do seu negócio' }}</div>
                </div>
            </div>

            <!-- Desktop -->
            <div class="hidden xl:flex items-center gap-2 shrink-0">
                <Button label="Voltar" icon="pi pi-arrow-left" severity="secondary" outlined class="rounded-full" @click="router.back()" />
                <Button label="Salvar" icon="pi pi-check" class="rounded-full" :loading="saving" :disabled="!dirty" @click="saveAll" />
            </div>

            <!-- Mobile -->
            <div class="flex xl:hidden items-center gap-2 shrink-0">
                <Button label="Ações" icon="pi pi-ellipsis-v" severity="secondary" size="small" class="rounded-full" @click="(e) => heroMenuRef.toggle(e)" />
                <Menu ref="heroMenuRef" :model="heroMenuItems" :popup="true" />
            </div>
        </div>
    </div>

    <!-- ── PROGRESSO / GAMIFICAÇÃO ───────────────────────────── -->
    <div class="px-3 md:px-4 mb-4">
        <div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 space-y-4">

            <div class="flex items-center gap-4">
                <div
                    class="shrink-0 w-12 h-12 rounded-xl flex items-center justify-center text-2xl border"
                    :style="{ backgroundColor: currentBizLevel.color + '18', borderColor: currentBizLevel.color + '40' }"
                    v-tooltip.top="currentBizLevel.label"
                >{{ currentBizLevel.icon }}</div>

                <div class="flex-1 min-w-0">
                    <div class="flex items-center justify-between mb-1.5">
                        <div class="flex items-center gap-2">
                            <span class="text-[1rem] font-bold text-[var(--text-color)]">{{ currentBizLevel.label }}</span>
                            <span class="text-xs font-semibold px-2 py-0.5 rounded-full"
                                  :style="{ backgroundColor: currentBizLevel.color + '20', color: currentBizLevel.color }">
                                Nível {{ bizLevels.indexOf(currentBizLevel) + 1 }}
                            </span>
                        </div>
                        <span class="text-xs font-bold" :style="{ color: progressColor }">{{ progress }}%</span>
                    </div>

                    <div class="w-full h-2.5 rounded-full bg-[var(--surface-ground)] overflow-hidden">
                        <div class="h-full rounded-full transition-all duration-700 ease-out relative overflow-hidden"
                             :style="{ width: progress + '%', backgroundColor: currentBizLevel.color }">
                            <div class="absolute inset-0 neg-shimmer" />
                        </div>
                    </div>

                    <p class="text-xs text-[var(--text-color-secondary)] mt-1.5 m-0">
                        <span v-if="nextBizLevel">
                            <span class="font-medium" :style="{ color: nextBizLevel.color }">{{ xpToNext }}% até {{ nextBizLevel.label }} {{ nextBizLevel.icon }}</span>
                            — complete mais dados para evoluir
                        </span>
                        <span v-else class="font-semibold" style="color: #10b981">🎉 Cadastro 100% completo!</span>
                    </p>
                </div>
            </div>

            <!-- Badges empresariais -->
            <div>
                <p class="text-xs font-semibold text-[var(--text-color-secondary)] uppercase tracking-wider mb-2">Conquistas do Negócio</p>
                <div class="flex gap-2 flex-wrap">
                    <div v-for="badge in bizBadges" :key="badge.key"
                         class="neg-badge"
                         :class="badge.earned ? 'neg-badge--earned' : 'neg-badge--locked'"
                         v-tooltip.top="badge.earned ? badge.label : 'Bloqueado — ' + badge.label">
                        <span class="text-base leading-none">{{ badge.icon }}</span>
                        <span class="text-xs font-medium leading-none">{{ badge.label }}</span>
                    </div>
                </div>
            </div>

            <!-- Dicas -->
            <div v-if="progressSuggestions.length" class="flex flex-wrap gap-2 pt-1 border-t border-[var(--surface-border)]">
                <span v-for="(tip, i) in progressSuggestions" :key="i"
                      class="inline-flex items-center gap-1.5 text-xs px-2.5 py-1 rounded-full bg-[var(--surface-ground)] text-[var(--text-color-secondary)] border border-[var(--surface-border)]">
                    <i :class="tip.icon" class="text-[0.65rem]" />
                    {{ tip.text }}
                </span>
            </div>
        </div>
    </div>

    <!-- Skeleton -->
    <div v-if="loading" class="px-3 md:px-4">
        <div class="animate-pulse space-y-4">
            <div v-for="i in 4" :key="i" class="h-32 bg-[var(--surface-border)] rounded-md" />
        </div>
    </div>

    <!-- ── GRID ──────────────────────────────────────────────── -->
    <div v-else class="px-3 md:px-4 pb-8 grid grid-cols-12 gap-4 md:gap-5">

        <!-- ── Sidebar ────────────────────────────────────────── -->
        <div class="col-span-12 lg:col-span-3">
            <div class="sticky rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-5 flex flex-col gap-3"
                 :style="{ top: 'var(--layout-sticky-top, 140px)' }">

                <!-- Mini logo / empresa -->
                <div class="flex items-center gap-3 pb-1">
                    <div class="relative shrink-0">
                        <div class="w-10 h-10 rounded-xl border border-[var(--surface-border)] bg-[var(--surface-ground)] overflow-hidden grid place-items-center">
                            <img v-if="ui.logoPreview" :src="ui.logoPreview" class="w-full h-full object-cover" alt="logo" />
                            <span v-else class="text-sm font-extrabold text-amber-500">{{ negocioInitials }}</span>
                        </div>
                        <span class="absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 rounded-full bg-amber-500 border-2 border-[var(--surface-card)] flex items-center justify-center">
                            <i class="pi pi-building text-white" style="font-size:0.4rem" />
                        </span>
                    </div>
                    <div class="min-w-0">
                        <div class="text-[1rem] font-semibold text-[var(--text-color)] truncate">{{ form.nome_fantasia || 'Meu Negócio' }}</div>
                        <div class="text-[0.75rem] text-amber-500 font-medium">{{ form.tipo_empresa || 'Tipo não definido' }}</div>
                    </div>
                </div>

                <!-- Nav -->
                <nav class="flex flex-col gap-0.5">
                    <button v-for="s in sections" :key="s.id"
                            class="nav-link flex items-center gap-2.5 px-3 py-2 rounded-xl text-[1rem] font-medium cursor-pointer text-left w-full border border-transparent bg-transparent transition-all"
                            :class="{ 'nav-link--active': activeSection === s.id }"
                            @click="scrollTo(s.id)">
                        <i :class="[s.icon, 'text-[1rem] opacity-65 shrink-0']" />
                        <span>{{ s.label }}</span>
                    </button>
                </nav>

                <div class="h-px bg-[var(--surface-border)]" />

                <Button label="Salvar alterações" icon="pi pi-check" class="w-full" size="small" :loading="saving" :disabled="!dirty" @click="saveAll" />
            </div>
        </div>

        <!-- ── Conteúdo ───────────────────────────────────────── -->
        <div class="col-span-12 lg:col-span-9 flex flex-col gap-4 md:gap-5">

            <!-- ── 01 IDENTIDADE ─────────────────────────────── -->
            <div id="identidade"
                 class="ncard relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-6 scroll-mt-20 transition-[border-color] duration-[220ms]"
                 style="--c: #f59e0b; --c-dim: rgba(245,158,11,0.08); --c-border: rgba(245,158,11,0.22)">
                <div class="ncard__num">01</div>
                <div class="ncard__shine" />

                <div class="flex items-center gap-2.5 mb-3.5">
                    <div class="w-9 h-9 rounded-[0.625rem] shrink-0 flex items-center justify-center" style="background:var(--c-dim);border:1px solid var(--c-border);color:var(--c)"><i class="pi pi-building" /></div>
                    <span class="text-[1rem] font-extrabold uppercase tracking-[0.14em] opacity-75" style="color:var(--c)">Identidade</span>
                </div>
                <div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)] mb-1">Nome e tipo do negócio</div>
                <div class="text-[1rem] text-[var(--text-color-secondary)] leading-relaxed">Informações principais exibidas no sistema e no perfil público.</div>

                <div class="h-px bg-[var(--surface-border)] my-5" />

                <div class="grid grid-cols-12 gap-4">
                    <!-- Nome do negócio -->
                    <div class="col-span-12 md:col-span-6">
                        <FloatLabel variant="on">
                            <InputText id="neg_nome" v-model="form.nome_fantasia" class="w-full"
                                       :invalid="!!fieldErrors.nome_fantasia"
                                       @input="markDirty(); clearErr('nome_fantasia')" />
                            <label for="neg_nome">Nome do negócio <span class="text-red-400">*</span></label>
                        </FloatLabel>
                        <Message v-if="fieldErrors.nome_fantasia" severity="error" size="small" variant="simple" class="mt-1">{{ fieldErrors.nome_fantasia }}</Message>
                        <div v-else class="mt-1.5 text-[1rem] text-[var(--text-color-secondary)]">Nome fantasia exibido no sistema.</div>
                    </div>

                    <!-- Razão Social -->
                    <div class="col-span-12 md:col-span-6">
                        <FloatLabel variant="on">
                            <InputText id="neg_razao" v-model="form.razao_social" class="w-full" @input="markDirty" />
                            <label for="neg_razao">Razão social</label>
                        </FloatLabel>
                        <div class="mt-1.5 text-[1rem] text-[var(--text-color-secondary)]">Nome jurídico registrado.</div>
                    </div>

                    <!-- Tipo de negócio -->
                    <div class="col-span-12">
                        <div class="text-[1rem] font-medium text-[var(--text-color)] mb-2">
                            Tipo de negócio <span class="text-red-400">*</span>
                        </div>
                        <div class="grid grid-cols-2 sm:grid-cols-4 gap-2"
                             :class="{ 'ring-2 ring-red-500/30 rounded-xl p-1': !!fieldErrors.tipo_empresa }">
                            <button v-for="bt in businessTypes" :key="bt.value" type="button"
                                    class="relative flex flex-col items-center gap-1.5 py-3 px-2 rounded-xl border transition-all cursor-pointer text-center"
                                    :class="form.tipo_empresa === bt.value
                                        ? 'bg-amber-500/10 border-amber-500/40 text-amber-500'
                                        : 'bg-[var(--surface-hover)] border-[var(--surface-border)] hover:border-amber-500/30 text-[var(--text-color-secondary)]'"
                                    @click="form.tipo_empresa = bt.value; markDirty(); clearErr('tipo_empresa')">
                                <i :class="`pi ${bt.icon} text-lg`" />
                                <span class="text-xs font-medium">{{ bt.label }}</span>
                                <i v-if="form.tipo_empresa === bt.value" class="pi pi-check-circle absolute top-1.5 right-1.5 text-xs text-amber-500" />
                            </button>
                        </div>
                        <Message v-if="fieldErrors.tipo_empresa" severity="error" size="small" variant="simple" class="mt-1">{{ fieldErrors.tipo_empresa }}</Message>
                    </div>
                </div>
            </div>

            <!-- ── 02 DADOS FISCAIS ───────────────────────────── -->
            <div id="fiscal"
                 class="ncard relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-6 scroll-mt-20 transition-[border-color] duration-[220ms]"
                 style="--c: #60a5fa; --c-dim: rgba(96,165,250,0.08); --c-border: rgba(96,165,250,0.22)">
                <div class="ncard__num">02</div>
                <div class="ncard__shine" />

                <div class="flex items-center gap-2.5 mb-3.5">
                    <div class="w-9 h-9 rounded-[0.625rem] shrink-0 flex items-center justify-center" style="background:var(--c-dim);border:1px solid var(--c-border);color:var(--c)"><i class="pi pi-file-edit" /></div>
                    <span class="text-[1rem] font-extrabold uppercase tracking-[0.14em] opacity-75" style="color:var(--c)">Dados Fiscais</span>
                </div>
                <div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)] mb-1">CNPJ e inscrições</div>
                <div class="text-[1rem] text-[var(--text-color-secondary)] leading-relaxed">Informações tributárias do seu negócio.</div>

                <div class="h-px bg-[var(--surface-border)] my-5" />

                <div class="grid grid-cols-12 gap-4">
                    <div class="col-span-12 md:col-span-4">
                        <FloatLabel variant="on">
                            <InputMask id="neg_cnpj" v-model="form.cnpj" mask="99.999.999/9999-99" :autoClear="false" class="w-full" @update:modelValue="markDirty" />
                            <label for="neg_cnpj">CNPJ</label>
                        </FloatLabel>
                        <div class="mt-1.5 text-[1rem] text-[var(--text-color-secondary)]">Cadastro Nacional de Pessoa Jurídica.</div>
                    </div>
                    <div class="col-span-12 md:col-span-4">
                        <FloatLabel variant="on">
                            <InputText id="neg_ie" v-model="form.ie" class="w-full" @input="markDirty" />
                            <label for="neg_ie">Inscrição Estadual (IE)</label>
                        </FloatLabel>
                        <div class="mt-1.5 text-[1rem] text-[var(--text-color-secondary)]">Opcional. Deixe em branco se isento.</div>
                    </div>
                    <div class="col-span-12 md:col-span-4">
                        <FloatLabel variant="on">
                            <InputText id="neg_im" v-model="form.im" class="w-full" @input="markDirty" />
                            <label for="neg_im">Inscrição Municipal (IM)</label>
                        </FloatLabel>
                        <div class="mt-1.5 text-[1rem] text-[var(--text-color-secondary)]">Opcional. Necessário para emissão de NFS-e.</div>
                    </div>
                </div>
            </div>

            <!-- ── 03 ENDEREÇO ────────────────────────────────── -->
            <div id="endereco"
                 class="ncard relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-6 scroll-mt-20 transition-[border-color] duration-[220ms]"
                 style="--c: #4ade80; --c-dim: rgba(74,222,128,0.08); --c-border: rgba(74,222,128,0.22)">
                <div class="ncard__num">03</div>
                <div class="ncard__shine" />

                <div class="flex items-center gap-2.5 mb-3.5">
                    <div class="w-9 h-9 rounded-[0.625rem] shrink-0 flex items-center justify-center" style="background:var(--c-dim);border:1px solid var(--c-border);color:var(--c)"><i class="pi pi-map-marker" /></div>
                    <span class="text-[1rem] font-extrabold uppercase tracking-[0.14em] opacity-75" style="color:var(--c)">Endereço</span>
                </div>
                <div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)] mb-1">Localização do negócio</div>
                <div class="text-[1rem] text-[var(--text-color-secondary)] leading-relaxed">Digite o CEP para preencher automaticamente.</div>

                <div class="h-px bg-[var(--surface-border)] my-5" />

                <div class="grid grid-cols-12 gap-4">
                    <!-- CEP -->
                    <div class="col-span-12 sm:col-span-3">
                        <FloatLabel variant="on">
                            <div class="relative">
                                <InputMask id="neg_cep" v-model="form.cep" mask="99999-999" :autoClear="false" class="w-full"
                                           @blur="onCepBlur" @update:modelValue="markDirty" />
                                <i v-if="fetchingCep" class="pi pi-spin pi-spinner absolute right-3 top-1/2 -translate-y-1/2 text-xs text-amber-500" />
                            </div>
                            <label for="neg_cep">CEP</label>
                        </FloatLabel>
                    </div>

                    <!-- Logradouro -->
                    <div class="col-span-12 sm:col-span-9">
                        <FloatLabel variant="on">
                            <InputText id="neg_logradouro" v-model="form.logradouro" class="w-full" @input="markDirty" />
                            <label for="neg_logradouro">Logradouro</label>
                        </FloatLabel>
                    </div>

                    <!-- Número -->
                    <div class="col-span-6 sm:col-span-2">
                        <FloatLabel variant="on">
                            <InputText id="neg_numero" v-model="form.numero" class="w-full" @input="markDirty" />
                            <label for="neg_numero">Número</label>
                        </FloatLabel>
                    </div>

                    <!-- Complemento -->
                    <div class="col-span-6 sm:col-span-4">
                        <FloatLabel variant="on">
                            <InputText id="neg_complemento" v-model="form.complemento" class="w-full" @input="markDirty" />
                            <label for="neg_complemento">Complemento</label>
                        </FloatLabel>
                    </div>

                    <!-- Bairro -->
                    <div class="col-span-12 sm:col-span-3">
                        <FloatLabel variant="on">
                            <InputText id="neg_bairro" v-model="form.bairro" class="w-full" @input="markDirty" />
                            <label for="neg_bairro">Bairro</label>
                        </FloatLabel>
                    </div>

                    <!-- Cidade -->
                    <div class="col-span-9 sm:col-span-2">
                        <FloatLabel variant="on">
                            <InputText id="neg_cidade" v-model="form.cidade" class="w-full" @input="markDirty" />
                            <label for="neg_cidade">Cidade</label>
                        </FloatLabel>
                    </div>

                    <!-- Estado -->
                    <div class="col-span-3 sm:col-span-1">
                        <FloatLabel variant="on">
                            <InputText id="neg_estado" v-model="form.estado" class="w-full" maxlength="2" @input="markDirty" />
                            <label for="neg_estado">UF</label>
                        </FloatLabel>
                    </div>
                </div>
            </div>

            <!-- ── 04 CONTATO ─────────────────────────────────── -->
            <div id="contato"
                 class="ncard relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-6 scroll-mt-20 transition-[border-color] duration-[220ms]"
                 style="--c: #22d3ee; --c-dim: rgba(34,211,238,0.08); --c-border: rgba(34,211,238,0.22)">
                <div class="ncard__num">04</div>
                <div class="ncard__shine" />

                <div class="flex items-center gap-2.5 mb-3.5">
                    <div class="w-9 h-9 rounded-[0.625rem] shrink-0 flex items-center justify-center" style="background:var(--c-dim);border:1px solid var(--c-border);color:var(--c)"><i class="pi pi-phone" /></div>
                    <span class="text-[1rem] font-extrabold uppercase tracking-[0.14em] opacity-75" style="color:var(--c)">Contato</span>
                </div>
                <div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)] mb-1">Telefone e e-mail</div>
                <div class="text-[1rem] text-[var(--text-color-secondary)] leading-relaxed">Como seus clientes entram em contato com o negócio.</div>

                <div class="h-px bg-[var(--surface-border)] my-5" />

                <div class="grid grid-cols-12 gap-4">
                    <div class="col-span-12 md:col-span-6">
                        <FloatLabel variant="on">
                            <InputMask id="neg_telefone" v-model="form.telefone" mask="(99) 99999-9999" :autoClear="false" class="w-full" @update:modelValue="markDirty" />
                            <label for="neg_telefone">Telefone</label>
                        </FloatLabel>
                        <div class="mt-1.5 text-[1rem] text-[var(--text-color-secondary)]">Telefone de contato do negócio.</div>
                    </div>
                    <div class="col-span-12 md:col-span-6">
                        <FloatLabel variant="on">
                            <InputText id="neg_email" v-model="form.email" type="email" class="w-full"
                                       :invalid="form.email.length > 0 && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)"
                                       @input="markDirty" />
                            <label for="neg_email">E-mail de contato</label>
                        </FloatLabel>
                        <Message v-if="form.email.length > 0 && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)"
                                 severity="error" size="small" variant="simple" class="mt-1">E-mail inválido.</Message>
                        <div v-else class="mt-1.5 text-[1rem] text-[var(--text-color-secondary)]">E-mail público do negócio.</div>
                    </div>
                </div>
            </div>

            <!-- ── 05 REDES SOCIAIS ───────────────────────────── -->
            <div id="redes"
                 class="ncard relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-6 scroll-mt-20 transition-[border-color] duration-[220ms]"
                 style="--c: #e879f9; --c-dim: rgba(232,121,249,0.08); --c-border: rgba(232,121,249,0.22)">
                <div class="ncard__num">05</div>
                <div class="ncard__shine" />

                <div class="flex items-center gap-2.5 mb-3.5">
                    <div class="w-9 h-9 rounded-[0.625rem] shrink-0 flex items-center justify-center" style="background:var(--c-dim);border:1px solid var(--c-border);color:var(--c)"><i class="pi pi-share-alt" /></div>
                    <span class="text-[1rem] font-extrabold uppercase tracking-[0.14em] opacity-75" style="color:var(--c)">Redes Sociais</span>
                </div>
                <div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)] mb-1">Presença digital</div>
                <div class="text-[1rem] text-[var(--text-color-secondary)] leading-relaxed">Site e redes do seu negócio, exibidos no perfil público.</div>

                <div class="h-px bg-[var(--surface-border)] my-5" />

                <div class="grid grid-cols-12 gap-4">
                    <div class="col-span-12 md:col-span-6">
                        <FloatLabel variant="on">
                            <IconField>
                                <InputIcon class="pi pi-globe" />
                                <InputText id="neg_site" v-model="form.site" type="url" class="w-full" @input="markDirty" />
                            </IconField>
                            <label for="neg_site">Site</label>
                        </FloatLabel>
                        <div class="mt-1.5 text-[1rem] text-[var(--text-color-secondary)]">Ex: https://seunegocio.com.br</div>
                    </div>
                </div>

                <!-- Redes personalizadas -->
                <div class="mt-5">
                    <div class="flex items-center justify-between mb-3">
                        <div>
                            <div class="text-[1rem] font-semibold text-[var(--text-color)]">Outras redes</div>
                            <div class="text-[1rem] text-[var(--text-color-secondary)]">Instagram, YouTube, LinkedIn ou qualquer outro link.</div>
                        </div>
                        <Button icon="pi pi-plus" label="Adicionar" severity="secondary" size="small" outlined class="rounded-full" @click="addRede" />
                    </div>

                    <div v-if="form.redes_sociais.length" class="flex flex-col gap-3">
                        <div v-for="(item, idx) in form.redes_sociais" :key="idx" class="flex items-center gap-2">
                            <FloatLabel variant="on" class="flex-1">
                                <InputText :id="`neg_rn_${idx}`" v-model="item.name" class="w-full" @input="markDirty" />
                                <label :for="`neg_rn_${idx}`">Nome da rede</label>
                            </FloatLabel>
                            <FloatLabel variant="on" class="flex-[2]">
                                <IconField>
                                    <InputIcon class="pi pi-link" />
                                    <InputText :id="`neg_ru_${idx}`" v-model="item.url" class="w-full" @input="markDirty" />
                                </IconField>
                                <label :for="`neg_ru_${idx}`">URL / usuário</label>
                            </FloatLabel>
                            <Button icon="pi pi-trash" severity="danger" text rounded size="small" v-tooltip.top="'Remover'" @click="removeRede(idx)" />
                        </div>
                    </div>
                    <div v-else class="text-[1rem] text-[var(--text-color-secondary)] italic mt-1">Nenhuma rede adicionada ainda.</div>
                </div>
            </div>

            <!-- ── 06 LOGOMARCA ───────────────────────────────── -->
            <div id="logomarca"
                 class="ncard relative overflow-hidden rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-6 scroll-mt-20 transition-[border-color] duration-[220ms]"
                 style="--c: #fb923c; --c-dim: rgba(251,146,60,0.08); --c-border: rgba(251,146,60,0.22)">
                <div class="ncard__num">06</div>
                <div class="ncard__shine" />

                <div class="flex items-center gap-2.5 mb-3.5">
                    <div class="w-9 h-9 rounded-[0.625rem] shrink-0 flex items-center justify-center" style="background:var(--c-dim);border:1px solid var(--c-border);color:var(--c)"><i class="pi pi-image" /></div>
                    <span class="text-[1rem] font-extrabold uppercase tracking-[0.14em] opacity-75" style="color:var(--c)">Logomarca</span>
                </div>
                <div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)] mb-1">Identidade visual</div>
                <div class="text-[1rem] text-[var(--text-color-secondary)] leading-relaxed">Envie um arquivo ou cole uma URL pública da logomarca.</div>

                <div class="h-px bg-[var(--surface-border)] my-5" />

                <div class="grid grid-cols-12 gap-4 items-start">
                    <!-- Preview -->
                    <div class="col-span-12 md:col-span-3 flex flex-col items-center gap-3">
                        <div class="relative w-24 h-24 rounded-2xl overflow-hidden cursor-pointer group border-2 border-dashed border-[var(--surface-border)] hover:border-amber-500/50 transition-all bg-[var(--surface-ground)]"
                             @click="triggerLogoUpload">
                            <img v-if="ui.logoPreview" :src="ui.logoPreview" class="w-full h-full object-cover" alt="logo preview" />
                            <span v-else class="w-full h-full flex items-center justify-center text-xl font-extrabold text-amber-500">{{ negocioInitials }}</span>
                            <div class="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity rounded-2xl">
                                <i class="pi pi-upload text-white" />
                            </div>
                        </div>
                        <div class="text-center">
                            <div class="text-[1rem] font-medium truncate max-w-[120px]">{{ form.nome_fantasia || '—' }}</div>
                            <div class="text-[1rem] text-[var(--text-color-secondary)] mt-0.5">Preview</div>
                        </div>
                        <Button label="Remover" icon="pi pi-trash" severity="danger" outlined size="small"
                                :disabled="!form.logo_url && !ui.logoFile && !ui.logoPreview"
                                @click="removeLogo" />
                    </div>

                    <!-- Upload + URL -->
                    <div class="col-span-12 md:col-span-9 flex flex-col gap-4">
                        <div class="rounded-md border border-dashed border-[var(--surface-border)] bg-[var(--surface-ground)] p-4 flex flex-col gap-2.5">
                            <div class="flex items-center gap-2 text-[1rem] font-semibold text-[var(--text-color-secondary)]">
                                <i class="pi pi-upload" />
                                <span>Arquivo (PNG · SVG · JPG · máx 2 MB)</span>
                            </div>
                            <div class="flex items-center gap-2 flex-wrap">
                                <input ref="logoInput" type="file" accept="image/*" class="text-[1rem] flex-1 text-[var(--text-color-secondary)]" @change="onLogoChange" />
                                <Button icon="pi pi-times" severity="secondary" outlined size="small" :disabled="!ui.logoFile" v-tooltip.top="'Limpar'" @click="clearLogoFile" />
                            </div>
                            <div class="text-[1rem] text-[var(--text-color-secondary)]">
                                PNG ou SVG recomendado. Ao salvar, enviado ao bucket <b>{{ LOGO_BUCKET }}</b>.
                            </div>
                        </div>

                        <FloatLabel variant="on">
                            <InputText id="neg_logo_url" v-model="form.logo_url" class="w-full"
                                       @input="ui.logoPreview = form.logo_url?.trim(); markDirty()" />
                            <label for="neg_logo_url">Logo URL</label>
                        </FloatLabel>
                        <div class="-mt-2 text-[1rem] text-[var(--text-color-secondary)]">Cole uma URL pública da imagem. Se vazio, usamos as iniciais do nome.</div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <div v-if="mounted" class="px-3 md:px-4 pb-3">
        <LoadedPhraseBlock />
    </div>
</template>

<style scoped>
/* ── Shimmer da barra de progresso ───────────────────────── */
@keyframes neg-shimmer-anim {
    0%   { transform: translateX(-100%); }
    100% { transform: translateX(250%); }
}
.neg-shimmer {
    background: linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.26) 50%, transparent 100%);
    width: 55%;
    animation: neg-shimmer-anim 2.2s ease-in-out infinite;
}

/* ── Badges ───────────────────────────────────────────────── */
.neg-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
    padding: 0.3rem 0.65rem;
    border-radius: 9999px;
    border: 1px solid;
    transition: all 0.18s ease;
    cursor: default;
}
.neg-badge--earned {
    background-color: rgba(245, 158, 11, 0.08);
    border-color: rgba(245, 158, 11, 0.35);
    color: #f59e0b;
}
.neg-badge--locked {
    background-color: var(--surface-ground);
    border-color: var(--surface-border);
    color: var(--text-color-secondary);
    filter: grayscale(1);
    opacity: 0.45;
}

/* ── Sidebar nav ─────────────────────────────────────────── */
.nav-link { color: var(--text-color-secondary); }
.nav-link:hover,
.nav-link--active {
    color: var(--text-color);
    background: var(--surface-ground);
    border-color: var(--surface-border);
}

/* ── Content cards ───────────────────────────────────────── */
.ncard { animation: neg-fadeUp 0.4s ease both; }
.ncard:hover { border-color: var(--c-border); }
.ncard:hover .ncard__shine { opacity: 1; }
.ncard:hover .ncard__num { opacity: 0.055; }

.ncard__num {
    position: absolute;
    top: 0.875rem;
    right: 1.25rem;
    font-size: 4.5rem;
    font-weight: 900;
    letter-spacing: -0.06em;
    line-height: 1;
    color: var(--text-color);
    opacity: 0.022;
    pointer-events: none;
    user-select: none;
    transition: opacity 0.22s;
}

.ncard__shine {
    position: absolute;
    inset: 0;
    border-radius: inherit;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s ease;
    background: radial-gradient(ellipse at 20% 0%, color-mix(in srgb, var(--c) 9%, transparent), transparent 52%);
}

/* ── Animation ───────────────────────────────────────────── */
@keyframes neg-fadeUp {
    from { opacity: 0; transform: translateY(14px); }
    to   { opacity: 1; transform: translateY(0);    }
}
</style>