<script setup>
/*
 * MelissaMedicos — Médicos & encaminhadores (CRUD + lista de pacientes
 * encaminhados). Segue blueprint melissa-table-page-blueprint.md.
 *
 * Tabela: medicos (filtro por owner_id + ativo=true). Vínculo com paciente
 * é "implícito" via patients.encaminhado_por (ILIKE %nome%) — não há
 * join table dedicada. Por isso a contagem é feita comparando strings.
 *
 * Row design preservado: avatar circular com iniciais + Dr(a). nome +
 * chip especialidade + meta inline (CRM, phone, email, clínica). Coluna
 * "Ações" frozen 100px com pencil + trash (soft delete: ativo=false).
 *
 * Click na coluna "Pacientes" abre dialog listando pacientes encaminhados
 * (espelha MelissaGrupos / MelissaTags).
 */
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import {
    listMedicosWithPatientCounts,
    createMedico,
    updateMedico,
    deleteMedico,
    fetchPatientsByMedicoNome
} from '@/services/Medicos.service.js';
import PatientCadastroDialog from '@/components/ui/PatientCadastroDialog.vue';
// DataTable/Column/Paginator/Dialog/InputText/Select/Textarea/Button: auto via PrimeVueResolver

const emit = defineEmits(['close']);
const toast = useToast();
const confirm = useConfirm();

// ── Breakpoints + drawer ──────────────────────────────────
const drawerOpen = ref(false);
const isMobile = ref(false);
let _mqMobile = null;
function _onMqMobileChange(e) {
    isMobile.value = e.matches;
    if (!e.matches) drawerOpen.value = false;
}
function toggleDrawer() { drawerOpen.value = !drawerOpen.value; }
function fecharDrawer() { drawerOpen.value = false; }

// ── Estado ─────────────────────────────────────────────────
const loading = ref(false);
const saving = ref(false);
const medicos = ref([]);

const busca = ref('');
const especFilter = ref('');   // string vazia = todas; senão = especialidade exata
const usoFilter = ref('');     // '' | 'com_pacs' | 'sem_pacs'

// ── Especialidades ─────────────────────────────────────────
const ESPECIALIDADES = [
    'Psiquiatria',
    'Neurologia',
    'Neuropsiquiatria infantil',
    'Clínica geral',
    'Pediatria',
    'Geriatria',
    'Endocrinologia',
    'Psicologia (encaminhador)',
    'Assistência social',
    'Fonoaudiologia',
    'Terapia ocupacional',
    'Fisioterapia',
    'Outra'
];

const USO_FILTER_OPTIONS = [
    { key: 'com_pacs', label: 'Com pacientes', icon: 'pi pi-users' },
    { key: 'sem_pacs', label: 'Sem pacientes', icon: 'pi pi-circle' }
];

// Lista de especialidades disponíveis no Select (somente as que aparecem
// nos médicos cadastrados; evita opções vazias). Inclui "Todas".
const especOptions = computed(() => {
    const set = new Set();
    for (const m of medicos.value) {
        if (m.especialidade) set.add(m.especialidade);
    }
    return Array.from(set).sort((a, b) => a.localeCompare(b, 'pt-BR'));
});

function toggleUsoFilter(u) {
    usoFilter.value = usoFilter.value === u ? '' : u;
}

const hasActiveFilters = computed(() =>
    !!(busca.value || especFilter.value || usoFilter.value)
);
function clearAllFilters() {
    busca.value = '';
    especFilter.value = '';
    usoFilter.value = '';
}

// ── Helpers ───────────────────────────────────────────────
function digitsOnly(v) { return String(v ?? '').replace(/\D/g, ''); }
function fmtPhone(v) {
    const d = digitsOnly(v);
    if (!d) return '';
    if (d.length === 11) return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7, 11)}`;
    if (d.length === 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6, 10)}`;
    return d;
}
function iniciais(nome) {
    if (!nome) return '?';
    const partes = String(nome).trim().split(/\s+/);
    if (partes.length === 1) return partes[0][0]?.toUpperCase() || '?';
    return (partes[0][0] + partes[partes.length - 1][0]).toUpperCase();
}

// ── Helpers de status (rowClass) ──────────────────────────
function rowStatusClass(m) {
    if (!m) return '';
    return Number(m.patients_count || 0) > 0 ? 'is-com-pacs' : 'is-sem-pacs';
}

// ── Stats ─────────────────────────────────────────────────
const stats = computed(() => {
    const all = medicos.value;
    const especs = new Set(all.map((m) => m.especialidade).filter(Boolean)).size;
    const comPacs = all.filter((m) => Number(m.patients_count || 0) > 0).length;
    const totalPacs = all.reduce((s, m) => s + Number(m.patients_count || 0), 0);
    return [
        { key: 'total', label: 'Médicos', value: all.length, cls: 'neutral' },
        { key: 'esp', label: 'Especialidades', value: especs, cls: especs > 0 ? 'info' : 'neutral' },
        { key: 'com', label: 'Com pacientes', value: comPacs, cls: comPacs > 0 ? 'ok' : 'neutral' },
        { key: 'enc', label: 'Encaminhados', value: totalPacs, cls: totalPacs > 0 ? 'accent' : 'neutral' }
    ];
});

// ── Filtragem ─────────────────────────────────────────────
const filtered = computed(() => {
    let list = medicos.value;
    if (especFilter.value) {
        list = list.filter((m) => m.especialidade === especFilter.value);
    }
    if (usoFilter.value === 'com_pacs') {
        list = list.filter((m) => Number(m.patients_count || 0) > 0);
    }
    if (usoFilter.value === 'sem_pacs') {
        list = list.filter((m) => Number(m.patients_count || 0) === 0);
    }
    const q = String(busca.value || '').trim().toLowerCase();
    if (q) {
        list = list.filter((m) =>
            String(m.nome || '').toLowerCase().includes(q) ||
            String(m.especialidade || '').toLowerCase().includes(q) ||
            String(m.crm || '').toLowerCase().includes(q) ||
            String(m.clinica || '').toLowerCase().includes(q)
        );
    }
    return list;
});

// ── Paginação compartilhada (DataTable + grid) ────────────
const PAGE_SIZE_OPTIONS = [10, 20, 50, 100];
const rowsMM = ref(10);
const firstMM = ref(0);
function onPage(event) {
    firstMM.value = event.first;
    rowsMM.value = event.rows;
}
watch([busca, especFilter, usoFilter], () => { firstMM.value = 0; });

const pagedItems = computed(() =>
    filtered.value.slice(firstMM.value, firstMM.value + rowsMM.value)
);

// ── View mode (list / grid) ───────────────────────────────
const VIEW_MODE_KEY = 'mm.viewMode.v1';
const viewMode = ref('list');
try {
    const saved = localStorage.getItem(VIEW_MODE_KEY);
    if (saved === 'list' || saved === 'grid') viewMode.value = saved;
} catch (_) { /* localStorage indisponível — mantém default */ }
function setViewMode(m) {
    if (m !== 'list' && m !== 'grid') return;
    viewMode.value = m;
    try { localStorage.setItem(VIEW_MODE_KEY, m); } catch (_) { /* noop */ }
}

// ── Fetch ─────────────────────────────────────────────────
async function fetchAll() {
    loading.value = true;
    try {
        const data = await listMedicosWithPatientCounts();
        medicos.value = data || [];
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao carregar', detail: e?.message, life: 4500 });
    } finally {
        loading.value = false;
    }
}

onMounted(async () => {
    if (typeof window !== 'undefined' && window.matchMedia) {
        _mqMobile = window.matchMedia('(max-width: 1023px)');
        isMobile.value = _mqMobile.matches;
        _mqMobile.addEventListener('change', _onMqMobileChange);
    }
    await fetchAll();
});
onBeforeUnmount(() => {
    if (_mqMobile) _mqMobile.removeEventListener('change', _onMqMobileChange);
});

// ── CRUD ──────────────────────────────────────────────────
const dlgOpen = ref(false);
const dlgMode = ref('create');
const dlgError = ref('');
const dlgForm = ref({
    id: '',
    nome: '',
    crm: '',
    especialidade: '',
    especialidade_outra: '',
    telefone_profissional: '',
    telefone_pessoal: '',
    email: '',
    clinica: '',
    cidade: '',
    estado: 'SP',
    observacoes: ''
});

const especialidadeFinal = computed(() => {
    if (dlgForm.value.especialidade === 'Outra') return dlgForm.value.especialidade_outra.trim();
    return dlgForm.value.especialidade;
});

function abrirCriar() {
    dlgMode.value = 'create';
    dlgForm.value = {
        id: '', nome: '', crm: '', especialidade: '', especialidade_outra: '',
        telefone_profissional: '', telefone_pessoal: '', email: '',
        clinica: '', cidade: '', estado: 'SP', observacoes: ''
    };
    dlgError.value = '';
    dlgOpen.value = true;
}
function abrirEditar(row) {
    dlgMode.value = 'edit';
    const isOutraEsp = row.especialidade && !ESPECIALIDADES.includes(row.especialidade);
    dlgForm.value = {
        id: row.id,
        nome: row.nome || '',
        crm: row.crm || '',
        especialidade: isOutraEsp ? 'Outra' : (row.especialidade || ''),
        especialidade_outra: isOutraEsp ? row.especialidade : '',
        telefone_profissional: fmtPhone(row.telefone_profissional),
        telefone_pessoal: fmtPhone(row.telefone_pessoal),
        email: row.email || '',
        clinica: row.clinica || '',
        cidade: row.cidade || '',
        estado: row.estado || 'SP',
        observacoes: row.observacoes || ''
    };
    dlgError.value = '';
    dlgOpen.value = true;
}
function onRowClick(event) {
    if (event?.data) abrirEditar(event.data);
}

