<script setup>
/*
 * MelissaTags — Tags de pacientes (CRUD + lista de pacientes vinculados).
 * Segue blueprint melissa-table-page-blueprint.md (DataTable + sidebar com
 * filtros coloridos, view toggle list/grade, subheader, footer fixo com
 * "Limpar filtros", Xs inline pra zerar filtro individual).
 *
 * Tabela: patient_tags (filtro por owner_id — tags são per-user, não
 * tenant-wide como grupos); join com pacientes via patient_patient_tag.
 * View opcional: v_tag_patient_counts (com pacientes_count agregado).
 *
 * Row design preservado: dot colorido + nome + badge "Padrão" + contagem
 * de pacientes; coluna "Ações" frozen 100px com pencil + trash (ocultos
 * em is_padrao).
 *
 * Click na coluna "Pacientes" abre dialog com a lista vinculada (espelha
 * GruposPacientesPage / MelissaGrupos).
 */
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import { supabase } from '@/lib/supabase/client';
import { tenantDb } from '@/lib/supabase/tenantClient';
import PatientCadastroDialog from '@/components/ui/PatientCadastroDialog.vue';
// DataTable/Column/Paginator/Dialog/InputText/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 tags = ref([]);

const busca = ref('');
const tipoFilter = ref('');   // '' | 'padrao' | 'mine'
const usoFilter = ref('');    // '' | 'em_uso' | 'vazio'

// ── Helpers de status (rowClass) ──────────────────────────
function rowStatusClass(t) {
    if (!t) return '';
    if (t.is_padrao) return 'is-padrao';
    if ((t.pacientes_count || 0) > 0) return 'is-em-uso';
    return 'is-vazio';
}

// ── Stats ─────────────────────────────────────────────────
const stats = computed(() => {
    const all = tags.value;
    const minhas = all.filter((t) => !t.is_padrao).length;
    const padrao = all.filter((t) => t.is_padrao).length;
    const emUso = all.filter((t) => (t.pacientes_count || 0) > 0).length;
    return [
        { key: 'total', label: 'Total', value: all.length, cls: 'neutral' },
        { key: 'minhas', label: 'Minhas', value: minhas, cls: minhas > 0 ? 'accent' : 'neutral' },
        { key: 'uso', label: 'Em uso', value: emUso, cls: emUso > 0 ? 'ok' : 'neutral' },
        { key: 'padrao', label: 'Padrão', value: padrao, cls: padrao > 0 ? 'info' : 'neutral' }
    ];
});

const TIPO_FILTER_OPTIONS = [
    { key: 'padrao', label: 'Padrão', icon: 'pi pi-shield' },
    { key: 'mine', label: 'Minhas', icon: 'pi pi-user' }
];
const USO_FILTER_OPTIONS = [
    { key: 'em_uso', label: 'Em uso', icon: 'pi pi-users' },
    { key: 'vazio', label: 'Vazias', icon: 'pi pi-circle' }
];

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

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

// ── Filtragem ─────────────────────────────────────────────
const filtered = computed(() => {
    let list = tags.value;
    if (tipoFilter.value === 'padrao') list = list.filter((t) => !!t.is_padrao);
    if (tipoFilter.value === 'mine') list = list.filter((t) => !t.is_padrao);
    if (usoFilter.value === 'em_uso') list = list.filter((t) => (t.pacientes_count || 0) > 0);
    if (usoFilter.value === 'vazio') list = list.filter((t) => (t.pacientes_count || 0) === 0);
    const q = String(busca.value || '').trim().toLowerCase();
    if (q) {
        list = list.filter((t) => String(t.nome || '').toLowerCase().includes(q));
    }
    return list;
});

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

const pagedItems = computed(() =>
    filtered.value.slice(firstMT.value, firstMT.value + rowsMT.value)
);

// ── View mode (list / grid) ───────────────────────────────
const VIEW_MODE_KEY = 'mt.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 */ }
}

// ── Auth/tenant ───────────────────────────────────────────
async function getOwnerId() {
    const { data } = await supabase.auth.getUser();
    if (!data?.user?.id) throw new Error('Sessão não inicializada.');
    return data.user.id;
}
async function getActiveTenantId(uid) {
    const { data } = await supabase
        .from('tenant_members').select('tenant_id')
        .eq('user_id', uid).eq('status', 'active')
        .order('created_at', { ascending: false }).limit(1).single();
    if (!data?.tenant_id) throw new Error('Tenant não encontrado.');
    return data.tenant_id;
}

// ── Fetch ─────────────────────────────────────────────────
function normalize(r) {
    return {
        ...r,
        nome: r?.nome ?? r?.name ?? '',
        cor: r?.cor ?? r?.color ?? null,
        is_padrao: Boolean(r?.is_padrao ?? r?.is_native ?? false),
        pacientes_count: Number(r?.pacientes_count ?? r?.patient_count ?? 0)
    };
}
async function load() {
    loading.value = true;
    try {
        const ownerId = await getOwnerId();
        // Tenta a view agregada primeiro (já traz pacientes_count); se falhar
        // (RLS, view não existir), cai pra patient_tags + count manual.
        const v = await tenantDb().from('v_tag_patient_counts').select('*').eq('owner_id', ownerId).order('nome', { ascending: true });
        if (!v.error) {
            tags.value = (v.data || []).map(normalize);
            return;
        }
        const t = await tenantDb().from('patient_tags').select('*').eq('owner_id', ownerId);
        if (t.error) throw t.error;
        // Sem a view, busca o count via patient_patient_tag agrupado por tag_id.
        const ids = (t.data || []).map((x) => x.id);
        let counts = new Map();
        if (ids.length > 0) {
            const { data: vData } = await tenantDb().from('patient_patient_tag').select('tag_id').in('tag_id', ids);
            for (const r of vData || []) {
                counts.set(r.tag_id, (counts.get(r.tag_id) || 0) + 1);
            }
        }
        tags.value = (t.data || [])
            .map((r) => normalize({ ...r, pacientes_count: counts.get(r.id) || 0 }))
            .sort((a, b) => a.nome.localeCompare(b.nome));
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao carregar tags', detail: e?.message, life: 4500 });
    } finally {
        loading.value = false;
    }
}

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

