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

import Textarea from 'primevue/textarea';
import InputNumber from 'primevue/inputnumber';
import Checkbox from 'primevue/checkbox';
import Popover from 'primevue/popover';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';

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

const loading = ref(false);
const isFetching = ref(false);
const rows = ref([]);
const q = ref('');

const showDlg = ref(false);
const saving = ref(false);

const showBulletDlg = ref(false);
const bulletSaving = ref(false);
const bulletIsEdit = ref(false);

const selected = ref(null);

// Intervalo para preview
const billingInterval = ref('month'); // 'month' | 'year'
const intervalOptions = [
    { label: 'Mensal', value: 'month' },
    { label: 'Anual', value: 'year' }
];

// ✅ Filtro de vitrine por público (clinic vs therapist) — ORDEM: Todos, Clínica, Terapeuta
const targetFilter = ref('all'); // 'clinic' | 'therapist' | 'all'
const targetOptions = [
    { label: 'Todos', value: 'all' },
    { label: 'Clínica', value: 'clinic' },
    { label: 'Terapeuta', value: 'therapist' }
];

// ✅ Política de planos sem preço no PREVIEW:
// - 'hide'    => não mostra no preview
// - 'consult' => mostra com "Sob consulta"
const previewPricePolicy = ref('hide'); // 'hide' | 'consult'
const previewPolicyOptions = [
    { label: 'Ocultar sem preço', value: 'hide' },
    { label: 'Mostrar "Sob consulta"', value: 'consult' }
];

function normalizeTarget(row) {
    return row?.plan_target || null;
}

function targetLabel(t) {
    if (t === 'clinic') return 'Clínica';
    if (t === 'therapist') return 'Terapeuta';
    return '—';
}

function targetSeverity(t) {
    if (t === 'clinic') return 'info';
    if (t === 'therapist') return 'success';
    return 'secondary';
}

function priceCentsFor(p, interval) {
    return interval === 'year' ? p.yearly_cents : p.monthly_cents;
}

function isPriceDefined(cents) {
    return cents !== null && cents !== undefined;
}

function isFree(cents) {
    return isPriceDefined(cents) && Number(cents) === 0;
}

function formatBRLFromCents(cents) {
    if (cents == null) return '—';
    const v = Number(cents) / 100;
    return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}

// ✅ Texto/estado do preço no preview
function priceDisplayForPreview(p) {
    const cents = priceCentsFor(p, billingInterval.value);

    if (!isPriceDefined(cents)) {
        return {
            kind: 'none',
            main: previewPricePolicy.value === 'consult' ? 'Sob consulta' : '—',
            sub: ''
        };
    }

    if (isFree(cents)) {
        return {
            kind: 'free',
            main: 'Grátis',
            sub: ''
        };
    }

    return {
        kind: 'paid',
        main: formatBRLFromCents(cents),
        sub: billingInterval.value === 'year' ? 'por ano' : 'por mês'
    };
}

const form = ref({
    plan_id: null,
    public_name: '',
    public_description: '',
    badge: '',
    is_featured: false,
    is_visible: true,
    sort_order: 0
});

const bullets = ref([]);
const bulletForm = ref({
    id: null,
    text: '',
    sort_order: 0,
    highlight: false
});

/* popover bullets (na tabela) */
const bulletsPop = ref(null);
const popPlanTitle = ref('');
const popBullets = ref([]);

function openBulletsPopover(event, row) {
    popPlanTitle.value = row?.public_name || row?.plan_name || row?.plan_key || 'Benefícios';
    popBullets.value = Array.isArray(row?.bullets) ? row.bullets : [];
    bulletsPop.value?.toggle(event);
}

/**
 * ✅ BASE: busca textual (sem filtro de público)
 */
const searchedRows = computed(() => {
    const term = String(q.value || '')
        .trim()
        .toLowerCase();
    const list = rows.value || [];

    if (!term) return list;

    return list.filter((r) => {
        const a = String(r.public_name || '').toLowerCase();
        const b = String(r.plan_key || '').toLowerCase();
        const c = String(r.plan_name || '').toLowerCase();
        return a.includes(term) || b.includes(term) || c.includes(term);
    });
});