async function salvar() {
    const nome = String(dlgForm.value.nome || '').trim();
    if (!nome) {
        dlgError.value = 'Informe o nome do médico.';
        return;
    }
    if (dlgForm.value.especialidade === 'Outra' && !dlgForm.value.especialidade_outra.trim()) {
        dlgError.value = 'Informe a especialidade.';
        return;
    }
    saving.value = true;
    dlgError.value = '';

    const payload = {
        nome,
        crm: dlgForm.value.crm.trim() || null,
        especialidade: especialidadeFinal.value || null,
        telefone_profissional: dlgForm.value.telefone_profissional ? digitsOnly(dlgForm.value.telefone_profissional) : null,
        telefone_pessoal: dlgForm.value.telefone_pessoal ? digitsOnly(dlgForm.value.telefone_pessoal) : null,
        email: dlgForm.value.email.trim() || null,
        clinica: dlgForm.value.clinica.trim() || null,
        cidade: dlgForm.value.cidade.trim() || null,
        estado: dlgForm.value.estado.trim() || null,
        observacoes: dlgForm.value.observacoes.trim() || null
    };

    try {
        if (dlgMode.value === 'create') {
            await createMedico(payload);
            toast.add({ severity: 'success', summary: 'Médico cadastrado', life: 2200 });
        } else {
            await updateMedico(dlgForm.value.id, payload);
            toast.add({ severity: 'success', summary: 'Médico atualizado', life: 2200 });
        }
        dlgOpen.value = false;
        await fetchAll();
    } catch (e) {
        dlgError.value = e?.message || 'Falha ao salvar.';
    } finally {
        saving.value = false;
    }
}

function confirmarExcluir(row) {
    confirm.require({
        message: `Desativar "Dr(a). ${row.nome}"? O registro será ocultado da listagem.`,
        header: 'Desativar médico',
        icon: 'pi pi-exclamation-triangle',
        acceptLabel: 'Desativar',
        rejectLabel: 'Cancelar',
        acceptSeverity: 'danger',
        accept: () => excluir(row)
    });
}
async function excluir(row) {
    saving.value = true;
    try {
        await deleteMedico(row.id);
        toast.add({ severity: 'success', summary: 'Médico desativado', life: 2200 });
        await fetchAll();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao desativar.', life: 4000 });
    } finally {
        saving.value = false;
    }
}

// ── Dialog: Pacientes encaminhados pelo médico ─────────────────
// Mesmo pattern de MelissaGrupos/MelissaTags. A listagem vem do service
// (fetchPatientsByMedicoNome) que faz ILIKE em patients.encaminhado_por.
const patientsDialog = reactive({
    open: false,
    loading: false,
    error: '',
    medico: null,
    items: [],
    search: ''
});

const patientsDialogFiltered = computed(() => {
    const s = String(patientsDialog.search || '').toLowerCase().trim();
    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)
    );
});

async function openMedicoPatientsModal(medicoRow) {
    if (!medicoRow) return;
    patientsDialog.open = true;
    patientsDialog.loading = true;
    patientsDialog.error = '';
    patientsDialog.medico = medicoRow;
    patientsDialog.items = [];
    patientsDialog.search = '';
    try {
        const data = await fetchPatientsByMedicoNome(medicoRow.nome);
        patientsDialog.items = data || [];
    } catch (e) {
        patientsDialog.error = e?.message || 'Erro ao carregar pacientes encaminhados.';
    } 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;
});
</script>

