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

import { supabase } from '@/lib/supabase/client';
import { tenantDb } from '@/lib/supabase/tenantClient';
import Checkbox from 'primevue/checkbox';
import Menu from 'primevue/menu';

import { createGroup, deleteGroup, listGroupsWithCounts, updateGroup } from '@/services/GruposPacientes.service.js';

import PatientCadastroDialog from '@/components/ui/PatientCadastroDialog.vue';
import { getSysGroupColor, getSystemGroupDefaultColor, setSysGroupColor } from '@/utils/systemGroupColors.js';

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

// ── Hero sticky ───────────────────────────────────────────
const headerEl = ref(null);
const headerSentinelRef = ref(null);
const headerStuck = ref(false);
let _observer = null;

// ── Mobile ────────────────────────────────────────────────
const grpMobileMenuRef = ref(null);
const grpSearchDlgOpen = ref(false);

const grpMobileMenuItems = computed(() => [
    { label: 'Adicionar grupo', icon: 'pi pi-plus', command: () => openCreate() },
    {
        label: 'Buscar',
        icon: 'pi pi-search',
        command: () => {
            grpSearchDlgOpen.value = true;
        }
    },
    { separator: true },
    ...(selectedGroups.value?.length ? [{ label: 'Excluir selecionados', icon: 'pi pi-trash', command: () => confirmDeleteSelected() }, { separator: true }] : []),
    { label: 'Recarregar', icon: 'pi pi-refresh', command: () => fetchAll() }
]);

const dt = ref(null);
const loading = ref(false);
const hasLoaded = ref(false);
const groups = ref([]);
const selectedGroups = ref([]);

const filters = ref({ global: { value: null, matchMode: 'contains' } });

// ── Quick-stats ───────────────────────────────────────────
const quickStats = computed(() => {
    const all = groups.value || [];
    const sistema = all.filter((g) => g.is_system).length;
    const custom = all.filter((g) => !g.is_system).length;
    const comPacs = cards.value.length;
    const totalPacs = all.reduce((s, g) => s + Number(g.patients_count ?? g.patient_count ?? 0), 0);
    return [
        { label: 'Total de grupos', value: all.length, cls: '' },
        { label: 'Grupos padrão', value: sistema, cls: '' },
        { label: 'Meus grupos', value: custom, cls: custom > 0 ? 'qs-ok' : '' },
        { label: 'Com pacientes', value: comPacs, cls: comPacs > 0 ? 'qs-ok' : '' },
        { label: 'Total pacientes', value: totalPacs, cls: '' }
    ];
});

function systemDefaultColor(row) {
    return getSystemGroupDefaultColor(row.nome).replace('#', '');
}

function effectiveCor(row) {
    if (row.is_system) {
        const stored = getSysGroupColor(row.id);
        if (stored) return stored.replace('#', '');
        if (row.cor) return row.cor;
        return systemDefaultColor(row);
    }
    return row.cor || '';
}

// ── Dialog ────────────────────────────────────────────────
const dlg = reactive({ open: false, mode: 'create', id: '', nome: '', cor: '', saving: false, isSystem: false });

const dlgPresetColors = [
    { bg: '6366f1', name: 'Índigo' },
    { bg: '8b5cf6', name: 'Violeta' },
    { bg: 'ec4899', name: 'Rosa' },
    { bg: 'ef4444', name: 'Vermelho' },
    { bg: 'f97316', name: 'Laranja' },
    { bg: 'eab308', name: 'Amarelo' },
    { bg: '22c55e', name: 'Verde' },
    { bg: '14b8a6', name: 'Teal' },
    { bg: '3b82f6', name: 'Azul' },
    { bg: '06b6d4', name: 'Ciano' },
    { bg: '64748b', name: 'Ardósia' },
    { bg: '292524', name: 'Escuro' }
];

const dlgPreviewColor = computed(() => (!dlg.cor ? '#64748b' : dlg.cor.startsWith('#') ? dlg.cor : `#${dlg.cor}`));
const dlgPresetBgValues = dlgPresetColors.map((p) => p.bg);
const isCustomColor = computed(() => {
    if (!dlg.cor) return false;
    return !dlgPresetBgValues.includes(String(dlg.cor).replace('#', '').toLowerCase());
});

// ── Dialog pacientes ──────────────────────────────────────
const patientsDialog = reactive({ open: false, loading: false, error: '', group: null, items: [], search: '' });

// ── Cards painel lateral ──────────────────────────────────
const cards = computed(() =>
    (groups.value || [])
        .filter((g) => {
            const n = Number.parseInt(String(g.patients_count ?? g.patient_count ?? 0), 10);
            return Number.isFinite(n) && n > 0;
        })
        .sort((a, b) => {
            const na = Number.parseInt(String(a.patients_count ?? a.patient_count ?? 0), 10) || 0;
            const nb = Number.parseInt(String(b.patients_count ?? b.patient_count ?? 0), 10) || 0;
            return nb - na;
        })
);