/**
 * ✅ TABELA: agora o filtro Todos/Clínica/Terapeuta também afeta a tabela
 */
const tableRows = computed(() => {
    let list = (searchedRows.value || []).slice();

    if (targetFilter.value !== 'all') {
        list = list.filter((r) => normalizeTarget(r) === targetFilter.value);
    }

    return list;
});

/**
 * ✅ PREVIEW: usa o mesmo filtro de público + visibilidade
 */
const previewRows = computed(() => {
    let list = (searchedRows.value || []).slice();

    if (targetFilter.value !== 'all') {
        list = list.filter((r) => normalizeTarget(r) === targetFilter.value);
    }

    list = list.filter((r) => r.is_visible !== false);
    return list;
});

const previewPlans = computed(() => {
    let list = (previewRows.value || []).slice();

    if (previewPricePolicy.value === 'hide') {
        list = list.filter((p) => isPriceDefined(priceCentsFor(p, billingInterval.value)));
    }

    list.sort((a, b) => {
        const af = a.is_featured ? 0 : 1;
        const bf = b.is_featured ? 0 : 1;
        if (af !== bf) return af - bf;

        const ao = Number(a.sort_order ?? 0);
        const bo = Number(b.sort_order ?? 0);
        if (ao !== bo) return ao - bo;

        return String(a.plan_key || '').localeCompare(String(b.plan_key || ''));
    });

    return list;
});

async function fetchAll() {
    if (isFetching.value) return;
    isFetching.value = true;
    loading.value = true;

    try {
        const { data, error } = await supabase.from('v_public_pricing').select('*').order('plan_target', { ascending: true }).order('is_featured', { ascending: false }).order('sort_order', { ascending: true }).order('plan_key', { ascending: true });

        if (error) throw error;
        rows.value = data || [];
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 4500 });
    } finally {
        loading.value = false;
        isFetching.value = false;
    }
}

async function openEdit(row) {
    if (saving.value || bulletSaving.value) return;

    selected.value = row;
    form.value = {
        plan_id: row.plan_id,
        public_name: row.public_name || row.plan_name || row.plan_key || '',
        public_description: row.public_description || '',
        badge: row.badge || '',
        is_featured: !!row.is_featured,
        is_visible: row.is_visible !== false,
        sort_order: Number(row.sort_order ?? 0)
    };

    await fetchBullets(row.plan_id);
    showDlg.value = true;
}

async function fetchBullets(planId) {
    const { data, error } = await supabase.from('plan_public_bullets').select('*').eq('plan_id', planId).order('sort_order', { ascending: true }).order('created_at', { ascending: true });

    if (error) {
        toast.add({ severity: 'error', summary: 'Erro', detail: error.message, life: 4500 });
        bullets.value = [];
        return;
    }

    bullets.value = data || [];
}

function validate() {
    const name = String(form.value.public_name || '').trim();
    if (!name) {
        toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Informe o nome público do plano.', life: 3000 });
        return false;
    }

    form.value.public_name = name;
    form.value.public_description = String(form.value.public_description || '').trim();
    form.value.badge = String(form.value.badge || '').trim() || null;
    form.value.sort_order = Number(form.value.sort_order ?? 0);
    form.value.is_featured = !!form.value.is_featured;
    form.value.is_visible = !!form.value.is_visible;

    return true;
}

async function save() {
    if (!validate()) return;
    saving.value = true;

    try {
        const payload = { ...form.value };
        const { error } = await supabase.from('plan_public').upsert(payload, { onConflict: 'plan_id' });

        if (error) throw error;

        toast.add({ severity: 'success', summary: 'Ok', detail: 'Vitrine atualizada.', life: 2500 });
        showDlg.value = false;
        await fetchAll();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 4500 });
    } finally {
        saving.value = false;
    }
}