// ── CRUD ──────────────────────────────────────────────────
const dlgOpen = ref(false);
const dlgMode = ref('create');
const dlgForm = ref({ id: '', nome: '', cor: '#22C55E' });
const dlgError = ref('');
const PRESET_COLORS = ['6366f1', '8b5cf6', 'ec4899', 'ef4444', 'f97316', 'eab308', '22c55e', '14b8a6', '3b82f6', '06b6d4', '64748b', '292524'];

function abrirCriar() {
    dlgMode.value = 'create';
    dlgForm.value = { id: '', nome: '', cor: '#22C55E' };
    dlgError.value = '';
    dlgOpen.value = true;
}
function abrirEditar(row) {
    if (row.is_padrao) {
        toast.add({ severity: 'info', summary: 'Tag padrão', detail: 'Não dá pra editar tags do sistema.', life: 2500 });
        return;
    }
    dlgMode.value = 'edit';
    dlgForm.value = {
        id: row.id,
        nome: row.nome || '',
        cor: row.cor ? (row.cor.startsWith('#') ? row.cor : '#' + row.cor) : '#22C55E'
    };
    dlgError.value = '';
    dlgOpen.value = true;
}
function onRowClick(event) {
    if (event?.data && !event.data.is_padrao) abrirEditar(event.data);
}

async function salvar() {
    const nome = String(dlgForm.value.nome || '').trim();
    if (!nome) {
        dlgError.value = 'Informe um nome.';
        return;
    }
    saving.value = true;
    dlgError.value = '';
    try {
        const ownerId = await getOwnerId();
        const cor = dlgForm.value.cor.startsWith('#') ? dlgForm.value.cor : '#' + dlgForm.value.cor;
        if (dlgMode.value === 'create') {
            const tenantId = await getActiveTenantId(ownerId);
            const { error } = await tenantDb().from('patient_tags').insert({
                owner_id: ownerId, nome, cor
            });
            if (error) throw error;
            toast.add({ severity: 'success', summary: 'Tag criada', life: 2200 });
        } else {
            const { error } = await tenantDb().from('patient_tags')
                .update({ nome, cor, updated_at: new Date().toISOString() })
                .eq('id', dlgForm.value.id).eq('owner_id', ownerId);
            if (error) throw error;
            toast.add({ severity: 'success', summary: 'Tag atualizada', life: 2200 });
        }
        dlgOpen.value = false;
        await load();
    } catch (e) {
        const msg = e?.message || '';
        dlgError.value = (e?.code === '23505' || /duplicate/i.test(msg)) ? 'Já existe uma tag com esse nome.' : (msg || 'Falha ao salvar.');
    } finally {
        saving.value = false;
    }
}

function confirmarExcluir(row) {
    if (row.is_padrao) return;
    confirm.require({
        message: `Excluir a tag "${row.nome}"? Os vínculos com pacientes também serão removidos.`,
        header: 'Confirmar exclusão',
        icon: 'pi pi-exclamation-triangle',
        acceptLabel: 'Excluir',
        rejectLabel: 'Cancelar',
        acceptSeverity: 'danger',
        accept: () => excluir(row)
    });
}
async function excluir(row) {
    saving.value = true;
    try {
        const ownerId = await getOwnerId();
        await tenantDb().from('patient_patient_tag').delete().eq('tag_id', row.id);
        const { error } = await tenantDb().from('patient_tags').delete().eq('id', row.id).eq('owner_id', ownerId);
        if (error) throw error;
        toast.add({ severity: 'success', summary: 'Tag excluída', life: 2200 });
        await load();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao excluir.', life: 4000 });
    } finally {
        saving.value = false;
    }
}

// ── Helpers de formatação (pra dialog "Pacientes da tag") ─────
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;
}

// ── Dialog: Pacientes da tag ──────────────────────────────────
// Espelha o pattern de MelissaGrupos: click na coluna "Pacientes" abre
// dialog com a lista vinculada via patient_patient_tag.
const patientsDialog = reactive({
    open: false,
    loading: false,
    error: '',
    tag: 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)
    );
});

const patientsTagHex = computed(() => {
    if (!patientsDialog.tag) return '#22c55e';
    const c = patientsDialog.tag.cor || '#22c55e';
    return c.startsWith('#') ? c : '#' + c;
});