<template>
    <aside
        class="mm-mobile-drawer"
        :class="{ 'is-open': drawerOpen }"
        v-show="isMobile"
        aria-label="Estatísticas e filtros"
    >
        <div id="mm-mobile-drawer-target" class="mm-mobile-drawer__scroll" />
    </aside>
    <Transition name="mm-drawer-fade">
        <div
            v-if="isMobile && drawerOpen"
            class="mm-mobile-drawer__backdrop"
            @click="fecharDrawer"
        />
    </Transition>

    <section class="mm-page">
        <header class="mm-page__head">
            <button
                class="mm-menu-btn mm-menu-btn--mobile-only"
                v-tooltip.bottom="'Estatísticas & filtros'"
                @click="toggleDrawer"
            >
                <i class="pi pi-bars" />
                <span>Menu Médicos</span>
            </button>
            <div class="mm-page__title">
                <i class="pi pi-user-edit mm-page__title-icon" />
                <span>Médicos & referências</span>
                <span class="mm-page__count">{{ filtered.length }}</span>
            </div>
            <div class="mm-page__actions">
                <button
                    class="mm-act-btn mm-act-btn--primary"
                    v-tooltip.bottom="'Novo médico'"
                    :disabled="loading"
                    @click="abrirCriar"
                >
                    <i :class="saving ? 'pi pi-spin pi-spinner' : 'pi pi-plus'" />
                    <span>Novo</span>
                </button>
                <button
                    class="mm-head-btn"
                    v-tooltip.bottom="'Recarregar'"
                    :disabled="loading"
                    @click="fetchAll"
                >
                    <i :class="loading ? 'pi pi-spin pi-spinner' : 'pi pi-refresh'" />
                </button>
                <button class="mm-close" v-tooltip.bottom="'Voltar (Esc)'" @click="emit('close')">
                    <i class="pi pi-times" />
                </button>
            </div>
        </header>

        <!-- Subheader explicativo (blueprint §9) -->
        <div class="mm-subheader">
            <i class="pi pi-info-circle mm-subheader__icon" />
            <span class="mm-subheader__text">
                Médicos e profissionais de referência que <strong>encaminham pacientes</strong>
                pra clínica. Cadastre pra registrar a origem do paciente — a contagem é feita
                automaticamente pelo campo <strong>"encaminhado por"</strong> do prontuário.
            </span>
        </div>

        <div class="mm-body">
            <Teleport to="#mm-mobile-drawer-target" :disabled="!isMobile">
            <aside class="mm-side">
                <div class="mm-side__scroll">
                    <!-- Stats -->
                    <div class="mm-w mm-w--side">
                        <div class="mm-w__head">
                            <span class="mm-w__title"><i class="pi pi-chart-bar" /> Estatísticas</span>
                        </div>
                        <div class="mm-stats">
                            <div
                                v-for="s in stats"
                                :key="s.key"
                                class="mm-stat"
                                :class="`is-${s.cls}`"
                            >
                                <div class="mm-stat__val">{{ s.value }}</div>
                                <div class="mm-stat__lbl">{{ s.label }}</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filtro de especialidade (Select PrimeVue — muitas opções
                         pra usar button list).  -->
                    <div class="mm-w mm-w--side">
                        <div class="mm-w__head">
                            <span class="mm-w__title"><i class="pi pi-bookmark" /> Especialidade</span>
                            <button
                                v-if="especFilter"
                                class="mm-side__clear-inline"
                                v-tooltip.top="'Limpar filtro de especialidade'"
                                aria-label="Limpar filtro de especialidade"
                                @click="especFilter = ''"
                            >
                                <i class="pi pi-times" />
                            </button>
                        </div>
                        <Select
                            v-model="especFilter"
                            :options="especOptions"
                            placeholder="Todas as especialidades"
                            class="w-full mm-side__select"
                            :disabled="especOptions.length === 0"
                            showClear
                        />
                    </div>

                    <!-- Filtro de uso -->
                    <div class="mm-w mm-w--side">
                        <div class="mm-w__head">
                            <span class="mm-w__title"><i class="pi pi-users" /> Uso</span>
                            <button
                                v-if="usoFilter"
                                class="mm-side__clear-inline"
                                v-tooltip.top="'Limpar filtro de uso'"
                                aria-label="Limpar filtro de uso"
                                @click="usoFilter = ''"
                            >
                                <i class="pi pi-times" />
                            </button>
                        </div>
                        <div class="mm-side__list">
                            <button
                                v-for="o in USO_FILTER_OPTIONS"
                                :key="o.key"
                                class="mm-side__item"
                                :class="[`is-uso-${o.key}`, { 'is-active': usoFilter === o.key }]"
                                @click="toggleUsoFilter(o.key)"
                            >
                                <i :class="o.icon" />
                                <span>{{ o.label }}</span>
                            </button>
                        </div>
                    </div>
                </div>

                <Transition name="mm-clear">
                    <div v-if="hasActiveFilters" class="mm-side__footer">
                        <button class="mm-side__clear-all" @click="clearAllFilters">
                            <i class="pi pi-filter-slash" />
                            <span>Limpar filtros</span>
                        </button>
                    </div>
                </Transition>
            </aside>
            </Teleport>

            <div class="mm-main">
                <div class="mm-toolbar">
                    <div class="mm-search">
                        <i class="pi pi-search mm-search__icon" />
                        <input
                            v-model="busca"
                            type="text"
                            placeholder="Buscar por nome, especialidade, CRM, clínica…"
                            class="mm-search__input"
                        />
                        <button
                            v-if="busca"
                            class="mm-search__clear"
                            v-tooltip.bottom="'Limpar busca'"
                            @click="busca = ''"
                        >
                            <i class="pi pi-times" />
                        </button>
                    </div>
                    <div class="mm-view-toggle" role="group" aria-label="Visualização">
                        <button
                            class="mm-view-toggle__btn"
                            :class="{ 'is-active': viewMode === 'list' }"
                            v-tooltip.bottom="'Lista'"
                            aria-label="Lista"
                            @click="setViewMode('list')"
                        >
                            <i class="pi pi-list" />
                        </button>
                        <button
                            class="mm-view-toggle__btn"
                            :class="{ 'is-active': viewMode === 'grid' }"
                            v-tooltip.bottom="'Grade'"
                            aria-label="Grade"
                            @click="setViewMode('grid')"
                        >
                            <i class="pi pi-th-large" />
                        </button>
                    </div>
                </div>

                <DataTable
                    v-if="viewMode === 'list'"
                    :value="filtered"
                    :loading="loading"
                    dataKey="id"
                    paginator
                    :rows="rowsMM"
                    :first="firstMM"
                    :rowsPerPageOptions="PAGE_SIZE_OPTIONS"
                    paginatorTemplate="RowsPerPageDropdown FirstPageLink PrevPageLink CurrentPageReport NextPageLink LastPageLink"
                    currentPageReportTemplate="{first}–{last} de {totalRecords}"
                    :rowClass="rowStatusClass"
                    selectionMode="single"
                    scrollable
                    scrollHeight="flex"
                    tableStyle="min-width: 800px"
                    class="mm-table"
                    @row-click="onRowClick"
                    @page="onPage"
                >
                    <Column header="Médico" style="min-width: 280px">
                        <template #body="{ data }">
                            <div class="mm-row__med">
                                <span class="mm-row__avatar">{{ iniciais(data.nome) }}</span>
                                <div class="mm-row__main">
                                    <div class="mm-row__name-row">
                                        <span class="mm-row__name">Dr(a). {{ data.nome }}</span>
                                        <span v-if="data.especialidade" class="mm-row__esp">
                                            {{ data.especialidade }}
                                        </span>
                                    </div>
                                    <div v-if="data.clinica || data.cidade" class="mm-row__sub">
                                        <i v-if="data.clinica" class="pi pi-building" />
                                        <span v-if="data.clinica">{{ data.clinica }}</span>
                                        <span v-if="data.clinica && data.cidade" class="mm-row__sep">·</span>
                                        <span v-if="data.cidade">
                                            {{ data.cidade }}{{ data.estado ? '/' + data.estado : '' }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </Column>

                    <Column header="Contato" style="min-width: 220px">
                        <template #body="{ data }">
                            <div class="mm-row__contact">
                                <span v-if="data.crm">
                                    <i class="pi pi-id-card" /> CRM {{ data.crm }}
                                </span>
                                <span v-if="data.telefone_profissional">
                                    <i class="pi pi-phone" /> {{ fmtPhone(data.telefone_profissional) }}
                                </span>
                                <span v-if="data.email">
                                    <i class="pi pi-envelope" /> {{ data.email }}
                                </span>
                                <span v-if="!data.crm && !data.telefone_profissional && !data.email" class="mm-row__empty">—</span>
                            </div>
                        </template>
                    </Column>

                    <Column header="Pacientes" style="width: 180px; min-width: 160px">
                        <template #body="{ data }">
                            <button
                                type="button"
                                class="mm-row__count-btn"
                                :class="{ 'is-empty': !data.patients_count }"
                                :disabled="!data.patients_count"
                                v-tooltip.top="data.patients_count > 0 ? 'Ver pacientes encaminhados' : 'Nenhum paciente encaminhado'"
                                aria-label="Ver pacientes encaminhados"
                                @click.stop="openMedicoPatientsModal(data)"
                            >
                                <i class="pi pi-users" />
                                <span>
                                    {{ data.patients_count || 0 }}
                                    {{ (data.patients_count || 0) === 1 ? 'paciente' : 'pacientes' }}
                                </span>
                            </button>
                        </template>
                    </Column>

                    <Column
                        header=""
                        :style="{ width: '100px', maxWidth: '100px', minWidth: '100px' }"
                        frozen
                        alignFrozen="right"
                        class="mm-col-acoes"
                    >
                        <template #body="{ data }">
                            <div class="mm-row__actions" @click.stop>
                                <button
                                    class="mm-row__btn"
                                    v-tooltip.left="'Editar'"
                                    aria-label="Editar"
                                    @click.stop="abrirEditar(data)"
                                >
                                    <i class="pi pi-pencil" />
                                </button>
                                <button
                                    class="mm-row__btn mm-row__btn--danger"
                                    v-tooltip.left="'Desativar'"
                                    aria-label="Desativar"
                                    @click.stop="confirmarExcluir(data)"
                                >
                                    <i class="pi pi-trash" />
                                </button>
                            </div>
                        </template>
                    </Column>

                    <template #empty>
                        <div class="mm-empty">
                            <i class="pi pi-user-edit mm-empty__icon" />
                            <div class="mm-empty__title">Nenhum médico encontrado</div>
                            <div class="mm-empty__hint">
                                <template v-if="busca || especFilter || usoFilter">
                                    Ajuste os filtros pra ver mais resultados.
                                </template>
                                <template v-else>
                                    Cadastre médicos pra registrar encaminhamentos.
                                </template>
                            </div>
                            <button class="mm-act-btn mm-act-btn--primary mm-empty__btn" @click="abrirCriar">
                                <i class="pi pi-plus" />
                                <span>Novo médico</span>
                            </button>
                        </div>
                    </template>

                    <template #loading>
                        <div class="mm-table__loading">
                            <i class="pi pi-spin pi-spinner" />
                            <span>Carregando médicos…</span>
                        </div>
                    </template>
                </DataTable>

                <!-- View Grade -->
                <div v-else-if="viewMode === 'grid'" class="mm-grid-wrap">
                    <div v-if="loading && filtered.length === 0" class="mm-table__loading mm-grid__loading">
                        <i class="pi pi-spin pi-spinner" />
                        <span>Carregando médicos…</span>
                    </div>
                    <div v-else-if="filtered.length === 0" class="mm-empty">
                        <i class="pi pi-user-edit mm-empty__icon" />
                        <div class="mm-empty__title">Nenhum médico encontrado</div>
                        <div class="mm-empty__hint">
                            <template v-if="busca || especFilter || usoFilter">
                                Ajuste os filtros pra ver mais resultados.
                            </template>
                            <template v-else>
                                Cadastre médicos pra registrar encaminhamentos.
                            </template>
                        </div>
                    </div>
                    <div v-else class="mm-grid">
                        <div
                            v-for="m in pagedItems"
                            :key="m.id"
                            class="mm-grid__card"
                            :class="rowStatusClass(m)"
                            role="button"
                            tabindex="0"
                            @click="abrirEditar(m)"
                            @keydown.enter.prevent="abrirEditar(m)"
                            @keydown.space.prevent="abrirEditar(m)"
                        >
                            <div class="mm-grid__top">
                                <span class="mm-row__avatar mm-row__avatar--lg">{{ iniciais(m.nome) }}</span>
                                <span v-if="m.especialidade" class="mm-row__esp">{{ m.especialidade }}</span>
                            </div>
                            <div class="mm-grid__name">Dr(a). {{ m.nome }}</div>
                            <div v-if="m.crm || m.telefone_profissional || m.email" class="mm-grid__contact">
                                <span v-if="m.crm"><i class="pi pi-id-card" /> CRM {{ m.crm }}</span>
                                <span v-if="m.telefone_profissional"><i class="pi pi-phone" /> {{ fmtPhone(m.telefone_profissional) }}</span>
                                <span v-if="m.email"><i class="pi pi-envelope" /> {{ m.email }}</span>
                            </div>
                            <div class="mm-grid__meta" @click.stop>
                                <button
                                    type="button"
                                    class="mm-row__count-btn"
                                    :class="{ 'is-empty': !m.patients_count }"
                                    :disabled="!m.patients_count"
                                    v-tooltip.top="m.patients_count > 0 ? 'Ver pacientes encaminhados' : 'Nenhum paciente encaminhado'"
                                    aria-label="Ver pacientes encaminhados"
                                    @click.stop="openMedicoPatientsModal(m)"
                                >
                                    <i class="pi pi-users" />
                                    <span>
                                        {{ m.patients_count || 0 }}
                                        {{ (m.patients_count || 0) === 1 ? 'paciente' : 'pacientes' }}
                                    </span>
                                </button>
                            </div>
                            <div class="mm-grid__footer" @click.stop>
                                <button
                                    class="mm-row__btn"
                                    v-tooltip.top="'Editar'"
                                    aria-label="Editar"
                                    @click.stop="abrirEditar(m)"
                                >
                                    <i class="pi pi-pencil" />
                                </button>
                                <button
                                    class="mm-row__btn mm-row__btn--danger"
                                    v-tooltip.top="'Desativar'"
                                    aria-label="Desativar"
                                    @click.stop="confirmarExcluir(m)"
                                >
                                    <i class="pi pi-trash" />
                                </button>
                            </div>
                        </div>
                    </div>
                    <Paginator
                        v-if="filtered.length > 0"
                        class="mm-paginator"
                        :rows="rowsMM"
                        :totalRecords="filtered.length"
                        :first="firstMM"
                        :rowsPerPageOptions="PAGE_SIZE_OPTIONS"
                        template="RowsPerPageDropdown FirstPageLink PrevPageLink CurrentPageReport NextPageLink LastPageLink"
                        currentPageReportTemplate="{first}–{last} de {totalRecords}"
                        @page="onPage"
                    />
                </div>
            </div>
        </div>

        <!-- Dialog: criar/editar médico — pattern espelhado da seção
             "Identidade" do PatientsCadastroPage: FloatLabel + IconField
             + variant="filled" em todos os campos, section dividers
             uppercase com linha h-px, grid xl:grid-cols-2. Botões e
             chrome do dialog ficam no padrão PrimeVue. -->
        <Dialog
            v-model:visible="dlgOpen"
            modal
            dismissable-mask
            :draggable="false"
            :style="{ width: '720px', maxWidth: '94vw' }"
            :header="dlgMode === 'create' ? 'Novo médico' : 'Editar médico'"
        >
            <div class="p-1">
                <!-- ── Identificação ─────────────────────────── -->
                <div class="flex items-center gap-2 mb-5">
                    <span class="text-[0.7rem] font-bold uppercase tracking-widest text-[var(--p-primary-color)]">
                        Identificação
                    </span>
                    <div class="flex-1 h-px bg-[color-mix(in_srgb,var(--p-primary-color)_25%,transparent)]" />
                </div>
                <div class="grid grid-cols-1 gap-6 xl:grid-cols-2 mb-7">
                    <!-- Nome — full width -->
                    <div class="xl:col-span-2">
                        <FloatLabel variant="on">
                            <IconField>
                                <InputIcon class="pi pi-user" />
                                <InputText
                                    id="med-nome"
                                    v-model="dlgForm.nome"
                                    class="w-full"
                                    variant="filled"
                                    autofocus
                                />
                            </IconField>
                            <label for="med-nome">Nome completo *</label>
                        </FloatLabel>
                    </div>

                    <!-- CRM -->
                    <div>
                        <FloatLabel variant="on">
                            <IconField>
                                <InputIcon class="pi pi-id-card" />
                                <InputText
                                    id="med-crm"
                                    v-model="dlgForm.crm"
                                    class="w-full"
                                    variant="filled"
                                />
                            </IconField>
                            <label for="med-crm">CRM</label>
                        </FloatLabel>
                    </div>

                    <!-- Especialidade -->
                    <div>
                        <FloatLabel variant="on">
                            <Select
                                id="med-esp"
                                v-model="dlgForm.especialidade"
                                :options="ESPECIALIDADES"
                                class="w-full"
                                variant="filled"
                            />
                            <label for="med-esp">Especialidade</label>
                        </FloatLabel>
                    </div>

                    <!-- Especialidade livre — aparece quando "Outra" -->
                    <div v-if="dlgForm.especialidade === 'Outra'" class="xl:col-span-2">
                        <FloatLabel variant="on">
                            <IconField>
                                <InputIcon class="pi pi-bookmark" />
                                <InputText
                                    id="med-esp-outra"
                                    v-model="dlgForm.especialidade_outra"
                                    class="w-full"
                                    variant="filled"
                                />
                            </IconField>
                            <label for="med-esp-outra">Especialidade (livre) *</label>
                        </FloatLabel>
                    </div>
                </div>

                <!-- ── Contato ──────────────────────────────── -->
                <div class="flex items-center gap-2 mb-5">
                    <span class="text-[0.7rem] font-bold uppercase tracking-widest text-[var(--p-primary-color)]">
                        Contato
                    </span>
                    <div class="flex-1 h-px bg-[color-mix(in_srgb,var(--p-primary-color)_25%,transparent)]" />
                </div>
                <div class="grid grid-cols-1 gap-6 xl:grid-cols-2 mb-7">
                    <div>
                        <FloatLabel variant="on">
                            <IconField>
                                <InputIcon class="pi pi-phone" />
                                <InputText
                                    id="med-tel-prof"
                                    v-model="dlgForm.telefone_profissional"
                                    class="w-full"
                                    variant="filled"
                                />
                            </IconField>
                            <label for="med-tel-prof">Telefone profissional</label>
                        </FloatLabel>
                    </div>

                    <div>
                        <FloatLabel variant="on">
                            <IconField>
                                <InputIcon class="pi pi-mobile" />
                                <InputText
                                    id="med-tel-pes"
                                    v-model="dlgForm.telefone_pessoal"
                                    class="w-full"
                                    variant="filled"
                                />
                            </IconField>
                            <label for="med-tel-pes">Telefone pessoal</label>
                        </FloatLabel>
                    </div>

                    <div class="xl:col-span-2">
                        <FloatLabel variant="on">
                            <IconField>
                                <InputIcon class="pi pi-envelope" />
                                <InputText
                                    id="med-email"
                                    v-model="dlgForm.email"
                                    class="w-full"
                                    variant="filled"
                                />
                            </IconField>
                            <label for="med-email">E-mail</label>
                        </FloatLabel>
                    </div>
                </div>

                <!-- ── Localização ───────────────────────────── -->
                <div class="flex items-center gap-2 mb-5">
                    <span class="text-[0.7rem] font-bold uppercase tracking-widest text-[var(--p-primary-color)]">
                        Localização
                    </span>
                    <div class="flex-1 h-px bg-[color-mix(in_srgb,var(--p-primary-color)_25%,transparent)]" />
                </div>
                <div class="grid grid-cols-1 gap-6 xl:grid-cols-2 mb-7">
                    <div class="xl:col-span-2">
                        <FloatLabel variant="on">
                            <IconField>
                                <InputIcon class="pi pi-building" />
                                <InputText
                                    id="med-clinica"
                                    v-model="dlgForm.clinica"
                                    class="w-full"
                                    variant="filled"
                                />
                            </IconField>
                            <label for="med-clinica">Clínica/instituição</label>
                        </FloatLabel>
                    </div>

                    <div>
                        <FloatLabel variant="on">
                            <IconField>
                                <InputIcon class="pi pi-map-marker" />
                                <InputText
                                    id="med-cidade"
                                    v-model="dlgForm.cidade"
                                    class="w-full"
                                    variant="filled"
                                />
                            </IconField>
                            <label for="med-cidade">Cidade</label>
                        </FloatLabel>
                    </div>

                    <div>
                        <FloatLabel variant="on">
                            <InputText
                                id="med-estado"
                                v-model="dlgForm.estado"
                                maxlength="2"
                                class="w-full uppercase"
                                variant="filled"
                            />
                            <label for="med-estado">UF</label>
                        </FloatLabel>
                    </div>
                </div>

                <!-- ── Observações ───────────────────────────── -->
                <div class="flex items-center gap-2 mb-5">
                    <span class="text-[0.7rem] font-bold uppercase tracking-widest text-[var(--p-primary-color)]">
                        Observações
                    </span>
                    <div class="flex-1 h-px bg-[color-mix(in_srgb,var(--p-primary-color)_25%,transparent)]" />
                </div>
                <div class="grid grid-cols-1 mb-2">
                    <FloatLabel variant="on">
                        <Textarea
                            id="med-obs"
                            v-model="dlgForm.observacoes"
                            autoResize
                            rows="3"
                            class="w-full"
                            variant="filled"
                        />
                        <label for="med-obs">Observações livres</label>
                    </FloatLabel>
                </div>

                <small
                    v-if="dlgError"
                    class="mt-3 text-[0.85rem] text-red-500 flex items-center gap-1.5"
                >
                    <i class="pi pi-exclamation-circle text-[0.78rem]" />
                    <span>{{ dlgError }}</span>
                </small>
            </div>

            <template #footer>
                <Button
                    label="Cancelar"
                    severity="secondary"
                    text
                    :disabled="saving"
                    @click="dlgOpen = false"
                />
                <Button
                    :label="saving ? 'Salvando…' : 'Salvar'"
                    icon="pi pi-check"
                    :loading="saving"
                    :disabled="!dlgForm.nome.trim() || saving"
                    @click="salvar"
                />
            </template>
        </Dialog>

        <!-- Dialog: Pacientes encaminhados — espelha o pattern de
             MelissaTags > "Pacientes da tag", usando cor primary do
             tema (médicos não têm cor própria como tags/grupos). Borda
             colorida + header com avatar + count pill + lista com
             avatares primary-tinted. -->
        <Dialog
            v-model:visible="patientsDialog.open"
            modal
            dismissable-mask
            :draggable="false"
            :style="{ width: '720px', maxWidth: '94vw' }"
            :pt="{
                root: { style: 'border: 2px solid var(--p-primary-color)' },
                header: { style: 'border-bottom: 1px solid color-mix(in srgb, var(--p-primary-color) 30%, transparent)' },
                pcCloseButton: { root: { class: 'mm-pdlg-close-btn' } }
            }"
        >
            <template #header>
                <div class="mm-pdlg__header">
                    <span class="mm-pdlg__avatar mm-pdlg__avatar--primary">
                        {{ iniciais(patientsDialog.medico?.nome) }}
                    </span>
                    <div class="mm-pdlg__title">
                        <div class="mm-pdlg__name mm-pdlg__name--primary">
                            Dr(a). {{ patientsDialog.medico?.nome }}
                        </div>
                        <div class="mm-pdlg__sub">
                            {{ patientsDialog.items.length }}
                            paciente{{ patientsDialog.items.length !== 1 ? 's' : '' }}
                            encaminhado{{ patientsDialog.items.length !== 1 ? 's' : '' }}
                        </div>
                    </div>
                </div>
            </template>

            <div class="mm-pdlg__body">
                <div class="mm-pdlg__toolbar">
                    <div class="mm-search mm-pdlg__search">
                        <i class="pi pi-search mm-search__icon" />
                        <input
                            v-model="patientsDialog.search"
                            type="text"
                            placeholder="Buscar paciente…"
                            class="mm-search__input"
                            :disabled="patientsDialog.loading"
                        />
                        <button
                            v-if="patientsDialog.search"
                            class="mm-search__clear"
                            v-tooltip.bottom="'Limpar busca'"
                            @click="patientsDialog.search = ''"
                        >
                            <i class="pi pi-times" />
                        </button>
                    </div>
                    <span v-if="!patientsDialog.loading" class="mm-pdlg__count-pill mm-pdlg__count-pill--primary">
                        {{ patientsDialog.items.length }}
                        {{ patientsDialog.items.length === 1 ? 'paciente' : 'pacientes' }}
                    </span>
                </div>

                <div v-if="patientsDialog.loading" class="mm-pdlg__loading mm-pdlg__loading--primary">
                    <i class="pi pi-spin pi-spinner" />
                    <span>Carregando pacientes…</span>
                </div>

                <div v-else-if="patientsDialog.error" class="mm-pdlg__error">
                    <i class="pi pi-exclamation-triangle" />
                    <span>{{ patientsDialog.error }}</span>
                </div>

                <div v-else-if="patientsDialog.items.length === 0" class="mm-pdlg__empty">
                    <div class="mm-pdlg__empty-icon mm-pdlg__empty-icon--primary">
                        <i class="pi pi-users" />
                    </div>
                    <div class="mm-pdlg__empty-title">Nenhum paciente encaminhado</div>
                    <div class="mm-pdlg__empty-hint">
                        Pacientes com este médico no campo
                        <strong>"encaminhado por"</strong> aparecem aqui.
                    </div>
                </div>

                <DataTable
                    v-else
                    :value="patientsDialogFiltered"
                    dataKey="id"
                    paginator
                    :rows="8"
                    :rowsPerPageOptions="[8, 15, 30]"
                    paginatorTemplate="RowsPerPageDropdown FirstPageLink PrevPageLink CurrentPageReport NextPageLink LastPageLink"
                    currentPageReportTemplate="{first}–{last} de {totalRecords}"
                    stripedRows
                    responsiveLayout="scroll"
                    class="mm-pdlg__table"
                >
                    <Column header="Paciente" sortable>
                        <template #body="{ data }">
                            <div class="mm-pdlg__patient">
                                <span class="mm-pdlg__avatar mm-pdlg__avatar--sm mm-pdlg__avatar--primary-soft">
                                    <img v-if="data.avatar_url" :src="data.avatar_url" :alt="data.full_name" />
                                    <span v-else>{{ iniciais(data.full_name) }}</span>
                                </span>
                                <div class="mm-pdlg__patient-text">
                                    <span class="mm-pdlg__patient-name">{{ data.full_name }}</span>
                                    <span class="mm-pdlg__patient-email">{{ data.email || '—' }}</span>
                                </div>
                            </div>
                        </template>
                    </Column>

                    <Column header="Telefone" style="min-width: 11rem">
                        <template #body="{ data }">
                            <span class="mm-pdlg__phone">{{ fmtPhone(data.phone) || '—' }}</span>
                        </template>
                    </Column>

                    <Column header="" style="width: 7rem">
                        <template #body="{ data }">
                            <button
                                type="button"
                                class="mm-pdlg__open-btn mm-pdlg__open-btn--primary"
                                v-tooltip.left="'Abrir prontuário'"
                                aria-label="Abrir prontuário do paciente"
                                @click="abrirPaciente(data)"
                            >
                                <i class="pi pi-external-link" />
                                <span>Abrir</span>
                            </button>
                        </template>
                    </Column>

                    <template #empty>
                        <div class="mm-pdlg__empty">
                            <i class="pi pi-search mm-pdlg__empty-icon-pi" />
                            <div class="mm-pdlg__empty-title">Nenhum resultado</div>
                            <div class="mm-pdlg__empty-hint">
                                Nenhum paciente corresponde à busca.
                            </div>
                            <button
                                class="mm-pdlg__inline-clear-btn"
                                @click="patientsDialog.search = ''"
                            >
                                <i class="pi pi-filter-slash" />
                                <span>Limpar busca</span>
                            </button>
                        </div>
                    </template>
                </DataTable>
            </div>
        </Dialog>

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

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