/* ---------- bullets (CRUD no dialog) ---------- */

function openBulletCreate() {
    bulletIsEdit.value = false;
    bulletForm.value = {
        id: null,
        text: '',
        sort_order: (bullets.value?.length || 0) + 1,
        highlight: false
    };
    showBulletDlg.value = true;
}

function openBulletEdit(row) {
    bulletIsEdit.value = true;
    bulletForm.value = {
        id: row.id,
        text: row.text ?? '',
        sort_order: Number(row.sort_order ?? 0),
        highlight: !!row.highlight
    };
    showBulletDlg.value = true;
}

function validateBullet() {
    const t = String(bulletForm.value.text || '').trim();
    if (!t) {
        toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Informe o texto do benefício.', life: 3000 });
        return false;
    }
    bulletForm.value.text = t;
    bulletForm.value.sort_order = Number(bulletForm.value.sort_order ?? 0);
    bulletForm.value.highlight = !!bulletForm.value.highlight;
    return true;
}

async function saveBullet() {
    if (!selected.value?.plan_id) return;
    if (!validateBullet()) return;
    bulletSaving.value = true;

    try {
        const payload = {
            plan_id: selected.value.plan_id,
            text: bulletForm.value.text,
            sort_order: bulletForm.value.sort_order,
            highlight: !!bulletForm.value.highlight
        };

        if (bulletIsEdit.value) {
            const { error } = await supabase.from('plan_public_bullets').update(payload).eq('id', bulletForm.value.id);

            if (error) throw error;
            toast.add({ severity: 'success', summary: 'Ok', detail: 'Benefício atualizado.', life: 2200 });
        } else {
            const { error } = await supabase.from('plan_public_bullets').insert(payload);

            if (error) throw error;
            toast.add({ severity: 'success', summary: 'Ok', detail: 'Benefício adicionado.', life: 2200 });
        }

        showBulletDlg.value = false;
        await fetchBullets(selected.value.plan_id);
        await fetchAll();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || String(e), life: 4500 });
    } finally {
        bulletSaving.value = false;
    }
}

function askDeleteBullet(row) {
    confirm.require({
        message: 'Excluir este benefício?',
        header: 'Confirmar exclusão',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        accept: () => doDeleteBullet(row)
    });
}

async function doDeleteBullet(row) {
    const { error } = await supabase.from('plan_public_bullets').delete().eq('id', row.id);

    if (error) {
        toast.add({ severity: 'error', summary: 'Erro', detail: error.message, life: 4500 });
        return;
    }

    toast.add({ severity: 'success', summary: 'Ok', detail: 'Benefício removido.', life: 2200 });
    await fetchBullets(selected.value.plan_id);
    await fetchAll();
}

// ── Hero sticky ───────────────────────────────────────────
const heroEl = ref(null);
const heroSentinelRef = ref(null);
const heroMenuRef = ref(null);
const heroStuck = ref(false);
let disconnectStickyObserver = null;

const heroMenuItems = computed(() => [
    { label: 'Recarregar', icon: 'pi pi-refresh', command: fetchAll, disabled: loading.value || saving.value || bulletSaving.value },
    { separator: true },
    {
        label: 'Filtrar por público',
        items: targetOptions.map((o) => ({
            label: o.label,
            command: () => {
                targetFilter.value = o.value;
            }
        }))
    }
]);

onMounted(async () => {
    await fetchAll();

    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 {
        disconnectStickyObserver?.();
    } catch {}
});
</script>