async function openTagPatientsModal(tagRow) {
    if (!tagRow) return;
    patientsDialog.open = true;
    patientsDialog.loading = true;
    patientsDialog.error = '';
    patientsDialog.tag = tagRow;
    patientsDialog.items = [];
    patientsDialog.search = '';
    try {
        const { data, error } = await tenantDb().from('patient_patient_tag')
            .select('tag_id, patient:patients(id, nome_completo, email_principal, telefone, avatar_url)')
            .eq('tag_id', tagRow.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 (e) {
        patientsDialog.error = e?.message || 'Erro ao carregar pacientes da tag.';
    } 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="mt-mobile-drawer"
        :class="{ 'is-open': drawerOpen }"
        v-show="isMobile"
        aria-label="Estatísticas e filtros"
    >
        <div id="mt-mobile-drawer-target" class="mt-mobile-drawer__scroll" />
    </aside>
    <Transition name="mt-drawer-fade">
        <div
            v-if="isMobile && drawerOpen"
            class="mt-mobile-drawer__backdrop"
            @click="fecharDrawer"
        />
    </Transition>

    <section class="mt-page">
        <header class="mt-page__head">
            <button
                class="mt-menu-btn mt-menu-btn--mobile-only"
                v-tooltip.bottom="'Estatísticas & filtros'"
                @click="toggleDrawer"
            >
                <i class="pi pi-bars" />
                <span>Menu Tags</span>
            </button>
            <div class="mt-page__title">
                <i class="pi pi-tag mt-page__title-icon" />
                <span>Tags</span>
                <span class="mt-page__count">{{ filtered.length }}</span>
            </div>
            <div class="mt-page__actions">
                <button
                    class="mt-act-btn mt-act-btn--primary"
                    v-tooltip.bottom="'Nova tag'"
                    :disabled="loading"
                    @click="abrirCriar"
                >
                    <i :class="saving ? 'pi pi-spin pi-spinner' : 'pi pi-plus'" />
                    <span>Nova</span>
                </button>
                <button
                    class="mt-head-btn"
                    v-tooltip.bottom="'Recarregar'"
                    :disabled="loading"
                    @click="load"
                >
                    <i :class="loading ? 'pi pi-spin pi-spinner' : 'pi pi-refresh'" />
                </button>
                <button class="mt-close" v-tooltip.bottom="'Voltar (Esc)'" @click="emit('close')">
                    <i class="pi pi-times" />
                </button>
            </div>
        </header>

        <!-- Subheader explicativo (blueprint §9) -->
        <div class="mt-subheader">
            <i class="pi pi-info-circle mt-subheader__icon" />
            <span class="mt-subheader__text">
                Marcadores rápidos pra classificar pacientes (ex: TDAH, VIP, Convênio).
                <strong>Crie tags próprias</strong> com cor identificadora — diferente de
                grupos, tags são <strong>per-usuário</strong> e podem ser combinadas.
            </span>
        </div>

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

                    <!-- Filtro de tipo -->
                    <div class="mt-w mt-w--side">
                        <div class="mt-w__head">
                            <span class="mt-w__title"><i class="pi pi-filter" /> Tipo</span>
                            <button
                                v-if="tipoFilter"
                                class="mt-side__clear-inline"
                                v-tooltip.top="'Limpar filtro de tipo'"
                                aria-label="Limpar filtro de tipo"
                                @click="tipoFilter = ''"
                            >
                                <i class="pi pi-times" />
                            </button>
                        </div>
                        <div class="mt-side__list">
                            <button
                                v-for="o in TIPO_FILTER_OPTIONS"
                                :key="o.key"
                                class="mt-side__item"
                                :class="[`is-tipo-${o.key}`, { 'is-active': tipoFilter === o.key }]"
                                @click="toggleTipoFilter(o.key)"
                            >
                                <i :class="o.icon" />
                                <span>{{ o.label }}</span>
                            </button>
                        </div>
                    </div>

                    <!-- Filtro de uso -->
                    <div class="mt-w mt-w--side">
                        <div class="mt-w__head">
                            <span class="mt-w__title"><i class="pi pi-users" /> Uso</span>
                            <button
                                v-if="usoFilter"
                                class="mt-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="mt-side__list">
                            <button
                                v-for="o in USO_FILTER_OPTIONS"
                                :key="o.key"
                                class="mt-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="mt-clear">
                    <div v-if="hasActiveFilters" class="mt-side__footer">
                        <button class="mt-side__clear-all" @click="clearAllFilters">
                            <i class="pi pi-filter-slash" />
                            <span>Limpar filtros</span>
                        </button>
                    </div>
                </Transition>
            </aside>
            </Teleport>

            <div class="mt-main">
                <!-- Toolbar (busca + view toggle) -->
                <div class="mt-toolbar">
                    <div class="mt-search">
                        <i class="pi pi-search mt-search__icon" />
                        <input
                            v-model="busca"
                            type="text"
                            placeholder="Buscar por nome…"
                            class="mt-search__input"
                        />
                        <button
                            v-if="busca"
                            class="mt-search__clear"
                            v-tooltip.bottom="'Limpar busca'"
                            @click="busca = ''"
                        >
                            <i class="pi pi-times" />
                        </button>
                    </div>
                    <div class="mt-view-toggle" role="group" aria-label="Visualização">
                        <button
                            class="mt-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="mt-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="rowsMT"
                    :first="firstMT"
                    :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: 600px"
                    class="mt-table"
                    @row-click="onRowClick"
                    @page="onPage"
                >
                    <Column header="Tag" style="min-width: 280px">
                        <template #body="{ data }">
                            <div class="mt-row__tag">
                                <span class="mt-row__dot" :style="{ background: data.cor || '#64748b' }" />
                                <div class="mt-row__main">
                                    <div class="mt-row__name-row">
                                        <span class="mt-row__name">{{ data.nome }}</span>
                                        <span v-if="data.is_padrao" class="mt-row__badge mt-row__badge--padrao">
                                            <i class="pi pi-shield" /> Padrão
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </Column>

                    <Column header="Pacientes" style="width: 180px; min-width: 160px">
                        <template #body="{ data }">
                            <button
                                type="button"
                                class="mt-row__count-btn"
                                :class="{ 'is-empty': data.pacientes_count === 0 }"
                                :disabled="data.pacientes_count === 0"
                                v-tooltip.top="data.pacientes_count > 0 ? 'Ver pacientes da tag' : 'Sem pacientes vinculados'"
                                aria-label="Ver pacientes da tag"
                                @click.stop="openTagPatientsModal(data)"
                            >
                                <i class="pi pi-users" />
                                <span>
                                    {{ data.pacientes_count }}
                                    {{ data.pacientes_count === 1 ? 'paciente' : 'pacientes' }}
                                </span>
                            </button>
                        </template>
                    </Column>

                    <Column
                        header=""
                        :style="{ width: '100px', maxWidth: '100px', minWidth: '100px' }"
                        frozen
                        alignFrozen="right"
                        class="mt-col-acoes"
                    >
                        <template #body="{ data }">
                            <div class="mt-row__actions" @click.stop>
                                <button
                                    v-if="!data.is_padrao"
                                    class="mt-row__btn"
                                    v-tooltip.left="'Editar'"
                                    aria-label="Editar"
                                    @click.stop="abrirEditar(data)"
                                >
                                    <i class="pi pi-pencil" />
                                </button>
                                <button
                                    v-if="!data.is_padrao"
                                    class="mt-row__btn mt-row__btn--danger"
                                    v-tooltip.left="'Excluir'"
                                    aria-label="Excluir"
                                    @click.stop="confirmarExcluir(data)"
                                >
                                    <i class="pi pi-trash" />
                                </button>
                                <span v-else class="mt-row__locked" v-tooltip.left="'Tag padrão (bloqueada)'">
                                    <i class="pi pi-lock" />
                                </span>
                            </div>
                        </template>
                    </Column>

                    <template #empty>
                        <div class="mt-empty">
                            <i class="pi pi-tag mt-empty__icon" />
                            <div class="mt-empty__title">Nenhuma tag encontrada</div>
                            <div class="mt-empty__hint">
                                <template v-if="busca || tipoFilter || usoFilter">
                                    Ajuste os filtros pra ver mais resultados.
                                </template>
                                <template v-else>
                                    Crie sua primeira tag pra organizar pacientes.
                                </template>
                            </div>
                            <button class="mt-act-btn mt-act-btn--primary mt-empty__btn" @click="abrirCriar">
                                <i class="pi pi-plus" />
                                <span>Nova tag</span>
                            </button>
                        </div>
                    </template>

                    <template #loading>
                        <div class="mt-table__loading">
                            <i class="pi pi-spin pi-spinner" />
                            <span>Carregando tags…</span>
                        </div>
                    </template>
                </DataTable>

                <!-- View Grade -->
                <div v-else-if="viewMode === 'grid'" class="mt-grid-wrap">
                    <div v-if="loading && filtered.length === 0" class="mt-table__loading mt-grid__loading">
                        <i class="pi pi-spin pi-spinner" />
                        <span>Carregando tags…</span>
                    </div>
                    <div v-else-if="filtered.length === 0" class="mt-empty">
                        <i class="pi pi-tag mt-empty__icon" />
                        <div class="mt-empty__title">Nenhuma tag encontrada</div>
                        <div class="mt-empty__hint">
                            <template v-if="busca || tipoFilter || usoFilter">
                                Ajuste os filtros pra ver mais resultados.
                            </template>
                            <template v-else>
                                Crie sua primeira tag pra organizar pacientes.
                            </template>
                        </div>
                    </div>
                    <div v-else class="mt-grid">
                        <div
                            v-for="t in pagedItems"
                            :key="t.id"
                            class="mt-grid__card"
                            :class="rowStatusClass(t)"
                            role="button"
                            tabindex="0"
                            @click="abrirEditar(t)"
                            @keydown.enter.prevent="abrirEditar(t)"
                            @keydown.space.prevent="abrirEditar(t)"
                        >
                            <div class="mt-grid__top">
                                <span class="mt-grid__dot" :style="{ background: t.cor || '#64748b' }" />
                                <span v-if="t.is_padrao" class="mt-row__badge mt-row__badge--padrao">
                                    <i class="pi pi-shield" /> Padrão
                                </span>
                            </div>
                            <div class="mt-grid__name">{{ t.nome }}</div>
                            <div class="mt-grid__meta" @click.stop>
                                <button
                                    type="button"
                                    class="mt-row__count-btn"
                                    :class="{ 'is-empty': t.pacientes_count === 0 }"
                                    :disabled="t.pacientes_count === 0"
                                    v-tooltip.top="t.pacientes_count > 0 ? 'Ver pacientes da tag' : 'Sem pacientes vinculados'"
                                    aria-label="Ver pacientes da tag"
                                    @click.stop="openTagPatientsModal(t)"
                                >
                                    <i class="pi pi-users" />
                                    <span>
                                        {{ t.pacientes_count }}
                                        {{ t.pacientes_count === 1 ? 'paciente' : 'pacientes' }}
                                    </span>
                                </button>
                            </div>
                            <div class="mt-grid__footer" @click.stop>
                                <button
                                    v-if="!t.is_padrao"
                                    class="mt-row__btn"
                                    v-tooltip.top="'Editar'"
                                    aria-label="Editar"
                                    @click.stop="abrirEditar(t)"
                                >
                                    <i class="pi pi-pencil" />
                                </button>
                                <button
                                    v-if="!t.is_padrao"
                                    class="mt-row__btn mt-row__btn--danger"
                                    v-tooltip.top="'Excluir'"
                                    aria-label="Excluir"
                                    @click.stop="confirmarExcluir(t)"
                                >
                                    <i class="pi pi-trash" />
                                </button>
                                <span v-else class="mt-row__locked" v-tooltip.top="'Tag padrão (bloqueada)'">
                                    <i class="pi pi-lock" />
                                </span>
                            </div>
                        </div>
                    </div>
                    <Paginator
                        v-if="filtered.length > 0"
                        class="mt-paginator"
                        :rows="rowsMT"
                        :totalRecords="filtered.length"
                        :first="firstMT"
                        :rowsPerPageOptions="PAGE_SIZE_OPTIONS"
                        template="RowsPerPageDropdown FirstPageLink PrevPageLink CurrentPageReport NextPageLink LastPageLink"
                        currentPageReportTemplate="{first}–{last} de {totalRecords}"
                        @page="onPage"
                    />
                </div>
            </div>
        </div>

        <!-- Dialog: criar/editar tag — pattern espelhado do
             PatientsCadastroPage Identidade (FloatLabel + IconField +
             variant="filled" + section dividers uppercase). -->
        <Dialog
            v-model:visible="dlgOpen"
            modal
            dismissable-mask
            :draggable="false"
            :style="{ width: '480px', maxWidth: '94vw' }"
            :header="dlgMode === 'create' ? 'Nova tag' : 'Editar tag'"
        >
            <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)]">
                        Tag
                    </span>
                    <div class="flex-1 h-px bg-[color-mix(in_srgb,var(--p-primary-color)_25%,transparent)]" />
                </div>
                <div class="mb-6">
                    <FloatLabel variant="on">
                        <IconField>
                            <InputIcon class="pi pi-tag" />
                            <InputText
                                id="tag-nome"
                                v-model="dlgForm.nome"
                                class="w-full"
                                variant="filled"
                                autofocus
                                @keydown.enter="salvar"
                            />
                        </IconField>
                        <label for="tag-nome">Nome da tag *</label>
                    </FloatLabel>
                </div>

                <!-- ── Cor identificadora ────────────────────── -->
                <div class="flex items-center gap-2 mb-4">
                    <span class="text-[0.7rem] font-bold uppercase tracking-widest text-[var(--p-primary-color)]">
                        Cor
                    </span>
                    <div class="flex-1 h-px bg-[color-mix(in_srgb,var(--p-primary-color)_25%,transparent)]" />
                </div>
                <div class="flex items-center gap-3 mb-4">
                    <input
                        v-model="dlgForm.cor"
                        type="color"
                        class="h-10 w-14 rounded-lg border border-[var(--surface-border)] bg-transparent cursor-pointer"
                    />
                    <span class="text-[0.82rem] font-mono text-[var(--text-color-secondary)] uppercase">
                        {{ dlgForm.cor }}
                    </span>
                </div>
                <div class="flex flex-wrap gap-2">
                    <button
                        v-for="c in PRESET_COLORS"
                        :key="c"
                        type="button"
                        class="mt-color-preset"
                        :class="{ 'is-selected': dlgForm.cor.toLowerCase() === '#' + c }"
                        :style="{ background: '#' + c }"
                        :aria-label="`Usar cor #${c}`"
                        @click="dlgForm.cor = '#' + c"
                    />
                </div>

                <small
                    v-if="dlgError"
                    class="mt-4 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 da tag -->
        <Dialog
            v-model:visible="patientsDialog.open"
            modal
            dismissable-mask
            :draggable="false"
            :style="{ width: '720px', maxWidth: '94vw' }"
            :pt="{
                root: { style: `border: 2px solid ${patientsTagHex}` },
                header: { style: `border-bottom: 1px solid ${patientsTagHex}30` },
                pcCloseButton: { root: { class: 'mt-pdlg-close-btn' } }
            }"
        >
            <template #header>
                <div class="mt-pdlg__header">
                    <span class="mt-pdlg__avatar" :style="{ background: patientsTagHex }">
                        <i class="pi pi-tag" />
                    </span>
                    <div class="mt-pdlg__title">
                        <div class="mt-pdlg__name" :style="{ color: patientsTagHex }">
                            Tag — {{ patientsDialog.tag?.nome }}
                        </div>
                        <div class="mt-pdlg__sub">
                            {{ patientsDialog.items.length }}
                            paciente{{ patientsDialog.items.length !== 1 ? 's' : '' }}
                        </div>
                    </div>
                </div>
            </template>

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

                <div
                    v-if="patientsDialog.loading"
                    class="mt-pdlg__loading"
                    :style="{ color: patientsTagHex }"
                >
                    <i class="pi pi-spin pi-spinner" />
                    <span>Carregando pacientes…</span>
                </div>

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

                <div v-else-if="patientsDialog.items.length === 0" class="mt-pdlg__empty">
                    <div
                        class="mt-pdlg__empty-icon"
                        :style="{ background: `${patientsTagHex}18`, color: patientsTagHex }"
                    >
                        <i class="pi pi-users" />
                    </div>
                    <div class="mt-pdlg__empty-title">Nenhum paciente com esta tag</div>
                    <div class="mt-pdlg__empty-hint">
                        Aplique a tag a pacientes na página de pacientes.
                    </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="mt-pdlg__table"
                >
                    <Column header="Paciente" sortable>
                        <template #body="{ data }">
                            <div class="mt-pdlg__patient">
                                <span
                                    class="mt-pdlg__avatar mt-pdlg__avatar--sm"
                                    :style="data.avatar_url ? null : { background: `${patientsTagHex}25`, color: patientsTagHex }"
                                >
                                    <img v-if="data.avatar_url" :src="data.avatar_url" :alt="data.full_name" />
                                    <span v-else>{{ initials(data.full_name) }}</span>
                                </span>
                                <div class="mt-pdlg__patient-text">
                                    <span class="mt-pdlg__patient-name">{{ data.full_name }}</span>
                                    <span class="mt-pdlg__patient-email">{{ data.email || '—' }}</span>
                                </div>
                            </div>
                        </template>
                    </Column>

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

                    <Column header="" style="width: 7rem">
                        <template #body="{ data }">
                            <button
                                type="button"
                                class="mt-pdlg__open-btn"
                                :style="{ borderColor: patientsTagHex, color: patientsTagHex }"
                                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="mt-pdlg__empty">
                            <i class="pi pi-search mt-pdlg__empty-icon-pi" />
                            <div class="mt-pdlg__empty-title">Nenhum resultado</div>
                            <div class="mt-pdlg__empty-hint">
                                Nenhum paciente corresponde à busca.
                            </div>
                            <button
                                class="mt-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 ─── */