.mm-page__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 18px;
    border-bottom: 1px solid var(--m-border);
    flex-shrink: 0;
    gap: 10px;
}
.mm-page__title {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1rem;
    font-weight: 500;
}
.mm-page__title-icon {
    color: var(--p-primary-color);
    font-size: 1.05rem;
}
.mm-page__title > span:not(.mm-page__count) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mm-page__count {
    font-size: 0.7rem;
    font-weight: 600;
    color: var(--m-accent);
    background: var(--m-accent-soft);
    border: 1px solid color-mix(in srgb, var(--m-accent) 35%, transparent);
    padding: 2px 8px;
    border-radius: 999px;
}
.mm-page__actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

.mm-close, .mm-head-btn {
    width: 32px; height: 32px;
    display: grid; place-items: center;
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    color: var(--m-text);
    border-radius: 9px;
    cursor: pointer;
    font-family: inherit;
    transition: background-color 140ms ease;
}
.mm-close:hover, .mm-head-btn:hover { background: var(--m-bg-soft-hover); }
.mm-head-btn > i { font-size: 0.85rem; }

.mm-act-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    height: 32px;
    padding: 0 12px;
    border-radius: 9px;
    cursor: pointer;
    font-family: inherit;
    font-size: 0.78rem;
    font-weight: 600;
    transition: background-color 140ms ease, transform 140ms ease;
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    color: var(--m-text);
}
.mm-act-btn--primary {
    background: var(--m-accent);
    border-color: var(--m-accent);
    color: white;
}
.mm-act-btn--primary:hover {
    background: color-mix(in srgb, var(--m-accent) 88%, white);
    transform: translateY(-1px);
}
.mm-act-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
.mm-act-btn > i { font-size: 0.78rem; }