const patientsDialogFiltered = computed(() => {
    const s = String(patientsDialog.search || '')
        .trim()
        .toLowerCase();
    if (!s) return patientsDialog.items || [];
    return (patientsDialog.items || []).filter(
        (p) =>
            String(p.full_name || '')
                .toLowerCase()
                .includes(s) ||
            String(p.email || '')
                .toLowerCase()
                .includes(s) ||
            String(p.phone || '')
                .toLowerCase()
                .includes(s)
    );
});

function patientsLabel(n) {
    return n === 1 ? '1 paciente' : `${n} pacientes`;
}

function colorStyle(cor) {
    const hex = String(cor || '').startsWith('#') ? cor : '#' + cor;
    return { background: hex };
}

const patientsGroupHex = computed(() => {
    if (!patientsDialog.group) return '#6366f1';
    const raw = effectiveCor(patientsDialog.group);
    return raw ? (raw.startsWith('#') ? raw : `#${raw}`) : '#6366f1';
});

function humanizeError(err) {
    const msg = err?.message || err?.error_description || String(err) || 'Erro inesperado.';
    const code = err?.code;
    if (code === '23505' || /duplicate key value/i.test(msg)) return 'Já existe um grupo com esse nome. Tente outro nome.';
    if (/Grupo padrão/i.test(msg)) return 'Esse é um grupo padrão do sistema e não pode ser alterado.';
    return msg;
}

// ── Fetch ─────────────────────────────────────────────────
async function fetchAll() {
    loading.value = true;
    try {
        const baseGroups = await listGroupsWithCounts();
        const realCountMap = await fetchRealGroupCountsForOwner();
        groups.value = applyRealCountsToGroups(baseGroups, realCountMap);
    } catch (err) {
        toast.add({ severity: 'error', summary: 'Erro', detail: humanizeError(err), life: 3500 });
    } finally {
        loading.value = false;
        hasLoaded.value = true;
    }
}

function applyRealCountsToGroups(groupsArr, countMap) {
    return (groupsArr || []).map((g) => ({ ...g, patients_count: Number(countMap[g.id] || 0) }));
}

async function fetchRealGroupCountsForOwner() {
    const ownerId = (await supabase.auth.getUser())?.data?.user?.id;
    if (!ownerId) throw new Error('Sessão inválida.');
    const { data, error } = await tenantDb().from('patient_group_patient').select('patient_group_id, patient:patients!inner(id, owner_id)').eq('patient.owner_id', ownerId);
    if (error) throw error;
    const map = Object.create(null);
    for (const row of data || []) {
        const gid = row.patient_group_id;
        if (gid) map[gid] = (map[gid] || 0) + 1;
    }
    return map;
}

// ── Seleção ───────────────────────────────────────────────
function isSelected(row) {
    return (selectedGroups.value || []).some((s) => s.id === row.id);
}
function toggleRowSelection(row, checked) {
    if (row.is_system) return;
    const sel = selectedGroups.value || [];
    selectedGroups.value = checked ? (sel.some((s) => s.id === row.id) ? sel : [...sel, row]) : sel.filter((s) => s.id !== row.id);
}

// ── CRUD ──────────────────────────────────────────────────
function openCreate() {
    dlg.open = true;
    dlg.mode = 'create';
    dlg.id = '';
    dlg.nome = '';
    dlg.cor = '';
    dlg.isSystem = false;
}
function openEdit(row) {
    dlg.open = true;
    dlg.mode = 'edit';
    dlg.id = row.id;
    dlg.nome = row.nome;
    dlg.cor = row.cor || '';
    dlg.isSystem = false;
}
function openEditColor(row) {
    dlg.open = true;
    dlg.mode = 'edit';
    dlg.id = row.id;
    dlg.nome = row.nome;
    dlg.cor = effectiveCor(row);
    dlg.isSystem = true;
}

async function saveDialog() {
    const nome = String(dlg.nome || '').trim();
    if (!dlg.isSystem) {
        if (!nome) {
            toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Informe um nome.', life: 2500 });
            return;
        }
        if (nome.length < 2) {
            toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Nome muito curto.', life: 2500 });
            return;
        }
    }
    const corRaw = String(dlg.cor || '').trim();
    const cor = corRaw ? (corRaw.startsWith('#') ? corRaw : `#${corRaw}`) : null;
    dlg.saving = true;
    try {
        if (dlg.isSystem) {
            setSysGroupColor(dlg.id, cor);
            toast.add({ severity: 'success', summary: 'Sucesso', detail: 'Cor do grupo atualizada.', life: 2500 });
            dlg.open = false;
            await fetchAll();
            return;
        } else if (dlg.mode === 'create') {
            await createGroup(nome, cor);
            toast.add({ severity: 'success', summary: 'Sucesso', detail: 'Grupo criado.', life: 2500 });
        } else {
            await updateGroup(dlg.id, nome, cor);
            toast.add({ severity: 'success', summary: 'Sucesso', detail: 'Grupo atualizado.', life: 2500 });
        }
        dlg.open = false;
        await fetchAll();
    } catch (err) {
        toast.add({ severity: 'error', summary: 'Erro', detail: humanizeError(err), life: 3500 });
    } finally {
        dlg.saving = false;
    }
}