.mt-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: mt-page-enter 240ms cubic-bezier(0.2, 0.7, 0.3, 1);
}
@keyframes mt-page-enter {
    from { opacity: 0; transform: scale(0.985); }
    to   { opacity: 1; transform: scale(1); }
}

.mt-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;
}
.mt-page__title {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1rem;
    font-weight: 500;
}
.mt-page__title-icon {
    color: var(--p-primary-color);
    font-size: 1.05rem;
}
.mt-page__title > span:not(.mt-page__count) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mt-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;
}
.mt-page__actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

.mt-close, .mt-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;
}
.mt-close:hover, .mt-head-btn:hover { background: var(--m-bg-soft-hover); }
.mt-head-btn > i { font-size: 0.85rem; }

.mt-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);
}
.mt-act-btn--primary {
    background: var(--m-accent);
    border-color: var(--m-accent);
    color: white;
}
.mt-act-btn--primary:hover {
    background: color-mix(in srgb, var(--m-accent) 88%, white);
    transform: translateY(-1px);
}
.mt-act-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
.mt-act-btn > i { font-size: 0.78rem; }

.mt-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;
}
.mt-menu-btn:hover {
    background: color-mix(in srgb, var(--m-accent) 88%, white);
    transform: translateY(-1px);
}

.mt-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;
}
.mt-subheader__icon {
    color: var(--p-primary-color);
    font-size: 0.92rem;
    flex-shrink: 0;
    margin-top: 1px;
}
.mt-subheader__text { flex: 1; min-width: 0; }
.mt-subheader__text strong { color: var(--m-text); font-weight: 600; }

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