.mm-menu-btn {
    display: none;
    height: 32px;
    align-items: center;
    gap: 6px;
    flex-shrink: 0;
    background: var(--m-accent);
    border: 1px solid var(--m-accent);
    color: white;
    padding: 0 11px;
    border-radius: 9px;
    cursor: pointer;
    font-family: inherit;
    font-size: 0.78rem;
    font-weight: 600;
    transition: background-color 140ms ease, transform 140ms ease;
}
.mm-menu-btn:hover {
    background: color-mix(in srgb, var(--m-accent) 88%, white);
    transform: translateY(-1px);
}

.mm-subheader {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 10px 18px;
    border-bottom: 1px solid var(--m-border);
    background: var(--m-bg-soft);
    font-size: 0.78rem;
    color: var(--m-text-muted);
    line-height: 1.45;
    flex-shrink: 0;
}
.mm-subheader__icon {
    color: var(--p-primary-color);
    font-size: 0.92rem;
    flex-shrink: 0;
    margin-top: 1px;
}
.mm-subheader__text { flex: 1; min-width: 0; }
.mm-subheader__text strong { color: var(--m-text); font-weight: 600; }

.mm-body {
    flex: 1;
    display: flex;
    min-height: 0;
    gap: 0;
    padding: 0;
}

/* ─── Sidebar ─── */
.mm-side {
    width: 280px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    background: var(--m-bg-soft);
    border-right: 1px solid var(--m-border);
    overflow: hidden;
}
.mm-side__scroll {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
}
.mm-side__scroll::-webkit-scrollbar { width: 5px; }
.mm-side__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

.mm-side__footer {
    flex-shrink: 0;
    padding: 12px;
    background: var(--m-bg-soft);
    border-top: 1px solid var(--m-border);
}
.mm-side__clear-all {
    width: 100%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 9px 12px;
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    color: var(--m-text);
    border-radius: 10px;
    cursor: pointer;
    font-family: inherit;
    font-size: 0.78rem;
    font-weight: 600;
    transition: background-color 140ms ease, border-color 140ms ease, color 140ms ease;
}
.mm-side__clear-all:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    color: var(--m-text);
}
.mm-side__clear-all > i {
    font-size: 0.78rem;
    color: var(--m-text-muted);
    transition: color 140ms ease;
}
.mm-side__clear-all:hover > i { color: var(--m-text); }

.mm-side__clear-inline {
    width: 18px;
    height: 18px;
    display: grid;
    place-items: center;
    background: transparent;
    border: 1px solid color-mix(in srgb, rgb(220, 38, 38) 30%, var(--m-border));
    color: rgb(220, 38, 38);
    border-radius: 4px;
    cursor: pointer;
    font-family: inherit;
    transition: background-color 140ms ease, border-color 140ms ease;
}
.mm-side__clear-inline:hover {
    background: rgba(220, 38, 38, 0.10);
    border-color: rgba(220, 38, 38, 0.55);
}
.mm-side__clear-inline > i { font-size: 0.6rem; }

.mm-w {
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    border-radius: 12px;
    padding: 12px;
}
.mm-w--side {
    margin: 12px 12px 0;
    flex-shrink: 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}
.mm-w--side:last-of-type { margin-bottom: 12px; }
.mm-w__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}
.mm-w__title {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 0.7rem;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    color: var(--m-text-muted);
    font-weight: 600;
}
.mm-w__title > i { color: var(--m-text-muted); font-size: 0.7rem; }