function confirmDeleteOne(row) {
    confirm.require({
        message: `Excluir "${row.nome}"?`,
        header: 'Excluir grupo',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        acceptLabel: 'Excluir',
        rejectLabel: 'Cancelar',
        accept: async () => {
            try {
                await deleteGroup(row.id);
                toast.add({ severity: 'success', summary: 'Sucesso', detail: 'Grupo excluído.', life: 2500 });
                await fetchAll();
            } catch (err) {
                toast.add({ severity: 'error', summary: 'Erro', detail: humanizeError(err), life: 3500 });
            }
        }
    });
}

function confirmDeleteSelected() {
    const sel = selectedGroups.value || [];
    const deletables = sel.filter((g) => !g.is_system);
    const blocked = sel.filter((g) => g.is_system);
    if (!deletables.length) {
        toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Os itens selecionados são grupos do sistema e não podem ser excluídos.', life: 3500 });
        return;
    }
    const msgBlocked = blocked.length ? ` (${blocked.length} grupo(s) padrão serão ignorados)` : '';
    confirm.require({
        message: `Excluir ${deletables.length} grupo(s)?${msgBlocked}`,
        header: 'Excluir selecionados',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        acceptLabel: 'Excluir',
        rejectLabel: 'Cancelar',
        accept: async () => {
            try {
                for (const g of deletables) await deleteGroup(g.id);
                selectedGroups.value = [];
                toast.add({ severity: 'success', summary: 'Sucesso', detail: 'Exclusão concluída.', life: 2500 });
                await fetchAll();
            } catch (err) {
                toast.add({ severity: 'error', summary: 'Erro', detail: humanizeError(err), life: 3500 });
            }
        }
    });
}