/* ─── Sidebar ─── */
.mt-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;
}
.mt-side__scroll {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
}
.mt-side__scroll::-webkit-scrollbar { width: 5px; }
.mt-side__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

.mt-side__footer {
    flex-shrink: 0;
    padding: 12px;
    background: var(--m-bg-soft);
    border-top: 1px solid var(--m-border);
}
.mt-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;
}
.mt-side__clear-all:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    color: var(--m-text);
}
.mt-side__clear-all > i {
    font-size: 0.78rem;
    color: var(--m-text-muted);
    transition: color 140ms ease;
}
.mt-side__clear-all:hover > i { color: var(--m-text); }

.mt-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;
}
.mt-side__clear-inline:hover {
    background: rgba(220, 38, 38, 0.10);
    border-color: rgba(220, 38, 38, 0.55);
}
.mt-side__clear-inline > i { font-size: 0.6rem; }

.mt-w {
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    border-radius: 12px;
    padding: 12px;
}
.mt-w--side {
    margin: 12px 12px 0;
    flex-shrink: 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}
.mt-w--side:last-of-type { margin-bottom: 12px; }
.mt-w__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}
.mt-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;
}
.mt-w__title > i { color: var(--m-text-muted); font-size: 0.7rem; }

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

/* ─── Filter buttons ─── */
.mt-side__list {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.mt-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;
}
.mt-side__item > i {
    font-size: 0.78rem;
    width: 14px;
    text-align: center;
}