.mm-stats {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 6px;
}
.mm-stat {
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-radius: 10px;
    padding: 8px 10px;
}
.mm-stat__val {
    font-size: 1.1rem;
    font-weight: 600;
    line-height: 1.1;
}
.mm-stat__lbl {
    font-size: 0.65rem;
    color: var(--m-text-muted);
    margin-top: 4px;
    text-transform: uppercase;
    letter-spacing: 0.06em;
}
.mm-stat.is-ok .mm-stat__val     { color: rgb(22, 163, 74); }
.mm-stat.is-info .mm-stat__val   { color: rgb(37, 99, 235); }
.mm-stat.is-accent .mm-stat__val { color: var(--m-accent); }

/* Select de Especialidade na sidebar */
.mm-side__select :deep(.p-select) {
    width: 100%;
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-radius: 9px;
    height: 36px;
}
.mm-side__select :deep(.p-select-label) {
    font-size: 0.82rem;
    padding: 0 10px;
    color: var(--m-text);
    line-height: 36px;
}

/* ─── Filter buttons ─── */
.mm-side__list {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.mm-side__item {
    width: 100%;
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 8px 10px;
    background: transparent;
    border: 1px solid transparent;
    color: var(--m-text);
    border-radius: 10px;
    cursor: pointer;
    font-family: inherit;
    font-size: 0.82rem;
    text-align: left;
    transition: background-color 140ms ease, border-color 140ms ease, box-shadow 140ms ease;
}
.mm-side__item > i {
    font-size: 0.78rem;
    width: 14px;
    text-align: center;
}

/* Uso: Com pacientes = green-600, Sem pacientes = neutral/cinza */
.mm-side__item.is-uso-com_pacs {
    background: rgba(22, 163, 74, 0.05);
    border-color: rgba(22, 163, 74, 0.18);
}
.mm-side__item.is-uso-com_pacs > i { color: rgb(22, 163, 74); }
.mm-side__item.is-uso-com_pacs:hover {
    background: rgba(22, 163, 74, 0.10);
    border-color: rgba(22, 163, 74, 0.30);
}
.mm-side__item.is-active.is-uso-com_pacs {
    background: rgba(22, 163, 74, 0.16);
    border-color: rgba(22, 163, 74, 0.55);
    box-shadow: 0 0 0 1px rgba(22, 163, 74, 0.35);
}

.mm-side__item.is-uso-sem_pacs {
    background: var(--m-bg-soft);
    border-color: var(--m-border);
}
.mm-side__item.is-uso-sem_pacs > i { color: var(--m-text-muted); }
.mm-side__item.is-uso-sem_pacs:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
}
.mm-side__item.is-active.is-uso-sem_pacs {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    box-shadow: 0 0 0 1px var(--m-border-strong);
}

.mm-clear-enter-active,
.mm-clear-leave-active {
    transition: opacity 220ms ease, transform 220ms ease, max-height 240ms ease;
    overflow: hidden;
}
.mm-clear-enter-from,
.mm-clear-leave-to {
    opacity: 0;
    transform: translateY(6px);
    max-height: 0;
}
.mm-clear-enter-to,
.mm-clear-leave-from {
    opacity: 1;
    transform: translateY(0);
    max-height: 80px;
}

/* ─── Main column ─── */
.mm-main {
    flex: 1;
    min-width: 0;
    min-height: 0;
    display: flex;
    flex-direction: column;
    padding: 12px;
    gap: 10px;
}

.mm-toolbar {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}
.mm-search {
    position: relative;
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
}
.mm-search__icon {
    position: absolute;
    left: 12px;
    color: var(--m-text-muted);
    font-size: 0.78rem;
    pointer-events: none;
}
.mm-search__input {
    width: 100%;
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    color: var(--m-text);
    padding: 9px 36px 9px 34px;
    border-radius: 10px;
    font-size: 0.85rem;
    font-family: inherit;
    outline: none;
    transition: background-color 140ms ease, border-color 140ms ease;
}
.mm-search__input::placeholder { color: var(--m-text-faint); }
.mm-search__input:focus {
    border-color: var(--m-border-strong);
    background: var(--m-bg-medium);
}
.mm-search__clear {
    position: absolute;
    right: 8px;
    width: 22px;
    height: 22px;
    display: grid;
    place-items: center;
    background: transparent;
    border: none;
    color: var(--m-text-muted);
    border-radius: 6px;
    cursor: pointer;
    font-family: inherit;
    transition: background-color 140ms ease, color 140ms ease;
}
.mm-search__clear:hover {
    background: var(--m-bg-soft-hover);
    color: var(--m-text);
}
.mm-search__clear > i { font-size: 0.7rem; }

.mm-view-toggle {
    flex-shrink: 0;
    display: inline-flex;
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    border-radius: 10px;
    padding: 2px;
    gap: 2px;
}
.mm-view-toggle__btn {
    width: 32px;
    height: 32px;
    display: grid;
    place-items: center;
    background: transparent;
    border: none;
    color: var(--m-text-muted);
    border-radius: 8px;
    cursor: pointer;
    font-family: inherit;
    transition: background-color 140ms ease, color 140ms ease;
}
.mm-view-toggle__btn:hover {
    background: var(--m-bg-soft-hover);
    color: var(--m-text);
}
.mm-view-toggle__btn.is-active {
    background: var(--m-accent-soft);
    color: var(--m-accent);
}
.mm-view-toggle__btn > i { font-size: 0.85rem; }

/* ─── DataTable ─── */
.mm-table {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
}
.mm-table :deep(.p-datatable) {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background: transparent;
    border: 1px solid var(--m-border);
    border-radius: 10px;
    overflow: hidden;
}
.mm-table :deep(.p-datatable-table-container) {
    flex: 1;
    min-height: 0;
    background: transparent;
}
.mm-table :deep(.p-datatable-thead),
.mm-table :deep(.p-datatable-thead > tr) {
    background: transparent !important;
}
.mm-table :deep(.p-datatable-thead > tr > th) {
    background: var(--p-content-background) !important;
    color: var(--m-text);
    font-size: 0.78rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    padding: 10px 14px;
    border-bottom: 1px solid var(--m-border);
}
.mm-table :deep(.p-datatable-tbody > tr) {
    background: transparent;
    color: var(--m-text);
    cursor: pointer;
    transition: background-color 140ms ease;
    border-left: 3px solid var(--m-border);
}
.mm-table :deep(.p-datatable-tbody > tr > td) {
    padding: 10px 14px;
    border-bottom: 1px solid var(--m-border);
    background: transparent;
    vertical-align: middle;
}
.mm-table :deep(.p-datatable-tbody > tr:hover) {
    background: var(--m-bg-soft-hover);
}
.mm-table :deep(.p-datatable-tbody > tr.p-datatable-row-selected) {
    background: var(--m-accent-soft);
}
.mm-table :deep(.p-datatable-tbody > tr.is-com-pacs) { border-left-color: rgb(22, 163, 74); }
.mm-table :deep(.p-datatable-tbody > tr.is-sem-pacs) { border-left-color: var(--m-border-strong); }

.mm-table :deep(.p-datatable-loading-overlay) {
    background: color-mix(in srgb, var(--m-bg-medium) 70%, transparent);
    backdrop-filter: blur(2px);
}
.mm-table__loading {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: var(--m-text);
    font-size: 0.85rem;
}

.mm-table :deep(.p-paginator) {
    background: var(--m-bg-medium);
    border: none;
    border-top: 1px solid var(--m-border);
    padding: 8px 12px;
    justify-content: center;
    flex-wrap: wrap;
    gap: 6px;
}
.mm-table :deep(.p-paginator-current) {
    color: var(--m-text-muted);
    font-size: 0.78rem;
    background: transparent;
    border: none;
    padding: 0 6px;
}
.mm-table :deep(.p-paginator-first),
.mm-table :deep(.p-paginator-prev),
.mm-table :deep(.p-paginator-next),
.mm-table :deep(.p-paginator-last),
.mm-table :deep(.p-paginator-page) {
    min-width: 30px;
    height: 30px;
    color: var(--m-text);
    background: transparent;
    border: 1px solid var(--m-border);
    border-radius: 8px;
    font-size: 0.8rem;
    transition: background-color 140ms ease, border-color 140ms ease;
}
.mm-table :deep(.p-paginator-page.p-paginator-page-selected) {
    background: var(--m-accent-soft);
    border-color: var(--m-accent-strong);
    color: var(--m-accent);
}
.mm-table :deep(.p-paginator-first:not(.p-disabled):hover),
.mm-table :deep(.p-paginator-prev:not(.p-disabled):hover),
.mm-table :deep(.p-paginator-next:not(.p-disabled):hover),
.mm-table :deep(.p-paginator-last:not(.p-disabled):hover),
.mm-table :deep(.p-paginator-page:not(.p-paginator-page-selected):hover) {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
}
.mm-table :deep(.p-select) {
    background: transparent;
    border: 1px solid var(--m-border);
    border-radius: 8px;
    height: 30px;
    font-size: 0.78rem;
    color: var(--m-text);
    display: inline-flex;
    align-items: center;
}
.mm-table :deep(.p-select-label) {
    padding: 0 8px;
    color: var(--m-text);
    font-size: 0.78rem;
    display: flex;
    align-items: center;
    line-height: 1;
    height: 100%;
    background: transparent;
}

.mm-table :deep(td.p-datatable-frozen-column),
.mm-table :deep(th.p-datatable-frozen-column) {
    background: var(--p-content-background) !important;
    box-shadow: -3px 0 6px -3px rgba(0, 0, 0, 0.18);
    z-index: 1;
}
.mm-table :deep(.p-datatable-tbody > tr:hover td.p-datatable-frozen-column) {
    background: var(--m-bg-soft-hover);
}
.mm-table :deep(.p-datatable-tbody > tr.p-datatable-row-selected td.p-datatable-frozen-column) {
    background: var(--m-accent-soft);
}