<template>
    <ConfirmDialog />

    <div class="flex flex-col gap-4 p-4">
        <!-- Header -->
        <div class="cfg-subheader">
            <div class="cfg-subheader__icon"><i class="pi pi-shop" /></div>
            <div class="min-w-0 flex-1">
                <div class="cfg-subheader__title">Vitrine de Planos</div>
                <div class="cfg-subheader__sub">Configure como os planos aparecem na página pública.</div>
            </div>
            <div class="hidden xl:flex items-center gap-2 shrink-0">
                <SelectButton v-model="targetFilter" :options="targetOptions" optionLabel="label" optionValue="value" size="small" :disabled="loading || saving || bulletSaving" />
                <Button label="Recarregar" icon="pi pi-refresh" severity="secondary" outlined size="small" :loading="loading" :disabled="saving || bulletSaving" @click="fetchAll" />
            </div>
            <div class="flex xl:hidden shrink-0">
                <Button label="Ações" icon="pi pi-ellipsis-v" severity="warn" size="small" aria-haspopup="true" aria-controls="showcase_hero_menu" @click="(e) => heroMenuRef.toggle(e)" />
                <Menu ref="heroMenuRef" id="showcase_hero_menu" :model="heroMenuItems" :popup="true" />
            </div>
        </div>
        <!-- Search -->
        <div>
            <FloatLabel variant="on" class="w-full md:w-80">
                <IconField class="w-full">
                    <InputIcon class="pi pi-search" />
                    <InputText v-model="q" id="plans_public_search" class="w-full pr-10" variant="filled" :disabled="loading || saving || bulletSaving" />
                </IconField>
                <label for="plans_public_search">Buscar plano</label>
            </FloatLabel>
        </div>

        <!-- Popover global (reutilizado) -->
        <Popover ref="bulletsPop">
            <div class="w-[340px] max-w-[80vw]">
                <div class="text-[1rem] font-semibold mb-2">{{ popPlanTitle }}</div>

                <div v-if="!popBullets?.length" class="text-[1rem] text-[var(--text-color-secondary)]">Nenhum benefício configurado.</div>

                <ul v-else class="m-0 pl-4 space-y-2">
                    <li v-for="b in popBullets" :key="b.id" class="text-[1rem] leading-snug">
                        <span :class="b.highlight ? 'font-semibold' : ''">
                            {{ b.text }}
                        </span>
                        <div v-if="b.highlight" class="inline ml-2 text-[1rem] text-[var(--text-color-secondary)]">(destaque)</div>
                    </li>
                </ul>
            </div>
        </Popover>

        <DataTable :value="tableRows" dataKey="plan_id" :loading="loading" stripedRows responsiveLayout="scroll">
            <Column header="Plano" style="min-width: 18rem">
                <template #body="{ data }">
                    <div class="flex flex-col">
                        <span class="font-semibold">{{ data.public_name || data.plan_name || data.plan_key }}</span>
                        <div class="text-[1rem] text-[var(--text-color-secondary)]">{{ data.plan_key }} • {{ data.plan_name || '—' }}</div>
                    </div>
                </template>
            </Column>

            <Column header="Público" style="width: 10rem">
                <template #body="{ data }">
                    <Tag :value="targetLabel(normalizeTarget(data))" :severity="targetSeverity(normalizeTarget(data))" rounded />
                </template>
            </Column>

            <Column header="Mensal" style="width: 12rem">
                <template #body="{ data }">
                    <span class="font-medium">{{ formatBRLFromCents(data.monthly_cents) }}</span>
                </template>
            </Column>

            <Column header="Anual" style="width: 12rem">
                <template #body="{ data }">
                    <span class="font-medium">{{ formatBRLFromCents(data.yearly_cents) }}</span>
                </template>
            </Column>

            <Column field="badge" header="Badge" style="min-width: 12rem" />

            <Column header="Visível" style="width: 8rem">
                <template #body="{ data }">
                    <span>{{ data.is_visible ? 'Sim' : 'Não' }}</span>
                </template>
            </Column>

            <Column header="Destaque" style="width: 9rem">
                <template #body="{ data }">
                    <span>{{ data.is_featured ? 'Sim' : 'Não' }}</span>
                </template>
            </Column>

            <Column field="sort_order" header="Ordem" style="width: 8rem" />

            <Column header="Ações" style="width: 14rem">
                <template #body="{ data }">
                    <div class="flex gap-2 justify-end">
                        <Button severity="secondary" outlined size="small" :disabled="loading || saving || bulletSaving" @click="(e) => openBulletsPopover(e, data)">
                            <i class="pi pi-list mr-2" />
                            <span class="font-medium">{{ data.bullets?.length || 0 }}</span>
                        </Button>

                        <Button icon="pi pi-pencil" severity="secondary" outlined size="small" :disabled="loading || saving || bulletSaving" @click="openEdit(data)" />
                    </div>
                </template>
            </Column>
        </DataTable>

        <!-- PREVIEW PÚBLICO (conceitual) -->
        <div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] overflow-hidden">
            <!-- Hero -->
            <div class="relative p-6 md:p-10">
                <div class="absolute inset-0 opacity-40 pointer-events-none bg-[radial-gradient(ellipse_at_top,rgba(16,185,129,0.18),transparent_55%)]" />
                <div class="relative">
                    <div class="flex flex-col md:flex-row md:items-end md:justify-between gap-6">
                        <div class="max-w-2xl">
                            <div class="flex items-center gap-2 mb-3 flex-wrap">
                                <Tag :value="targetFilter === 'all' ? 'Vitrine (Todos)' : `Vitrine (${targetLabel(targetFilter)})`" :severity="targetFilter === 'therapist' ? 'success' : targetFilter === 'clinic' ? 'info' : 'secondary'" rounded />
                                <div class="text-[1rem] text-[var(--text-color-secondary)]">Ajuste nomes, descrições, badges e benefícios — e veja o resultado aqui.</div>
                            </div>

                            <div class="text-3xl md:text-5xl font-semibold leading-tight">
                                Um plano não é preço.<br />
                                É promessa organizada.
                            </div>

                            <div class="text-[var(--text-color-secondary)] mt-3">A vitrine é o lugar onde o produto deixa de ser tabela e vira escolha. Clareza, contraste e uma hierarquia que guia o olhar — sem ruído.</div>
                        </div>

                        <div class="flex flex-col items-start md:items-end gap-4">
                            <div class="flex flex-col gap-2">
                                <div class="text-[1rem] text-[var(--text-color-secondary)]">Cobrança</div>
                                <SelectButton v-model="billingInterval" :options="intervalOptions" optionLabel="label" optionValue="value" />
                            </div>

                            <div class="flex flex-col gap-2">
                                <div class="text-[1rem] text-[var(--text-color-secondary)]">Planos sem preço</div>
                                <SelectButton v-model="previewPricePolicy" :options="previewPolicyOptions" optionLabel="label" optionValue="value" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Cards -->
            <div class="p-6 md:p-10 pt-0">
                <div v-if="!previewPlans.length" class="text-[1rem] text-[var(--text-color-secondary)]">Nenhum plano visível para este filtro.</div>

                <div v-else class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div
                        v-for="p in previewPlans"
                        :key="p.plan_id"
                        :class="[
                            'relative rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] overflow-hidden',
                            'shadow-sm transition-transform',
                            p.is_featured ? 'md:-translate-y-2 md:scale-[1.02] ring-1 ring-emerald-500/25' : ''
                        ]"
                    >
                        <div class="h-2 w-full opacity-50 bg-[var(--surface-100)]" />

                        <div class="p-6">
                            <div class="flex items-center justify-between gap-3">
                                <div class="flex items-center gap-2 flex-wrap">
                                    <Tag :value="targetLabel(normalizeTarget(p))" :severity="targetSeverity(normalizeTarget(p))" rounded />
                                    <Tag v-if="p.badge || p.is_featured" :value="p.badge || 'Destaque'" :severity="p.is_featured ? 'success' : 'secondary'" rounded />
                                </div>

                                <div class="text-[1rem] text-[var(--text-color-secondary)]">{{ p.plan_key }}</div>
                            </div>

                            <div class="mt-4">
                                <template v-if="priceDisplayForPreview(p).kind === 'paid'">
                                    <div class="text-4xl font-semibold leading-none">
                                        {{ priceDisplayForPreview(p).main }}
                                    </div>
                                    <div class="text-[1rem] text-[var(--text-color-secondary)] mt-1">
                                        {{ priceDisplayForPreview(p).sub }}
                                    </div>
                                </template>

                                <template v-else-if="priceDisplayForPreview(p).kind === 'free'">
                                    <div class="text-4xl font-semibold leading-none">
                                        {{ priceDisplayForPreview(p).main }}
                                    </div>
                                    <div class="text-[1rem] text-[var(--text-color-secondary)] mt-1">
                                        {{ billingInterval === 'year' ? 'no anual' : 'no mensal' }}
                                    </div>
                                </template>

                                <template v-else>
                                    <div class="text-2xl font-semibold leading-none">
                                        {{ priceDisplayForPreview(p).main }}
                                    </div>
                                    <div class="text-[1rem] text-[var(--text-color-secondary)] mt-1">Fale com a equipe para montar o plano ideal.</div>
                                </template>
                            </div>

                            <div class="text-[var(--text-color-secondary)] mt-3 min-h-[44px]">
                                {{ p.public_description || '—' }}
                            </div>

                            <Button class="mt-5 w-full" :label="p.is_featured ? 'Começar agora' : 'Selecionar plano'" :severity="p.is_featured ? 'success' : 'secondary'" :outlined="!p.is_featured" />

                            <div class="mt-6">
                                <div class="border-t border-dashed border-[var(--surface-border)]" />
                            </div>

                            <ul v-if="p.bullets?.length" class="mt-4 space-y-2">
                                <li v-for="b in p.bullets" :key="b.id" class="flex items-start gap-2">
                                    <i class="pi pi-check mt-1 text-[1rem] text-[var(--text-color-secondary)]"></i>
                                    <span :class="['text-[1rem] leading-snug', b.highlight ? 'font-semibold' : '']">
                                        {{ b.text }}
                                    </span>
                                </li>
                            </ul>

                            <div v-else class="mt-4 text-[1rem] text-[var(--text-color-secondary)]">Nenhum benefício configurado.</div>
                        </div>
                    </div>
                </div>

                <div v-if="previewPricePolicy === 'hide'" class="mt-6 text-[1rem] text-[var(--text-color-secondary)]">Observação: planos sem preço não aparecem no preview (política atual). Para exibir como "Sob consulta", mude acima.</div>
            </div>
        </div>
    </div>
    <!-- /content -->

    <!-- Dialog principal (✅ sem drag: removemos draggable) -->
    <Dialog v-model:visible="showDlg" modal header="Editar vitrine" :style="{ width: '820px' }" :closable="!saving" :dismissableMask="!saving" :draggable="false">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="flex flex-col gap-4">
                <!-- ✅ Nome público (FloatLabel + Icon) -->
                <FloatLabel variant="on">
                    <IconField>
                        <InputIcon class="pi pi-tag" />
                        <InputText id="pp-public-name" v-model.trim="form.public_name" class="w-full" variant="filled" :disabled="saving" autocomplete="off" autofocus @keydown.enter.prevent="save" />
                    </IconField>
                    <label for="pp-public-name">Nome público *</label>
                </FloatLabel>

                <!-- ✅ Descrição pública -->
                <FloatLabel variant="on">
                    <IconField>
                        <InputIcon class="pi pi-align-left" />
                        <Textarea id="pp-public-desc" v-model.trim="form.public_description" class="w-full" rows="3" autoResize :disabled="saving" />
                    </IconField>
                    <label for="pp-public-desc">Descrição pública</label>
                </FloatLabel>

                <!-- ✅ Badge -->
                <FloatLabel variant="on">
                    <IconField>
                        <InputIcon class="pi pi-bookmark" />
                        <InputText id="pp-badge" v-model.trim="form.badge" class="w-full" variant="filled" :disabled="saving" autocomplete="off" @keydown.enter.prevent="save" />
                    </IconField>
                    <label for="pp-badge">Badge (opcional)</label>
                </FloatLabel>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- ✅ Ordem -->
                    <FloatLabel variant="on">
                        <IconField>
                            <InputIcon class="pi pi-sort-amount-up-alt" />
                            <InputNumber id="pp-sort" v-model="form.sort_order" class="w-full" inputClass="w-full" :disabled="saving" />
                        </IconField>
                        <label for="pp-sort">Ordem</label>
                    </FloatLabel>

                    <div class="flex flex-col gap-3 pt-2">
                        <div class="flex items-center gap-2">
                            <Checkbox v-model="form.is_visible" :binary="true" :disabled="saving" />
                            <label>Visível no público</label>
                        </div>
                        <div class="flex items-center gap-2">
                            <Checkbox v-model="form.is_featured" :binary="true" :disabled="saving" />
                            <label>Destaque</label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- bullets -->
            <div>
                <div class="flex items-center justify-between mb-3">
                    <div class="font-semibold">Benefícios (bullets)</div>
                    <Button label="Adicionar" icon="pi pi-plus" size="small" :disabled="saving || bulletSaving" @click="openBulletCreate" />
                </div>

                <DataTable :value="bullets" dataKey="id" stripedRows responsiveLayout="scroll">
                    <Column field="text" header="Texto" />
                    <Column field="sort_order" header="Ordem" style="width: 7rem" />
                    <Column header="Destaque" style="width: 8rem">
                        <template #body="{ data }">
                            <span>{{ data.highlight ? 'Sim' : 'Não' }}</span>
                        </template>
                    </Column>
                    <Column header="Ações" style="width: 9rem">
                        <template #body="{ data }">
                            <div class="flex gap-2">
                                <Button icon="pi pi-pencil" severity="secondary" outlined size="small" :disabled="saving || bulletSaving" @click="openBulletEdit(data)" />
                                <Button icon="pi pi-trash" severity="danger" outlined size="small" :disabled="saving || bulletSaving" @click="askDeleteBullet(data)" />
                            </div>
                        </template>
                    </Column>
                </DataTable>
            </div>
        </div>

        <template #footer>
            <Button label="Cancelar" severity="secondary" outlined :disabled="saving" @click="showDlg = false" />
            <Button label="Salvar" icon="pi pi-check" :loading="saving" @click="save" />
        </template>
    </Dialog>

    <!-- Dialog bullet (✅ sem drag + inputs padronizados) -->
    <Dialog v-model:visible="showBulletDlg" modal :header="bulletIsEdit ? 'Editar benefício' : 'Novo benefício'" :style="{ width: '560px' }" :closable="!bulletSaving" :dismissableMask="!bulletSaving" :draggable="false">
        <div class="flex flex-col gap-4">
            <FloatLabel variant="on">
                <IconField>
                    <InputIcon class="pi pi-list" />
                    <Textarea id="pp-bullet-text" v-model.trim="bulletForm.text" class="w-full" rows="3" autoResize :disabled="bulletSaving" />
                </IconField>
                <label for="pp-bullet-text">Texto *</label>
            </FloatLabel>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FloatLabel variant="on">
                    <IconField>
                        <InputIcon class="pi pi-sort-numeric-up" />
                        <InputNumber id="pp-bullet-order" v-model="bulletForm.sort_order" class="w-full" inputClass="w-full" :disabled="bulletSaving" />
                    </IconField>
                    <label for="pp-bullet-order">Ordem</label>
                </FloatLabel>

                <div class="flex items-center gap-2 pt-7">
                    <Checkbox v-model="bulletForm.highlight" :binary="true" :disabled="bulletSaving" />
                    <label>Destaque</label>
                </div>
            </div>
        </div>

        <template #footer>
            <Button label="Cancelar" severity="secondary" outlined :disabled="bulletSaving" @click="showBulletDlg = false" />
            <Button :label="bulletIsEdit ? 'Salvar' : 'Criar'" icon="pi pi-check" :loading="bulletSaving" @click="saveBullet" />
        </template>
    </Dialog>
</template>