/* Tipo: Padrão = blue-600, Minhas = accent */
.mt-side__item.is-tipo-padrao {
    background: rgba(37, 99, 235, 0.05);
    border-color: rgba(37, 99, 235, 0.18);
}
.mt-side__item.is-tipo-padrao > i { color: rgb(37, 99, 235); }
.mt-side__item.is-tipo-padrao:hover {
    background: rgba(37, 99, 235, 0.10);
    border-color: rgba(37, 99, 235, 0.30);
}
.mt-side__item.is-active.is-tipo-padrao {
    background: rgba(37, 99, 235, 0.16);
    border-color: rgba(37, 99, 235, 0.55);
    box-shadow: 0 0 0 1px rgba(37, 99, 235, 0.35);
}

.mt-side__item.is-tipo-mine {
    background: color-mix(in srgb, var(--m-accent) 5%, transparent);
    border-color: color-mix(in srgb, var(--m-accent) 18%, transparent);
}
.mt-side__item.is-tipo-mine > i { color: var(--m-accent); }
.mt-side__item.is-tipo-mine:hover {
    background: color-mix(in srgb, var(--m-accent) 10%, transparent);
    border-color: color-mix(in srgb, var(--m-accent) 30%, transparent);
}
.mt-side__item.is-active.is-tipo-mine {
    background: color-mix(in srgb, var(--m-accent) 16%, transparent);
    border-color: color-mix(in srgb, var(--m-accent) 55%, transparent);
    box-shadow: 0 0 0 1px color-mix(in srgb, var(--m-accent) 35%, transparent);
}

/* Uso: Em uso = green-600, Vazio = amber-600 */
.mt-side__item.is-uso-em_uso {
    background: rgba(22, 163, 74, 0.05);
    border-color: rgba(22, 163, 74, 0.18);
}
.mt-side__item.is-uso-em_uso > i { color: rgb(22, 163, 74); }
.mt-side__item.is-uso-em_uso:hover {
    background: rgba(22, 163, 74, 0.10);
    border-color: rgba(22, 163, 74, 0.30);
}
.mt-side__item.is-active.is-uso-em_uso {
    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);
}

.mt-side__item.is-uso-vazio {
    background: rgba(217, 119, 6, 0.05);
    border-color: rgba(217, 119, 6, 0.18);
}
.mt-side__item.is-uso-vazio > i { color: rgb(217, 119, 6); }
.mt-side__item.is-uso-vazio:hover {
    background: rgba(217, 119, 6, 0.10);
    border-color: rgba(217, 119, 6, 0.30);
}
.mt-side__item.is-active.is-uso-vazio {
    background: rgba(217, 119, 6, 0.16);
    border-color: rgba(217, 119, 6, 0.55);
    box-shadow: 0 0 0 1px rgba(217, 119, 6, 0.35);
}

/* Transition do footer "Limpar filtros" */
.mt-clear-enter-active,
.mt-clear-leave-active {
    transition: opacity 220ms ease, transform 220ms ease, max-height 240ms ease;
    overflow: hidden;
}
.mt-clear-enter-from,
.mt-clear-leave-to {
    opacity: 0;
    transform: translateY(6px);
    max-height: 0;
}
.mt-clear-enter-to,
.mt-clear-leave-from {
    opacity: 1;
    transform: translateY(0);
    max-height: 80px;
}

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

.mt-toolbar {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}
.mt-search {
    position: relative;
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
}
.mt-search__icon {
    position: absolute;
    left: 12px;
    color: var(--m-text-muted);
    font-size: 0.78rem;
    pointer-events: none;
}
.mt-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;
}
.mt-search__input::placeholder { color: var(--m-text-faint); }
.mt-search__input:focus {
    border-color: var(--m-border-strong);
    background: var(--m-bg-medium);
}
.mt-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;
}
.mt-search__clear:hover {
    background: var(--m-bg-soft-hover);
    color: var(--m-text);
}
.mt-search__clear > i { font-size: 0.7rem; }

.mt-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;
}
.mt-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;
}
.mt-view-toggle__btn:hover {
    background: var(--m-bg-soft-hover);
    color: var(--m-text);
}
.mt-view-toggle__btn.is-active {
    background: var(--m-accent-soft);
    color: var(--m-accent);
}
.mt-view-toggle__btn > i { font-size: 0.85rem; }

/* ─── DataTable ─── */
.mt-table {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
}
.mt-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;
}
.mt-table :deep(.p-datatable-table-container) {
    flex: 1;
    min-height: 0;
    background: transparent;
}
.mt-table :deep(.p-datatable-thead),
.mt-table :deep(.p-datatable-thead > tr) {
    background: transparent !important;
}
.mt-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);
}
.mt-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);
}
.mt-table :deep(.p-datatable-tbody > tr > td) {
    padding: 10px 14px;
    border-bottom: 1px solid var(--m-border);
    background: transparent;
    vertical-align: middle;
}
.mt-table :deep(.p-datatable-tbody > tr:hover) {
    background: var(--m-bg-soft-hover);
}
.mt-table :deep(.p-datatable-tbody > tr.p-datatable-row-selected) {
    background: var(--m-accent-soft);
}
.mt-table :deep(.p-datatable-tbody > tr.is-padrao)  { border-left-color: rgb(37, 99, 235); cursor: default; }
.mt-table :deep(.p-datatable-tbody > tr.is-em-uso)  { border-left-color: rgb(22, 163, 74); }
.mt-table :deep(.p-datatable-tbody > tr.is-vazio)   { border-left-color: var(--m-border-strong); }

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