// ── Helpers ───────────────────────────────────────────────
function initials(name) {
    const parts = String(name || '')
        .trim()
        .split(/\s+/)
        .filter(Boolean);
    if (!parts.length) return '—';
    if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

function fmtPhone(v) {
    const d = String(v ?? '').replace(/\D/g, '');
    if (!d) return '—';
    if (d.length === 11) return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
    if (d.length === 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`;
    return d;
}

// ── Modal pacientes ───────────────────────────────────────
async function openGroupPatientsModal(groupRow) {
    patientsDialog.open = true;
    patientsDialog.loading = true;
    patientsDialog.error = '';
    patientsDialog.group = groupRow;
    patientsDialog.items = [];
    patientsDialog.search = '';
    try {
        const { data, error } = await tenantDb().from('patient_group_patient').select('patient_id, patient:patients(id, nome_completo, email_principal, telefone, avatar_url)').eq('patient_group_id', groupRow.id);
        if (error) throw error;
        patientsDialog.items = (data || [])
            .map((r) => r.patient)
            .filter(Boolean)
            .map((p) => ({ id: p.id, full_name: p.nome_completo || '—', email: p.email_principal || '—', phone: p.telefone || '—', avatar_url: p.avatar_url || null }))
            .sort((a, b) => String(a.full_name).localeCompare(String(b.full_name), 'pt-BR'));
    } catch (err) {
        patientsDialog.error = humanizeError(err);
    } finally {
        patientsDialog.loading = false;
    }
}

const editPatientId = ref(null);
const editPatientDialog = ref(false);
function abrirPaciente(patient) {
    if (!patient?.id) return;
    editPatientId.value = String(patient.id);
    editPatientDialog.value = true;
}
watch(editPatientDialog, (isOpen) => {
    if (!isOpen) editPatientId.value = null;
});

onMounted(() => {
    const rootMargin = `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px`;
    _observer = new IntersectionObserver(
        ([entry]) => {
            headerStuck.value = !entry.isIntersecting;
        },
        { threshold: 0, rootMargin }
    );
    if (headerSentinelRef.value) _observer.observe(headerSentinelRef.value);
    fetchAll();
});

onBeforeUnmount(() => {
    _observer?.disconnect();
});

const HIGHLIGHT_MS = 24 * 60 * 60 * 1000;
function isRecent(row) {
    if (!row?.created_at) return false;
    return Date.now() - new Date(row.created_at).getTime() < HIGHLIGHT_MS;
}
</script>

<template>
    <PatientCadastroDialog v-model="editPatientDialog" :patient-id="editPatientId" />

    <!-- Sentinel -->
    <div ref="headerSentinelRef" class="h-px" />

    <!-- ══════════════════════════════════════════════════════
       HERO sticky
  ═══════════════════════════════════════════════════════ -->
    <section
        ref="headerEl"
        class="sticky mx-3 md:mx-4 my-3 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
        :class="{ 'rounded-tl-none rounded-tr-none': headerStuck }"
        :style="{ top: 'var(--layout-sticky-top, 56px)' }"
    >
        <!-- Blobs -->
        <div class="absolute inset-0 pointer-events-none overflow-hidden" aria-hidden="true">
            <div class="absolute w-64 h-64 -top-16 -right-8 rounded-full blur-[60px] bg-emerald-400/10" />
            <div class="absolute w-72 h-72 top-0 -left-16 rounded-full blur-[60px] bg-indigo-500/[0.09]" />
        </div>

        <div class="relative z-1 flex items-center gap-3">
            <!-- Brand -->
            <div class="flex items-center gap-2 shrink-0">
                <div class="grid place-items-center w-9 h-9 rounded-md shrink-0 bg-indigo-500/10 text-indigo-500">
                    <i class="pi pi-sitemap text-base" />
                </div>
                <div class="min-w-0 hidden lg:block">
                    <div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)]">Grupos de Pacientes</div>
                    <div class="text-[1rem] text-[var(--text-color-secondary)]">Organize seus pacientes por grupos temáticos ou clínicos</div>
                </div>
            </div>

            <!-- Busca desktop -->
            <div class="hidden xl:flex flex-1 min-w-0 mx-2">
                <div class="w-64">
                    <FloatLabel variant="on">
                        <IconField class="w-full">
                            <InputIcon class="pi pi-search" />
                            <InputText id="grpSearch" v-model="filters.global.value" class="w-full" :disabled="loading" />
                        </IconField>
                        <label for="grpSearch">Buscar grupo...</label>
                    </FloatLabel>
                </div>
            </div>

            <!-- Ações desktop -->
            <div class="hidden xl:flex items-center gap-1 shrink-0">
                <Button v-if="selectedGroups?.length" label="Excluir selecionados" icon="pi pi-trash" severity="danger" outlined class="rounded-full" @click="confirmDeleteSelected" />
                <Button label="Novo grupo" icon="pi pi-plus" class="rounded-full" @click="openCreate" />
                <Button icon="pi pi-refresh" severity="secondary" outlined class="h-9 w-9 rounded-full" :loading="loading" @click="fetchAll" />
            </div>

            <!-- Mobile -->
            <div class="flex xl:hidden items-center gap-1 shrink-0 ml-auto">
                <Button icon="pi pi-search" severity="secondary" outlined class="h-9 w-9 rounded-full" @click="grpSearchDlgOpen = true" />
                <Button icon="pi pi-plus" class="h-9 w-9 rounded-full" @click="openCreate" />
                <Button label="Ações" icon="pi pi-ellipsis-v" severity="secondary" size="small" class="rounded-full" @click="(e) => grpMobileMenuRef.toggle(e)" />
                <Menu ref="grpMobileMenuRef" :model="grpMobileMenuItems" :popup="true" />
            </div>
        </div>
    </section>

    <!-- Dialog busca mobile -->
    <Dialog v-model:visible="grpSearchDlgOpen" modal :draggable="false" pt:mask:class="backdrop-blur-xs" header="Buscar grupo" class="w-[94vw] max-w-sm">
        <div class="pt-1">
            <InputGroup>
                <InputGroupAddon><i class="pi pi-search" /></InputGroupAddon>
                <InputText v-model="filters.global.value" placeholder="Nome do grupo..." autofocus />
                <Button v-if="filters.global.value" icon="pi pi-times" severity="secondary" @click="filters.global.value = null" />
            </InputGroup>
        </div>
        <template #footer>
            <Button label="Fechar" severity="secondary" outlined class="rounded-full" @click="grpSearchDlgOpen = false" />
        </template>
    </Dialog>

    <!-- ══════════════════════════════════════════════════════
       QUICK-STATS
  ═══════════════════════════════════════════════════════ -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-2 px-3 md:px-4 mb-3">
        <template v-if="loading">
            <Skeleton v-for="n in 4" :key="n" height="3.5rem" class="rounded-md" />
        </template>
        <template v-else>
            <div
                v-for="s in quickStats"
                :key="s.label"
                class="flex flex-col gap-0.5 px-4 py-2.5 rounded-md border flex-1 min-w-[80px] transition-colors duration-150"
                :class="{
                    'border-green-500/25 bg-green-500/5': s.cls === 'qs-ok',
                    'border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)]': !s.cls
                }"
            >
                <div
                    class="text-[1.35rem] font-bold leading-none"
                    :class="{
                        'text-green-500': s.cls === 'qs-ok',
                        'text-[var(--text-color)]': !s.cls
                    }"
                >
                    {{ s.value }}
                </div>
                <div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">{{ s.label }}</div>
            </div>
        </template>
    </div>

    <!-- ══════════════════════════════════════════════════════
       CONTEÚDO: tabela (esq.) + painel lateral (dir.)
  ═══════════════════════════════════════════════════════ -->
    <div class="flex flex-col lg:flex-row gap-3 px-3 md:px-4 pb-5">
        <!-- ── TABELA ──────────────────────────────────────── -->
        <div class="w-full lg:flex-1 min-w-0">
            <div class="rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] overflow-hidden">
                <!-- Cabeçalho da seção -->
                <div class="flex items-center justify-between px-4 py-3 border-b border-[var(--surface-border,#e2e8f0)]">
                    <div class="flex items-center gap-2">
                        <i class="pi pi-table text-[var(--text-color-secondary)] opacity-60" />
                        <span class="font-semibold text-[1rem]">Lista de grupos</span>
                    </div>
                    <span class="inline-flex items-center justify-center min-w-[22px] h-[22px] px-1.5 rounded-full bg-[var(--primary-color,#6366f1)] text-white text-[1rem] font-bold">
                        {{ groups.length }}
                    </span>
                </div>

                <DataTable
                    ref="dt"
                    v-model:selection="selectedGroups"
                    :value="groups"
                    dataKey="id"
                    :loading="loading"
                    paginator
                    :rows="10"
                    :rowsPerPageOptions="[5, 10, 25]"
                    stripedRows
                    responsiveLayout="scroll"
                    :filters="filters"
                    filterDisplay="menu"
                    paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                    currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} grupos"
                    class="grp-datatable"
                    :rowClass="(r) => (isRecent(r) ? 'row-new-highlight' : '')"
                >
                    <!-- Seleção -->
                    <Column selectionMode="multiple" style="width: 3rem" :exportable="false">
                        <template #body="{ data }">
                            <Checkbox :binary="true" :disabled="!!data.is_system" :modelValue="isSelected(data)" @update:modelValue="toggleRowSelection(data, $event)" />
                        </template>
                    </Column>

                    <Column field="nome" header="Nome" sortable style="min-width: 16rem">
                        <template #body="{ data }">
                            <div class="flex items-center gap-2">
                                <span class="w-[3px] h-5 rounded-sm shrink-0" :style="effectiveCor(data) ? colorStyle(effectiveCor(data)) : { background: 'var(--surface-border)' }" />
                                <span class="font-medium">{{ data.nome }}</span>
                            </div>
                        </template>
                    </Column>

                    <Column header="Origem" sortable sortField="is_system" style="min-width: 10rem">
                        <template #body="{ data }">
                            <Tag :value="data.is_system ? 'Padrão' : 'Criado por você'" :severity="data.is_system ? 'info' : 'success'" />
                        </template>
                    </Column>

                    <Column header="Pacientes" sortable sortField="patients_count" style="min-width: 9rem">
                        <template #body="{ data }">
                            <div class="flex items-center gap-1.5">
                                <span class="font-semibold text-[var(--text-color)]">
                                    {{ Number(data.patients_count ?? data.patient_count ?? 0) }}
                                </span>
                                <span class="text-[var(--text-color-secondary)] opacity-60 text-[0.73rem]">paciente(s)</span>
                            </div>
                        </template>
                    </Column>

                    <Column :exportable="false" header="Ações" style="width: 10rem">
                        <template #body="{ data }">
                            <div class="flex gap-1.5 justify-end">
                                <Button v-if="!data.is_system" icon="pi pi-pencil" severity="secondary" outlined rounded size="small" v-tooltip.top="'Editar'" @click="openEdit(data)" />
                                <Button v-if="!data.is_system" icon="pi pi-trash" severity="danger" outlined rounded size="small" v-tooltip.top="'Excluir'" @click="confirmDeleteOne(data)" />
                                <Button v-if="data.is_system" icon="pi pi-palette" severity="secondary" outlined rounded size="small" v-tooltip.top="'Editar cor'" @click="openEditColor(data)" />
                            </div>
                        </template>
                    </Column>

                    <template #empty>
                        <div class="py-10 text-center">
                            <div class="mx-auto mb-3 grid h-12 w-12 place-items-center rounded-md bg-indigo-500/10 text-indigo-500">
                                <i class="pi pi-search text-xl" />
                            </div>
                            <div class="font-semibold text-[var(--text-color)]">Nenhum grupo encontrado</div>
                            <div class="mt-1 text-[1rem] text-[var(--text-color-secondary)]">Tente limpar o filtro ou crie um novo grupo.</div>
                            <div class="mt-4 flex justify-center gap-2">
                                <Button severity="secondary" outlined icon="pi pi-filter-slash" label="Limpar filtro" @click="filters.global.value = null" />
                                <Button icon="pi pi-plus" label="Criar grupo" @click="openCreate" />
                            </div>
                        </div>
                    </template>
                </DataTable>
            </div>
            <LoadedPhraseBlock v-if="hasLoaded" class="mt-3" />
        </div>

        <!-- ── PAINEL LATERAL: grupos com pacientes ─────────── -->
        <div class="w-full lg:w-[272px] lg:shrink-0">
            <div class="rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] overflow-hidden">
                <!-- Header do painel -->
                <div class="flex items-center gap-2.5 px-3.5 pt-3 pb-2.5 border-b border-[var(--surface-border,#f1f5f9)]">
                    <div class="w-8 h-8 rounded-md flex items-center justify-center shrink-0 bg-indigo-500/10 text-indigo-500">
                        <i class="pi pi-users text-[0.9rem]" />
                    </div>
                    <div class="flex-1 min-w-0">
                        <span class="block text-[1rem] font-bold text-[var(--text-color)]">Pacientes por grupo</span>
                        <span class="block text-[0.72rem] text-[var(--text-color-secondary)]">Grupos com associações ativas</span>
                    </div>
                    <span v-if="cards.length" class="inline-flex items-center justify-center min-w-[20px] h-5 px-1 rounded-full bg-[var(--primary-color,#6366f1)] text-white text-[0.65rem] font-bold shrink-0">{{ cards.length }}</span>
                </div>

                <!-- Skeleton -->
                <div v-if="loading" class="flex flex-col gap-2 p-3">
                    <Skeleton v-for="n in 4" :key="n" height="2.75rem" class="rounded-md" />
                </div>

                <!-- Empty -->
                <div v-else-if="cards.length === 0" class="flex flex-col items-center justify-center gap-2 px-4 py-8 text-center text-[var(--text-color-secondary)]">
                    <i class="pi pi-users text-2xl opacity-20" />
                    <div class="font-semibold text-[0.8rem]">Nenhuma associação</div>
                    <div class="text-[0.72rem] opacity-70 leading-relaxed">Quando um grupo tiver pacientes vinculados, ele aparecerá aqui.</div>
                </div>

                <!-- Lista de grupos com pacientes -->
                <div v-else class="flex flex-col max-h-[480px] overflow-y-auto divide-y divide-[var(--surface-border,#f1f5f9)]">
                    <button
                        v-for="g in cards"
                        :key="g.id"
                        class="flex items-center gap-2.5 px-3.5 py-2.5 text-left w-full bg-transparent border-none hover:bg-[var(--surface-ground,#f8fafc)] transition-colors duration-100 cursor-pointer group"
                        @click="openGroupPatientsModal(g)"
                    >
                        <!-- Dot cor -->
                        <div class="w-2.5 h-2.5 rounded-full shrink-0" :style="effectiveCor(g) ? colorStyle(effectiveCor(g)) : { background: 'var(--surface-border)' }" />
                        <div class="flex-1 min-w-0">
                            <div class="font-semibold text-[0.8rem] truncate text-[var(--text-color)]">{{ g.nome }}</div>
                            <div class="text-[1rem] text-[var(--text-color-secondary)]">
                                {{ patientsLabel(Number(g.patients_count ?? g.patient_count ?? 0)) }}
                            </div>
                        </div>
                        <!-- Badge contagem -->
                        <span class="inline-flex items-center justify-center min-w-[22px] h-[22px] px-1 rounded-full font-bold text-[0.68rem] shrink-0" :class="g.is_system ? 'bg-sky-500/10 text-sky-600' : 'bg-indigo-500/10 text-indigo-600'">{{
                            Number(g.patients_count ?? g.patient_count ?? 0)
                        }}</span>
                        <i class="pi pi-chevron-right text-[0.6rem] text-[var(--text-color-secondary)] opacity-30 group-hover:opacity-100 group-hover:text-[var(--primary-color,#6366f1)] transition-all duration-150 shrink-0" />
                    </button>
                </div>

                <!-- Footer hint -->
                <div v-if="cards.length" class="px-3.5 py-2 text-[1rem] text-[var(--text-color-secondary)] opacity-50 border-t border-[var(--surface-border,#f1f5f9)] text-center">Clique para ver os pacientes do grupo</div>
            </div>
        </div>
    </div>

    <!-- ══════════════════════════════════════════════════════
       Dialog: Criar / Editar grupo
  ═══════════════════════════════════════════════════════ -->
    <Dialog
        v-model:visible="dlg.open"
        modal
        :draggable="false"
        :closable="!dlg.saving"
        :dismissableMask="!dlg.saving"
        class="w-[96vw] max-w-lg"
        :pt="{ content: { class: 'p-0' }, header: { class: 'pb-0' }, footer: { class: 'pt-0' } }"
        pt:mask:class="backdrop-blur-xs"
    >
        <template #header>
            <div class="flex w-full items-center gap-3 px-1">
                <span class="shrink-0 w-3.5 h-3.5 rounded-full border-2 border-white/30 shadow-[0_0_0_3px_rgba(0,0,0,0.08)] transition-colors duration-200" :style="{ backgroundColor: dlgPreviewColor }" />
                <div class="min-w-0">
                    <div class="text-[0.95rem] font-semibold truncate text-[var(--text-color)]">
                        {{ dlg.nome || (dlg.mode === 'create' ? 'Novo grupo' : 'Editar grupo') }}
                    </div>
                    <div class="text-[0.72rem] text-[var(--text-color-secondary)] opacity-70">
                        {{ dlg.isSystem ? 'Grupo padrão — edição de cor' : dlg.mode === 'create' ? 'Criar tipo de grupo' : 'Editar tipo de grupo' }}
                    </div>
                </div>
            </div>
        </template>

        <!-- Banner preview -->
        <div class="h-16 flex items-center justify-center rounded-md mb-4 transition-colors duration-[250ms]" :style="{ backgroundColor: dlgPreviewColor }">
            <span class="text-[0.9rem] font-bold tracking-tight px-4 py-1.5 bg-black/15 rounded-full backdrop-blur-sm text-white">
                {{ dlg.nome || 'Nome do grupo' }}
            </span>
        </div>

        <!-- Corpo -->
        <div class="flex flex-col gap-4">
            <FloatLabel variant="on">
                <IconField>
                    <InputIcon><i class="pi pi-sitemap" /></InputIcon>
                    <InputText id="grp-nome" v-model="dlg.nome" class="w-full" variant="filled" :disabled="dlg.saving || dlg.isSystem" @keydown.enter.prevent="saveDialog" />
                </IconField>
                <label for="grp-nome">{{ dlg.isSystem ? 'Nome do grupo (padrão)' : 'Nome do grupo *' }}</label>
            </FloatLabel>
            <div v-if="dlg.isSystem" class="flex items-center gap-1.5 text-[0.72rem] text-[var(--text-color-secondary)] opacity-60 -mt-1">
                <i class="pi pi-info-circle text-[0.65rem]" />
                <span>Grupos padrão do sistema — apenas a cor pode ser alterada</span>
            </div>

            <!-- Seletor de cor -->
            <div class="border border-[var(--surface-border,#e2e8f0)] rounded-md bg-[var(--surface-ground,#f8fafc)] p-3.5">
                <div class="text-[0.68rem] font-bold uppercase tracking-[0.07em] text-[var(--text-color-secondary)] opacity-60 mb-2.5">Cor do grupo</div>
                <div class="flex flex-wrap gap-[0.4rem]">
                    <button
                        v-for="p in dlgPresetColors"
                        :key="p.bg"
                        class="w-7 h-7 rounded-full grid place-items-center cursor-pointer relative border-0 transition-transform duration-[120ms] hover:scale-110 hover:shadow-[0_3px_10px_rgba(0,0,0,0.2)] disabled:cursor-not-allowed"
                        :class="dlg.cor === p.bg ? 'scale-110 shadow-[0_0_0_2px_var(--text-color),0_0_0_4px_var(--surface-card,#fff)]' : ''"
                        :style="{ backgroundColor: `#${p.bg}` }"
                        :title="p.name"
                        :disabled="dlg.saving"
                        @click="dlg.cor = p.bg"
                    >
                        <i v-if="dlg.cor === p.bg" class="pi pi-check text-white font-black" style="font-size: 11px" />
                    </button>

                    <!-- Custom color picker -->
                    <div
                        class="w-7 h-7 rounded-full grid place-items-center cursor-pointer overflow-hidden relative transition-transform duration-[120ms] hover:scale-110 hover:shadow-[0_3px_10px_rgba(0,0,0,0.2)]"
                        :class="isCustomColor ? 'scale-110 shadow-[0_0_0_2px_var(--text-color),0_0_0_4px_var(--surface-card,#fff)]' : ''"
                        style="background: conic-gradient(red, yellow, lime, cyan, blue, magenta, red)"
                        title="Cor personalizada"
                    >
                        <i v-if="isCustomColor" class="pi pi-check text-white font-black absolute z-10 pointer-events-none drop-shadow-[0_1px_2px_rgba(0,0,0,0.6)]" style="font-size: 11px" />
                        <ColorPicker
                            v-model="dlg.cor"
                            format="hex"
                            :disabled="dlg.saving"
                            class="absolute inset-0 [&_.p-colorpicker-preview]:w-full [&_.p-colorpicker-preview]:h-full [&_.p-colorpicker-preview]:border-0 [&_.p-colorpicker-preview]:rounded-full [&_.p-colorpicker-preview]:opacity-0"
                        />
                    </div>

                    <!-- Limpar cor -->
                    <button
                        v-if="dlg.cor"
                        class="w-7 h-7 rounded-full grid place-items-center cursor-pointer border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] text-[var(--text-color-secondary)] transition-transform duration-[120ms] hover:scale-110 disabled:cursor-not-allowed"
                        title="Sem cor"
                        :disabled="dlg.saving"
                        @click="dlg.cor = ''"
                    >
                        <i class="pi pi-times" style="font-size: 11px" />
                    </button>
                </div>
            </div>
        </div>

        <template #footer>
            <div class="flex items-center justify-end gap-2 pt-2">
                <Button label="Cancelar" severity="secondary" outlined class="rounded-full" :disabled="dlg.saving" @click="dlg.open = false" />
                <Button :label="dlg.isSystem ? 'Salvar cor' : 'Salvar'" icon="pi pi-check" class="rounded-full" :loading="dlg.saving" :disabled="!dlg.isSystem && !String(dlg.nome || '').trim()" @click="saveDialog" />
            </div>
        </template>
    </Dialog>

    <!-- ══════════════════════════════════════════════════════
       Dialog: Pacientes do grupo
  ═══════════════════════════════════════════════════════ -->
    <Dialog
        v-model:visible="patientsDialog.open"
        modal
        :draggable="false"
        :style="{ width: '860px', maxWidth: '95vw' }"
        :pt="{
            root: { style: `border: 4px solid ${patientsGroupHex}` },
            header: { style: `border-bottom: 1px solid ${patientsGroupHex}30` }
        }"
        pt:mask:class="backdrop-blur-xs"
    >
        <template #header>
            <div class="flex items-center gap-3">
                <div class="w-9 h-9 rounded-lg flex items-center justify-center text-white font-bold text-base shrink-0" :style="{ background: patientsGroupHex }">
                    {{ (patientsDialog.group?.nome || '?')[0].toUpperCase() }}
                </div>
                <div>
                    <div class="text-[1rem] font-bold" :style="{ color: patientsGroupHex }">Grupo — {{ patientsDialog.group?.nome }}</div>
                    <div class="text-[0.72rem] text-[var(--text-color-secondary)]">{{ patientsDialog.items.length }} paciente{{ patientsDialog.items.length !== 1 ? 's' : '' }}</div>
                </div>
            </div>
        </template>

        <div class="flex flex-col gap-3">
            <!-- Busca + contador -->
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
                <IconField class="w-full sm:w-72">
                    <InputIcon><i class="pi pi-search" /></InputIcon>
                    <InputText v-model="patientsDialog.search" placeholder="Buscar paciente..." class="w-full" :disabled="patientsDialog.loading" />
                </IconField>
                <span v-if="!patientsDialog.loading" class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold" :style="{ background: `${patientsGroupHex}18`, color: patientsGroupHex }"
                    >{{ patientsDialog.items.length }} paciente(s)</span
                >
            </div>

            <!-- Loading -->
            <div v-if="patientsDialog.loading" class="flex items-center gap-2 py-4" :style="{ color: patientsGroupHex }"><i class="pi pi-spin pi-spinner" /> Carregando…</div>

            <Message v-else-if="patientsDialog.error" severity="error">{{ patientsDialog.error }}</Message>

            <div v-else>
                <!-- Empty -->
                <div v-if="patientsDialog.items.length === 0" class="py-10 text-center">
                    <div class="mx-auto mb-3 grid h-12 w-12 place-items-center rounded-md" :style="{ background: `${patientsGroupHex}18`, color: patientsGroupHex }">
                        <i class="pi pi-users text-xl" />
                    </div>
                    <div class="font-semibold">Nenhum paciente neste grupo</div>
                    <div class="mt-1 text-[1rem] text-[var(--text-color-secondary)]">Associe pacientes a este grupo na página de pacientes.</div>
                </div>

                <!-- Tabela -->
                <DataTable v-else :value="patientsDialogFiltered" dataKey="id" stripedRows responsiveLayout="scroll" paginator :rows="8" :rowsPerPageOptions="[8, 15, 30]">
                    <Column header="Paciente" sortable>
                        <template #body="{ data }">
                            <div class="flex items-center gap-3">
                                <Avatar v-if="data.avatar_url" :image="data.avatar_url" shape="circle" />
                                <Avatar v-else :label="initials(data.full_name)" shape="circle" :style="{ background: `${patientsGroupHex}25`, color: patientsGroupHex }" />
                                <div class="min-w-0">
                                    <div class="font-medium truncate">{{ data.full_name }}</div>
                                    <div class="text-[0.75rem] text-[var(--text-color-secondary)]">{{ data.email || '—' }}</div>
                                </div>
                            </div>
                        </template>
                    </Column>

                    <Column header="Telefone" style="min-width: 11rem">
                        <template #body="{ data }">
                            <span class="text-[var(--text-color-secondary)]">{{ fmtPhone(data.phone) }}</span>
                        </template>
                    </Column>

                    <Column header="Ação" style="width: 9rem">
                        <template #body="{ data }">
                            <Button label="Abrir" icon="pi pi-external-link" size="small" outlined :style="{ borderColor: patientsGroupHex, color: patientsGroupHex }" @click="abrirPaciente(data)" />
                        </template>
                    </Column>

                    <template #empty>
                        <div class="py-8 text-center">
                            <i class="pi pi-search text-2xl opacity-20 mb-2 block" />
                            <div class="font-semibold text-[1rem]">Nenhum resultado</div>
                            <div class="text-[0.75rem] opacity-60 mt-1">Nenhum paciente corresponde à busca.</div>
                            <Button class="mt-3" severity="secondary" outlined icon="pi pi-filter-slash" label="Limpar" size="small" @click="patientsDialog.search = ''" />
                        </div>
                    </template>
                </DataTable>
            </div>
        </div>

        <template #footer>
            <Button label="Fechar" icon="pi pi-times" outlined class="rounded-full" :style="{ borderColor: patientsGroupHex, color: patientsGroupHex }" @click="patientsDialog.open = false" />
        </template>
    </Dialog>

    <ConfirmDialog />
</template>