/* ─── Row content (design preservado: avatar + nome + esp + meta) ─── */
.mm-row__med {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
}
.mm-row__avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: var(--m-accent-strong);
    border: 1px solid var(--m-accent);
    color: white;
    font-size: 0.78rem;
    font-weight: 600;
    display: grid;
    place-items: center;
    flex-shrink: 0;
}
.mm-row__avatar--lg {
    width: 48px;
    height: 48px;
    font-size: 0.92rem;
}
.mm-row__main {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 2px;
}
.mm-row__name-row {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}
.mm-row__name {
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--m-text);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mm-row__esp {
    display: inline-flex;
    align-items: center;
    font-size: 0.62rem;
    font-weight: 600;
    padding: 2px 8px;
    border-radius: 999px;
    background: var(--m-accent-soft);
    border: 1px solid color-mix(in srgb, var(--m-accent) 35%, var(--m-border));
    color: var(--m-accent);
    text-transform: uppercase;
    letter-spacing: 0.04em;
    flex-shrink: 0;
}
.mm-row__sub {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 0.74rem;
    color: var(--m-text-muted);
    flex-wrap: wrap;
}
.mm-row__sub > i { font-size: 0.7rem; }
.mm-row__sep { color: var(--m-text-faint); }

.mm-row__contact {
    display: flex;
    flex-direction: column;
    gap: 4px;
    font-size: 0.78rem;
    color: var(--m-text-muted);
    min-width: 0;
}
.mm-row__contact > span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mm-row__contact i { margin-right: 5px; font-size: 0.7rem; }
.mm-row__empty { color: var(--m-text-faint); }

/* Botão "X pacientes" clicável */
.mm-row__count-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 10px;
    background: transparent;
    border: 1px solid color-mix(in srgb, var(--p-primary-color) 25%, var(--m-border));
    color: var(--p-primary-color);
    border-radius: 999px;
    cursor: pointer;
    font-family: inherit;
    font-size: 0.78rem;
    font-weight: 500;
    transition: background-color 140ms ease, border-color 140ms ease, color 140ms ease;
    white-space: nowrap;
}
.mm-row__count-btn:hover:not(:disabled) {
    background: color-mix(in srgb, var(--p-primary-color) 12%, transparent);
    border-color: var(--p-primary-color);
}
.mm-row__count-btn:focus-visible {
    outline: 2px solid var(--p-primary-color);
    outline-offset: 2px;
}
.mm-row__count-btn.is-empty,
.mm-row__count-btn:disabled {
    color: var(--m-text-muted);
    border-color: var(--m-border);
    cursor: default;
    background: transparent;
}
.mm-row__count-btn > i { font-size: 0.7rem; }

.mm-row__actions {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 6px;
    flex-shrink: 0;
}
.mm-row__btn {
    width: 28px;
    height: 28px;
    display: grid;
    place-items: center;
    background: var(--p-content-background);
    border: 1px solid var(--m-border);
    color: var(--m-text-muted);
    border-radius: 8px;
    cursor: pointer;
    font-family: inherit;
    transition: background-color 140ms ease, color 140ms ease, border-color 140ms ease;
    flex-shrink: 0;
}
.mm-row__btn:hover {
    background: color-mix(in srgb, var(--p-primary-color) 12%, var(--p-content-background));
    border-color: var(--p-primary-color);
    color: var(--p-primary-color);
}
.mm-row__btn--danger:hover {
    background: rgba(220, 38, 38, 0.12);
    border-color: rgba(220, 38, 38, 0.5);
    color: rgb(220, 38, 38);
}
.mm-row__btn:disabled { opacity: 0.4; cursor: not-allowed; }
.mm-row__btn > i { font-size: 0.7rem; }

/* ─── Grid view ─── */
.mm-grid-wrap {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    gap: 10px;
    border: 1px solid var(--m-border);
    border-radius: 10px;
    overflow: hidden;
    background: transparent;
}
.mm-grid {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    padding: 12px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 10px;
    align-content: start;
}
.mm-grid::-webkit-scrollbar { width: 5px; }
.mm-grid::-webkit-scrollbar-thumb { background: var(--m-border-strong); border-radius: 3px; }
.mm-grid__loading {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 32px;
}
.mm-grid__card {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 12px;
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-left: 3px solid var(--m-border-strong);
    border-radius: 10px;
    color: var(--m-text);
    text-align: left;
    cursor: pointer;
    font-family: inherit;
    transition: background-color 140ms ease, border-color 140ms ease, transform 140ms ease;
}
.mm-grid__card:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    transform: translateY(-1px);
}
.mm-grid__card:focus-visible {
    outline: 2px solid var(--p-primary-color);
    outline-offset: 2px;
}
.mm-grid__card.is-com-pacs { border-left-color: rgb(22, 163, 74); }
.mm-grid__card.is-sem-pacs { border-left-color: var(--m-border-strong); }

.mm-grid__top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
}
.mm-grid__name {
    font-size: 0.95rem;
    font-weight: 600;
    color: var(--m-text);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mm-grid__contact {
    display: flex;
    flex-direction: column;
    gap: 4px;
    font-size: 0.74rem;
    color: var(--m-text-muted);
}
.mm-grid__contact > span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mm-grid__contact i { margin-right: 5px; font-size: 0.65rem; }
.mm-grid__meta {
    margin-top: auto;
    padding-top: 4px;
}
.mm-grid__footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 6px;
    border-top: 1px solid var(--m-border);
    padding-top: 8px;
    margin-top: 4px;
}

/* Paginator standalone (grid) */
.mm-paginator.p-paginator {
    background: var(--m-bg-medium);
    border: none;
    border-top: 1px solid var(--m-border);
    padding: 8px 12px;
    justify-content: center;
    flex-wrap: wrap;
    gap: 6px;
    flex-shrink: 0;
}
.mm-paginator.p-paginator .p-paginator-current {
    color: var(--m-text-muted);
    font-size: 0.78rem;
    background: transparent;
    border: none;
    padding: 0 6px;
}
.mm-paginator.p-paginator .p-paginator-first,
.mm-paginator.p-paginator .p-paginator-prev,
.mm-paginator.p-paginator .p-paginator-next,
.mm-paginator.p-paginator .p-paginator-last,
.mm-paginator.p-paginator .p-paginator-page {
    min-width: 30px;
    height: 30px;
    color: var(--m-text);
    background: transparent;
    border: 1px solid var(--m-border);
    border-radius: 8px;
    font-size: 0.8rem;
    transition: background-color 140ms ease, border-color 140ms ease;
}
.mm-paginator.p-paginator .p-paginator-page.p-paginator-page-selected {
    background: var(--m-accent-soft);
    border-color: var(--m-accent-strong);
    color: var(--m-accent);
}
.mm-paginator.p-paginator .p-paginator-first:not(.p-disabled):hover,
.mm-paginator.p-paginator .p-paginator-prev:not(.p-disabled):hover,
.mm-paginator.p-paginator .p-paginator-next:not(.p-disabled):hover,
.mm-paginator.p-paginator .p-paginator-last:not(.p-disabled):hover,
.mm-paginator.p-paginator .p-paginator-page:not(.p-paginator-page-selected):hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
}
.mm-paginator.p-paginator .p-select {
    background: transparent;
    border: 1px solid var(--m-border);
    border-radius: 8px;
    height: 30px;
    font-size: 0.78rem;
    color: var(--m-text);
    display: inline-flex;
    align-items: center;
}
.mm-paginator.p-paginator .p-select-label {
    padding: 0 8px;
    color: var(--m-text);
    font-size: 0.78rem;
    display: flex;
    align-items: center;
    line-height: 1;
    height: 100%;
    background: transparent;
}

/* ─── Empty state ─── */
.mm-empty {
    margin: 24px 0;
    padding: 56px 28px;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    color: var(--m-text-muted);
    border: 2px dashed var(--m-border-strong);
    border-radius: 12px;
    background: color-mix(in srgb, var(--m-bg-soft) 40%, transparent);
    gap: 8px;
}
.mm-empty__icon { font-size: 2rem; color: var(--m-text-faint); margin-bottom: 4px; }
.mm-empty__title { font-size: 0.92rem; font-weight: 600; color: var(--m-text); }
.mm-empty__hint { font-size: 0.78rem; }
.mm-empty__btn { margin-top: 8px; }