.mt-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;
}
.mt-table :deep(.p-paginator-current) {
    color: var(--m-text-muted);
    font-size: 0.78rem;
    background: transparent;
    border: none;
    padding: 0 6px;
}
.mt-table :deep(.p-paginator-first),
.mt-table :deep(.p-paginator-prev),
.mt-table :deep(.p-paginator-next),
.mt-table :deep(.p-paginator-last),
.mt-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;
}
.mt-table :deep(.p-paginator-page.p-paginator-page-selected) {
    background: var(--m-accent-soft);
    border-color: var(--m-accent-strong);
    color: var(--m-accent);
}
.mt-table :deep(.p-paginator-first:not(.p-disabled):hover),
.mt-table :deep(.p-paginator-prev:not(.p-disabled):hover),
.mt-table :deep(.p-paginator-next:not(.p-disabled):hover),
.mt-table :deep(.p-paginator-last:not(.p-disabled):hover),
.mt-table :deep(.p-paginator-page:not(.p-paginator-page-selected):hover) {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
}
.mt-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;
}
.mt-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;
}

.mt-table :deep(td.p-datatable-frozen-column),
.mt-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;
}
.mt-table :deep(.p-datatable-tbody > tr:hover td.p-datatable-frozen-column) {
    background: var(--m-bg-soft-hover);
}
.mt-table :deep(.p-datatable-tbody > tr.p-datatable-row-selected td.p-datatable-frozen-column) {
    background: var(--m-accent-soft);
}

/* ─── Row content (design preservado) ─── */
.mt-row__tag {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
}
.mt-row__dot {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    flex-shrink: 0;
    border: 1px solid rgba(255, 255, 255, 0.15);
    box-shadow: 0 0 0 2px color-mix(in srgb, var(--p-content-background) 60%, transparent);
}
.mt-row__main {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 2px;
}
.mt-row__name-row {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}
.mt-row__name {
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--m-text);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.mt-row__badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: 0.62rem;
    font-weight: 600;
    padding: 2px 8px;
    border-radius: 999px;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    border: 1px solid;
    flex-shrink: 0;
}
.mt-row__badge--padrao {
    color: rgb(37, 99, 235);
    background: rgba(37, 99, 235, 0.12);
    border-color: rgba(37, 99, 235, 0.3);
}
.mt-row__badge > i { font-size: 0.55rem; }

/* Botão "X pacientes" clicável (lista + grid) */
.mt-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;
}
.mt-row__count-btn:hover:not(:disabled) {
    background: color-mix(in srgb, var(--p-primary-color) 12%, transparent);
    border-color: var(--p-primary-color);
}
.mt-row__count-btn:focus-visible {
    outline: 2px solid var(--p-primary-color);
    outline-offset: 2px;
}
.mt-row__count-btn.is-empty,
.mt-row__count-btn:disabled {
    color: var(--m-text-muted);
    border-color: var(--m-border);
    cursor: default;
    background: transparent;
}
.mt-row__count-btn > i { font-size: 0.7rem; }

.mt-row__actions {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 6px;
    flex-shrink: 0;
}
.mt-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;
}
.mt-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);
}
.mt-row__btn--danger:hover {
    background: rgba(220, 38, 38, 0.12);
    border-color: rgba(220, 38, 38, 0.5);
    color: rgb(220, 38, 38);
}
.mt-row__btn:disabled { opacity: 0.4; cursor: not-allowed; }
.mt-row__btn > i { font-size: 0.7rem; }

.mt-row__locked {
    width: 28px;
    height: 28px;
    display: grid;
    place-items: center;
    color: var(--m-text-faint);
    font-size: 0.7rem;
}

/* ─── Grid view ─── */
.mt-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;
}
.mt-grid {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    padding: 12px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 10px;
    align-content: start;
}
.mt-grid::-webkit-scrollbar { width: 5px; }
.mt-grid::-webkit-scrollbar-thumb { background: var(--m-border-strong); border-radius: 3px; }
.mt-grid__loading {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 32px;
}
.mt-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;
}
.mt-grid__card:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    transform: translateY(-1px);
}
.mt-grid__card:focus-visible {
    outline: 2px solid var(--p-primary-color);
    outline-offset: 2px;
}
.mt-grid__card.is-padrao  { border-left-color: rgb(37, 99, 235); cursor: default; }
.mt-grid__card.is-padrao:hover { transform: none; }
.mt-grid__card.is-em-uso  { border-left-color: rgb(22, 163, 74); }
.mt-grid__card.is-vazio   { border-left-color: var(--m-border-strong); }

.mt-grid__top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
}
.mt-grid__dot {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    flex-shrink: 0;
    border: 1px solid rgba(255, 255, 255, 0.15);
}
.mt-grid__name {
    font-size: 0.95rem;
    font-weight: 600;
    color: var(--m-text);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mt-grid__meta {
    margin-top: auto;
    padding-top: 4px;
}
.mt-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;
    min-height: 36px;
}

/* Paginator standalone (grid) */
.mt-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;
}
.mt-paginator.p-paginator .p-paginator-current {
    color: var(--m-text-muted);
    font-size: 0.78rem;
    background: transparent;
    border: none;
    padding: 0 6px;
}
.mt-paginator.p-paginator .p-paginator-first,
.mt-paginator.p-paginator .p-paginator-prev,
.mt-paginator.p-paginator .p-paginator-next,
.mt-paginator.p-paginator .p-paginator-last,
.mt-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;
}
.mt-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);
}
.mt-paginator.p-paginator .p-paginator-first:not(.p-disabled):hover,
.mt-paginator.p-paginator .p-paginator-prev:not(.p-disabled):hover,
.mt-paginator.p-paginator .p-paginator-next:not(.p-disabled):hover,
.mt-paginator.p-paginator .p-paginator-last:not(.p-disabled):hover,
.mt-paginator.p-paginator .p-paginator-page:not(.p-paginator-page-selected):hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
}
.mt-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;
}
.mt-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 ─── */
.mt-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;
}
.mt-empty__icon { font-size: 2rem; color: var(--m-text-faint); margin-bottom: 4px; }
.mt-empty__title { font-size: 0.92rem; font-weight: 600; color: var(--m-text); }
.mt-empty__hint { font-size: 0.78rem; }
.mt-empty__btn { margin-top: 8px; }

/* ─── Dialog "Pacientes da tag" ─── */
.mt-pdlg__header {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
}
.mt-pdlg__avatar {
    width: 36px;
    height: 36px;
    display: grid;
    place-items: center;
    border-radius: 8px;
    color: white;
    font-weight: 700;
    font-size: 0.95rem;
    flex-shrink: 0;
    overflow: hidden;
}
.mt-pdlg__avatar > i { color: white; font-size: 1rem; }
.mt-pdlg__avatar--sm {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    font-size: 0.78rem;
    border: 1px solid color-mix(in srgb, currentColor 20%, transparent);
}
.mt-pdlg__avatar img { width: 100%; height: 100%; object-fit: cover; }
.mt-pdlg__title {
    display: flex;
    flex-direction: column;
    gap: 2px;
    min-width: 0;
}
.mt-pdlg__name {
    font-size: 1rem;
    font-weight: 700;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mt-pdlg__sub {
    font-size: 0.72rem;
    color: var(--m-text-muted);
}

.mt-pdlg__body {
    display: flex;
    flex-direction: column;
    gap: 14px;
}
.mt-pdlg__toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    flex-wrap: wrap;
}
.mt-pdlg__search {
    flex: 1;
    min-width: 200px;
    max-width: 320px;
}
.mt-pdlg__count-pill {
    padding: 4px 10px;
    border-radius: 999px;
    font-size: 0.72rem;
    font-weight: 600;
    flex-shrink: 0;
}

.mt-pdlg__loading {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 20px;
    font-size: 0.85rem;
    justify-content: center;
}
.mt-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;
}

.mt-pdlg__empty {
    padding: 36px 20px;
    text-align: center;
    color: var(--m-text-muted);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
}
.mt-pdlg__empty-icon {
    width: 48px;
    height: 48px;
    display: grid;
    place-items: center;
    border-radius: 10px;
    margin-bottom: 8px;
    font-size: 1.4rem;
}
.mt-pdlg__empty-icon-pi {
    font-size: 1.6rem;
    opacity: 0.4;
    margin-bottom: 8px;
}
.mt-pdlg__empty-title {
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--m-text);
}
.mt-pdlg__empty-hint { font-size: 0.78rem; }
.mt-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;
}
.mt-pdlg__inline-clear-btn:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    color: var(--m-text);
}

.mt-pdlg__table :deep(.p-datatable) {
    background: transparent;
    border: 1px solid var(--m-border);
    border-radius: 10px;
    overflow: hidden;
}
.mt-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);
}
.mt-pdlg__table :deep(.p-datatable-tbody > tr > td) {
    padding: 10px 12px;
    border-bottom: 1px solid var(--m-border);
    background: transparent;
    vertical-align: middle;
}
.mt-pdlg__table :deep(.p-datatable-tbody > tr:hover) {
    background: var(--m-bg-soft-hover);
}
.mt-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;
}

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

/* ─── Drawer mobile ─── */
.mt-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;
}
.mt-mobile-drawer.is-open { transform: translateX(0); }
.mt-mobile-drawer__scroll {
    flex: 1;
    min-height: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}
.mt-mobile-drawer__scroll .mt-side {
    flex: 1;
    min-height: 0;
    width: 100%;
    overflow: hidden;
    background: transparent;
    border-right: none;
    display: flex;
    flex-direction: column;
}
.mt-mobile-drawer__scroll .mt-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;
}
.mt-mobile-drawer__scroll .mt-side__scroll::-webkit-scrollbar { width: 5px; }
.mt-mobile-drawer__scroll .mt-side__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}
.mt-mobile-drawer__scroll .mt-w--side {
    margin: 0;
    flex-shrink: 0;
}
.mt-mobile-drawer__scroll .mt-w--side:last-of-type { margin-bottom: 0; }
.mt-mobile-drawer__scroll .mt-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%);
}
.mt-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;
}
.mt-drawer-fade-enter-active,
.mt-drawer-fade-leave-active { transition: opacity 200ms ease; }
.mt-drawer-fade-enter-from,
.mt-drawer-fade-leave-to { opacity: 0; }

/* Botão X de fechar no header do dialog "Pacientes da tag" — estilo
   igual ao .mt-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(.mt-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(.mt-pdlg-close-btn:hover) {
    background: var(--m-bg-soft-hover) !important;
}
:global(.mt-pdlg-close-btn .p-button-icon) {
    font-size: 0.85rem !important;
}

/* ─── Color preset (no dialog de criar/editar tag) ─── */
.mt-color-preset {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    border: 1px solid rgba(255, 255, 255, 0.18);
    cursor: pointer;
    transition: transform 140ms ease, box-shadow 140ms ease;
}
.mt-color-preset:hover {
    transform: scale(1.12);
}
.mt-color-preset.is-selected {
    box-shadow: 0 0 0 2px var(--p-content-background), 0 0 0 4px var(--p-primary-color);
    transform: scale(1.08);
}

/* ─── Mobile (<1024px) ─── */
@media (max-width: 1023px) {
    .mt-body { flex-direction: column; padding: 0; }
    .mt-main { width: 100%; padding: 8px; }
    .mt-page__title > span:first-of-type { display: none; }
    .mt-page__title-icon { display: none; }
    .mt-menu-btn--mobile-only { display: inline-flex; }
    .mt-act-btn--primary span { display: none; }
    .mt-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) {
    .mt-page {
        right: max(6px, min(50%, calc(100% - 1006px)));
    }
}
</style>