/* ─── Dialog "Pacientes encaminhados" ─── */
.mm-pdlg__header {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
}
.mm-pdlg__avatar {
    width: 40px;
    height: 40px;
    display: grid;
    place-items: center;
    border-radius: 50%;
    background: var(--m-accent-strong);
    border: 1px solid var(--m-accent);
    color: white;
    font-weight: 600;
    font-size: 0.85rem;
    flex-shrink: 0;
    overflow: hidden;
}
/* Avatar primary (header do dialog) — sólido */
.mm-pdlg__avatar--primary {
    background: var(--p-primary-color);
    border-color: var(--p-primary-color);
    color: var(--p-primary-contrast-color, white);
}
/* Avatar primary-soft (lista de pacientes) — tinted */
.mm-pdlg__avatar--primary-soft {
    background: color-mix(in srgb, var(--p-primary-color) 22%, transparent);
    border: 1px solid color-mix(in srgb, var(--p-primary-color) 30%, transparent);
    color: var(--p-primary-color);
}
.mm-pdlg__avatar--sm {
    width: 32px;
    height: 32px;
    font-size: 0.74rem;
}
.mm-pdlg__avatar img { width: 100%; height: 100%; object-fit: cover; }
.mm-pdlg__title {
    display: flex;
    flex-direction: column;
    gap: 2px;
    min-width: 0;
}
.mm-pdlg__name {
    font-size: 1rem;
    font-weight: 700;
    color: var(--m-text);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mm-pdlg__name--primary { color: var(--p-primary-color); }
.mm-pdlg__sub {
    font-size: 0.72rem;
    color: var(--m-text-muted);
}

.mm-pdlg__body {
    display: flex;
    flex-direction: column;
    gap: 14px;
}
.mm-pdlg__toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    flex-wrap: wrap;
}
.mm-pdlg__search {
    flex: 1;
    min-width: 200px;
    max-width: 320px;
}
.mm-pdlg__count-pill {
    padding: 4px 10px;
    border-radius: 999px;
    font-size: 0.72rem;
    font-weight: 600;
    flex-shrink: 0;
    background: var(--m-accent-soft);
    color: var(--m-accent);
    border: 1px solid color-mix(in srgb, var(--m-accent) 35%, transparent);
}
.mm-pdlg__count-pill--primary {
    background: color-mix(in srgb, var(--p-primary-color) 18%, transparent);
    color: var(--p-primary-color);
    border-color: color-mix(in srgb, var(--p-primary-color) 35%, transparent);
}

.mm-pdlg__loading {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 20px;
    font-size: 0.85rem;
    justify-content: center;
    color: var(--m-accent);
}
.mm-pdlg__loading--primary { color: var(--p-primary-color); }
.mm-pdlg__error {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: rgba(220, 38, 38, 0.10);
    border: 1px solid rgba(220, 38, 38, 0.30);
    border-radius: 8px;
    color: rgb(220, 38, 38);
    font-size: 0.82rem;
}

.mm-pdlg__empty {
    padding: 36px 20px;
    text-align: center;
    color: var(--m-text-muted);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
}
.mm-pdlg__empty-icon {
    width: 48px;
    height: 48px;
    display: grid;
    place-items: center;
    border-radius: 10px;
    margin-bottom: 8px;
    font-size: 1.4rem;
    background: var(--m-accent-soft);
    color: var(--m-accent);
}
.mm-pdlg__empty-icon--primary {
    background: color-mix(in srgb, var(--p-primary-color) 18%, transparent);
    color: var(--p-primary-color);
}
.mm-pdlg__empty-icon-pi {
    font-size: 1.6rem;
    opacity: 0.4;
    margin-bottom: 8px;
}
.mm-pdlg__empty-title {
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--m-text);
}
.mm-pdlg__empty-hint { font-size: 0.78rem; }
.mm-pdlg__empty-hint strong { color: var(--m-text); font-weight: 600; }
.mm-pdlg__inline-clear-btn {
    margin-top: 10px;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    background: transparent;
    border: 1px solid var(--m-border);
    color: var(--m-text-muted);
    border-radius: 8px;
    cursor: pointer;
    font-family: inherit;
    font-size: 0.78rem;
    transition: background-color 140ms ease, border-color 140ms ease, color 140ms ease;
}
.mm-pdlg__inline-clear-btn:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    color: var(--m-text);
}

.mm-pdlg__table :deep(.p-datatable) {
    background: transparent;
    border: 1px solid var(--m-border);
    border-radius: 10px;
    overflow: hidden;
}
.mm-pdlg__table :deep(.p-datatable-thead > tr > th) {
    background: var(--m-bg-soft) !important;
    color: var(--m-text);
    font-size: 0.74rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    padding: 10px 12px;
    border-bottom: 1px solid var(--m-border);
}
.mm-pdlg__table :deep(.p-datatable-tbody > tr > td) {
    padding: 10px 12px;
    border-bottom: 1px solid var(--m-border);
    background: transparent;
    vertical-align: middle;
}
.mm-pdlg__table :deep(.p-datatable-tbody > tr:hover) {
    background: var(--m-bg-soft-hover);
}
.mm-pdlg__table :deep(.p-paginator) {
    background: var(--m-bg-soft);
    border: none;
    border-top: 1px solid var(--m-border);
    padding: 8px 12px;
    justify-content: center;
    flex-wrap: wrap;
    gap: 6px;
}

.mm-pdlg__patient {
    display: flex;
    align-items: center;
    gap: 10px;
    min-width: 0;
}
.mm-pdlg__patient-text {
    display: flex;
    flex-direction: column;
    gap: 2px;
    min-width: 0;
}
.mm-pdlg__patient-name {
    font-size: 0.88rem;
    font-weight: 600;
    color: var(--m-text);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mm-pdlg__patient-email {
    font-size: 0.74rem;
    color: var(--m-text-muted);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mm-pdlg__phone {
    color: var(--m-text-muted);
    font-size: 0.85rem;
}
.mm-pdlg__open-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    background: transparent;
    border: 1px solid var(--m-accent);
    color: var(--m-accent);
    border-radius: 8px;
    cursor: pointer;
    font-family: inherit;
    font-size: 0.78rem;
    font-weight: 600;
    transition: background-color 140ms ease;
}
.mm-pdlg__open-btn:hover {
    background: var(--m-accent-soft);
}
.mm-pdlg__open-btn > i { font-size: 0.7rem; }
.mm-pdlg__open-btn--primary {
    border-color: var(--p-primary-color);
    color: var(--p-primary-color);
}
.mm-pdlg__open-btn--primary:hover {
    background: color-mix(in srgb, var(--p-primary-color) 12%, transparent);
}

/* Botão X de fechar no header do dialog "Pacientes encaminhados" —
   estilo igual ao .mm-close da página (32×32, bg --m-bg-soft, border).
   Usa :global() porque o Dialog do PrimeVue é teleportado pra body,
   fora do escopo scoped do componente. */
:global(.mm-pdlg-close-btn) {
    width: 32px !important;
    height: 32px !important;
    background: var(--m-bg-soft) !important;
    border: 1px solid var(--m-border) !important;
    color: var(--m-text) !important;
    border-radius: 9px !important;
    transition: background-color 140ms ease !important;
}
:global(.mm-pdlg-close-btn:hover) {
    background: var(--m-bg-soft-hover) !important;
}
:global(.mm-pdlg-close-btn .p-button-icon) {
    font-size: 0.85rem !important;
}

/* ─── Drawer mobile ─── */
.mm-mobile-drawer {
    position: fixed;
    top: 0; left: 0;
    height: 100vh;
    height: 100dvh;
    width: min(360px, 88vw);
    z-index: 80;
    background: var(--m-bg-medium);
    backdrop-filter: blur(28px) saturate(160%);
    -webkit-backdrop-filter: blur(28px) saturate(160%);
    border-right: 1px solid var(--m-border);
    transform: translateX(-100%);
    transition: transform 250ms cubic-bezier(0.4, 0, 0.2, 1);
    color: var(--m-text);
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
    display: flex;
    flex-direction: column;
}
.mm-mobile-drawer.is-open { transform: translateX(0); }
.mm-mobile-drawer__scroll {
    flex: 1;
    min-height: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}
.mm-mobile-drawer__scroll .mm-side {
    flex: 1;
    min-height: 0;
    width: 100%;
    overflow: hidden;
    background: transparent;
    border-right: none;
    display: flex;
    flex-direction: column;
}
.mm-mobile-drawer__scroll .mm-side__scroll {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mm-mobile-drawer__scroll .mm-side__scroll::-webkit-scrollbar { width: 5px; }
.mm-mobile-drawer__scroll .mm-side__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}
.mm-mobile-drawer__scroll .mm-w--side {
    margin: 0;
    flex-shrink: 0;
}
.mm-mobile-drawer__scroll .mm-w--side:last-of-type { margin-bottom: 0; }
.mm-mobile-drawer__scroll .mm-side__footer {
    flex-shrink: 0;
    margin: 0;
    padding: 12px;
    background: var(--m-bg-medium);
    border-top: 1px solid var(--m-border);
    backdrop-filter: blur(24px) saturate(160%);
    -webkit-backdrop-filter: blur(24px) saturate(160%);
}
.mm-mobile-drawer__backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.45);
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
    z-index: 79;
}
.mm-drawer-fade-enter-active,
.mm-drawer-fade-leave-active { transition: opacity 200ms ease; }
.mm-drawer-fade-enter-from,
.mm-drawer-fade-leave-to { opacity: 0; }

/* ─── Mobile (<1024px) ─── */
@media (max-width: 1023px) {
    .mm-body { flex-direction: column; padding: 0; }
    .mm-main { width: 100%; padding: 8px; }
    .mm-page__title > span:first-of-type { display: none; }
    .mm-page__title-icon { display: none; }
    .mm-menu-btn--mobile-only { display: inline-flex; }
    .mm-act-btn--primary span { display: none; }
    .mm-act-btn--primary { width: 32px; padding: 0; justify-content: center; }
}

/* ═══════ Fake dialog: largura adaptativa (>=1024px) ═══════
   Espelha pattern de MelissaAgendador/Negocio — fica mesma janela,
   drawer a esquerda, sobra espaco a direita. */
@media (min-width: 1024px) {
    .mm-page {
        right: max(6px, min(50%, calc(100% - 1006px)));
    }
}
</style>
