<script setup>
/*
 * MelissaRecorrencias — Sessão "Recorrências" como página fullscreen
 * dentro de Melissa. Segue o blueprint melissa-page-blueprint.md.
 *
 * Layout 2-col:
 *   - COL 1 — Aside esquerda (~280px): stats agregados + filtros (status)
 *   - COL 2 — Lista central (flex 1): cards de regra com progress bar,
 *            stats da série e expansão das sessões em pills
 *
 * Reaproveita a lógica de AgendaRecorrenciasPage (buildSessions,
 * generateAllDates, ruleStats, fmtRuleDesc/fmtPeriod). Modo clínica
 * (filterOwner) ficou de fora — só therapist.
 */
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useToast } from 'primevue/usetoast';
import Popover from 'primevue/popover';
import { supabase } from '@/lib/supabase/client';
import { useTenantStore } from '@/stores/tenantStore';
// Dialog/SelectButton/Button/Tag/ProgressBar/Avatar/Select: auto-import via PrimeVueResolver

const emit = defineEmits(['close']);

const toast = useToast();
const tenantStore = useTenantStore();

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

// ── State (espelhado da AgendaRecorrenciasPage) ─────────────
const loading = ref(false);
const userId = ref(null);
const rules = ref([]);
const exceptionsMap = ref({}); // ruleId → Exception[]
const sessionsMap = ref({});   // ruleId → AgendaEvento[]
const expandedId = ref(null);

const filterStatus = ref('ativo');
const statusOptions = [
    { label: 'Ativas', value: 'ativo' },
    { label: 'Encerradas', value: 'cancelado' },
    { label: 'Todas', value: 'all' }
];

const carregandoInicial = computed(
    () => loading.value && rules.value.length === 0
);

// ── Data load ───────────────────────────────────────────────
async function init() {
    const { data } = await supabase.auth.getUser();
    userId.value = data?.user?.id || null;
    await load();
}

async function load() {
    if (!userId.value) return;
    loading.value = true;
    try {
        let q = supabase.from('recurrence_rules').select('*').order('start_date', { ascending: false }).eq('owner_id', userId.value);
        if (filterStatus.value !== 'all') q = q.eq('status', filterStatus.value);

        const { data: rData, error: rErr } = await q;
        if (rErr) throw rErr;
        const rawRules = rData || [];

        const patientIds = [...new Set(rawRules.map((r) => r.patient_id).filter(Boolean))];
        const patientMap = {};
        if (patientIds.length) {
            const { data: pts } = await supabase.from('patients')
                .select('id, nome_completo, avatar_url').in('id', patientIds);
            for (const p of pts || []) patientMap[p.id] = p;
        }
        for (const r of rawRules) r._patient = patientMap[r.patient_id] || null;

        rules.value = rawRules;

        const ruleIds = rawRules.map((r) => r.id);
        if (ruleIds.length) await reloadSessions(ruleIds);
    } catch (e) {
        toast.add({ severity: 'warn', summary: 'Erro ao carregar', detail: e?.message, life: 3500 });
    } finally {
        loading.value = false;
    }
}

async function reloadSessions(ruleIds) {
    const [exRes, sessRes] = await Promise.all([
        supabase.from('recurrence_exceptions').select('*').in('recurrence_id', ruleIds).order('original_date'),
        supabase.from('agenda_eventos')
            .select('id, recurrence_id, recurrence_date, status, inicio_em, fim_em')
            .in('recurrence_id', ruleIds).order('inicio_em')
    ]);
    const exm = {};
    for (const ex of exRes.data || []) {
        if (!exm[ex.recurrence_id]) exm[ex.recurrence_id] = [];
        exm[ex.recurrence_id].push(ex);
    }
    exceptionsMap.value = {
        ...exceptionsMap.value, ...exm,
        ...Object.fromEntries(ruleIds.filter((id) => !exm[id]).map((id) => [id, []]))
    };

    const sm = {};
    for (const s of sessRes.data || []) {
        if (!sm[s.recurrence_id]) sm[s.recurrence_id] = [];
        sm[s.recurrence_id].push(s);
    }
    sessionsMap.value = {
        ...sessionsMap.value, ...sm,
        ...Object.fromEntries(ruleIds.filter((id) => !sm[id]).map((id) => [id, []]))
    };
}

// ── Geração de datas + sessões merged ──────────────────────
function generateAllDates(rule) {
    const { type, interval = 1, weekdays = [], start_date, end_date, max_occurrences } = rule;
    if (!start_date || !Array.isArray(weekdays) || !weekdays.length) return [];
    const maxOcc = Math.min(max_occurrences || 500, 500);
    const endLimitISO = end_date || null;
    const dates = [];

    if (type === 'custom_weekdays') {
        const cursor = new Date(start_date + 'T12:00:00');
        let safety = 0;
        while (dates.length < maxOcc && safety < 3000) {
            safety++;
            const iso = cursor.toISOString().slice(0, 10);
            if (endLimitISO && iso > endLimitISO) break;
            if (weekdays.includes(cursor.getDay())) dates.push(iso);
            cursor.setDate(cursor.getDate() + 1);
        }
    } else {
        const dow = weekdays[0];
        const cursor = new Date(start_date + 'T12:00:00');
        while (cursor.getDay() !== dow) cursor.setDate(cursor.getDate() + 1);
        while (dates.length < maxOcc) {
            const iso = cursor.toISOString().slice(0, 10);
            if (endLimitISO && iso > endLimitISO) break;
            dates.push(iso);
            cursor.setDate(cursor.getDate() + 7 * (interval || 1));
        }
    }
    return dates;
}

const TODAY = new Date().toISOString().slice(0, 10);

function buildSessions(rule) {
    const exByDate = {};
    for (const ex of exceptionsMap.value[rule.id] || []) exByDate[ex.original_date] = ex;
    const sessByDate = {};
    for (const s of sessionsMap.value[rule.id] || []) sessByDate[s.recurrence_date] = s;

    return generateAllDates(rule).map((iso) => {
        const real = sessByDate[iso];
        const ex = exByDate[iso];
        let status = 'agendado';
        if (real) {
            status = real.status || 'agendado';
        } else if (ex) {
            if (ex.type === 'cancel_session' || ex.type === 'therapist_canceled') status = 'cancelado';
            else if (ex.type === 'patient_missed') status = 'faltou';
            else if (ex.type === 'reschedule_session') status = 'remarcado';
        }
        return { date: iso, status, real_id: real?.id || null };
    });
}

// ── Stats ───────────────────────────────────────────────────
const STATUS_DONE = new Set(['compareceu', 'veio', 'realizado', 'presente']);

function ruleStats(rule) {
    const sessions = buildSessions(rule);
    const total = sessions.length;
    const done = sessions.filter((s) => STATUS_DONE.has(s.status)).length;
    const faltou = sessions.filter((s) => s.status === 'faltou').length;
    const cancelado = sessions.filter((s) => s.status === 'cancelado').length;
    const pendentes = sessions.filter((s) => s.status === 'agendado' || s.status === 'remarcado').length;
    const progress = total ? Math.round((done / total) * 100) : 0;
    return { total, done, faltou, cancelado, pendentes, progress };
}

const aggregateStats = computed(() => {
    let totalSeries = rules.value.length;
    let ativas = rules.value.filter((r) => r.status === 'ativo').length;
    let encerradas = rules.value.filter((r) => r.status === 'cancelado').length;
    let totalSessoes = 0;
    let totalDone = 0;
    for (const r of rules.value) {
        const s = ruleStats(r);
        totalSessoes += s.total;
        totalDone += s.done;
    }
    return [
        { key: 'series', label: 'Séries', value: totalSeries, cls: 'neutral' },
        { key: 'ativas', label: 'Ativas', value: ativas, cls: ativas > 0 ? 'ok' : 'neutral' },
        { key: 'encerradas', label: 'Encerradas', value: encerradas, cls: 'neutral' },
        { key: 'sessoes', label: 'Sessões', value: totalSessoes, cls: 'neutral' }
    ];
});

// ── Formatters ──────────────────────────────────────────────
const DIAS_SHORT = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];

function fmtDate(iso) {
    if (!iso) return '';
    const [y, m, d] = iso.split('-');
    return `${d}/${m}/${y}`;
}
function fmtRuleDesc(rule) {
    const days = (rule.weekdays || []).map((d) => DIAS_SHORT[d]).join(', ');
    const time = rule.start_time ? rule.start_time.slice(0, 5) : '';
    const freq = rule.interval > 1 ? `a cada ${rule.interval} sem.` : '';
    return [days, time, freq].filter(Boolean).join(' · ');
}
function fmtPeriod(rule) {
    const s = fmtDate(rule.start_date);
    if (rule.end_date) return `${s} até ${fmtDate(rule.end_date)}`;
    if (rule.max_occurrences) return `${s} · ${rule.max_occurrences} sessões`;
    return `A partir de ${s}`;
}
function fmtPillDate(iso) {
    const [, m, d] = iso.split('-');
    const dow = DIAS_SHORT[new Date(iso + 'T12:00:00').getDay()];
    return `${dow} ${Number(d)}/${Number(m)}`;
}
function pacienteIniciais(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();
}

// ── Status pill UI ──────────────────────────────────────────
const STATUS_OPTS = [
    { label: 'Agendado', value: 'agendado' },
    { label: 'Compareceu', value: 'compareceu' },
    { label: 'Faltou', value: 'faltou' },
    { label: 'Cancelado', value: 'cancelado' },
    { label: 'Remarcado', value: 'remarcado' }
];

const PILL_CLASS = {
    agendado: 'is-pending',
    compareceu: 'is-done',
    veio: 'is-done',
    realizado: 'is-done',
    presente: 'is-done',
    faltou: 'is-missed',
    cancelado: 'is-canceled',
    remarcado: 'is-rescheduled'
};

// ── Actions ─────────────────────────────────────────────────
async function onPillStatusChange(rule, s, newStatus) {
    try {
        if (s.real_id) {
            await supabase.from('agenda_eventos').update({ status: newStatus }).eq('id', s.real_id);
        } else {
            const { data: ex } = await supabase.from('agenda_eventos')
                .select('id').eq('recurrence_id', rule.id).eq('recurrence_date', s.date).maybeSingle();
            if (ex?.id) {
                await supabase.from('agenda_eventos').update({ status: newStatus }).eq('id', ex.id);
            } else {
                await supabase.from('agenda_eventos').insert({
                    recurrence_id: rule.id,
                    recurrence_date: s.date,
                    owner_id: rule.owner_id,
                    tenant_id: rule.tenant_id,
                    tipo: 'sessao',
                    status: newStatus,
                    inicio_em: s.date + 'T' + (rule.start_time || '00:00') + ':00',
                    fim_em: s.date + 'T' + (rule.end_time || '01:00') + ':00',
                    visibility_scope: 'public',
                    titulo: 'Sessão',
                    paciente_id: rule.patient_id || null,
                    patient_id: rule.patient_id || null
                });
            }
        }
        toast.add({ severity: 'success', summary: 'Status atualizado', life: 1500 });
        await reloadSessions([rule.id]);
    } catch (e) {
        toast.add({ severity: 'warn', summary: 'Erro', detail: e?.message, life: 3500 });
    }
}

async function onCancelRule(rule) {
    const name = rule._patient?.nome_completo || 'paciente';
    if (!confirm(`Encerrar a série de "${name}"?\n\nSessões futuras deixarão de ser geradas. Sessões passadas já registradas são mantidas.`)) return;
    try {
        await supabase.from('recurrence_rules').update({ status: 'cancelado', updated_at: new Date().toISOString() }).eq('id', rule.id);
        toast.add({ severity: 'success', summary: 'Série encerrada', life: 2000 });
        await load();
    } catch (e) {
        toast.add({ severity: 'warn', summary: 'Erro', detail: e?.message, life: 3500 });
    }
}

async function onReactivateRule(rule) {
    try {
        await supabase.from('recurrence_rules').update({ status: 'ativo', updated_at: new Date().toISOString() }).eq('id', rule.id);
        toast.add({ severity: 'success', summary: 'Série reativada', life: 2000 });
        await load();
    } catch (e) {
        toast.add({ severity: 'warn', summary: 'Erro', detail: e?.message, life: 3500 });
    }
}

function toggleExpand(ruleId) {
    expandedId.value = expandedId.value === ruleId ? null : ruleId;
}

// ── Popover de Ações (mobile compact) ──────────────────────
const actionsPopRef = ref(null);
function openActions(e) { actionsPopRef.value?.toggle(e); }

onMounted(async () => {
    if (typeof window !== 'undefined' && window.matchMedia) {
        _mqMobile = window.matchMedia('(max-width: 1023px)');
        isMobile.value = _mqMobile.matches;
        _mqMobile.addEventListener('change', _onMqMobileChange);
        _mqCompact = window.matchMedia('(max-width: 1279px)');
        isCompact.value = _mqCompact.matches;
        _mqCompact.addEventListener('change', _onMqCompactChange);
    }
    if (typeof tenantStore.loadSessionAndTenant === 'function') {
        await tenantStore.loadSessionAndTenant();
    }
    await init();
});
onBeforeUnmount(() => {
    if (_mqMobile) _mqMobile.removeEventListener('change', _onMqMobileChange);
    if (_mqCompact) _mqCompact.removeEventListener('change', _onMqCompactChange);
});
</script>

<template>
    <!-- Drawer host (blueprint §2) -->
    <aside
        class="mr-mobile-drawer"
        :class="{ 'is-open': drawerOpen }"
        v-show="isMobile"
        aria-label="Filtros e estatísticas"
    >
        <div id="mr-mobile-drawer-target" class="mr-mobile-drawer__scroll" />
    </aside>
    <Transition name="mr-drawer-fade">
        <div
            v-if="isMobile && drawerOpen"
            class="mr-mobile-drawer__backdrop"
            @click="fecharDrawer"
        />
    </Transition>

    <section class="mr-page">
        <header class="mr-page__head">
            <button
                class="mr-menu-btn mr-menu-btn--mobile-only"
                v-tooltip.bottom="'Filtros & estatísticas'"
                @click="toggleDrawer"
            >
                <i class="pi pi-bars" />
                <span>Menu Recorrências</span>
            </button>
            <div class="mr-page__title">
                <i class="pi pi-sync text-indigo-300" />
                <span>Recorrências</span>
                <span class="mr-page__count">{{ rules.length }}</span>
            </div>
            <div class="mr-page__actions">
                <button
                    class="mr-head-btn mr-head-btn--compact-only"
                    v-tooltip.bottom="'Filtros'"
                    @click="openActions"
                >
                    <i class="pi pi-sliders-h" />
                </button>
                <button
                    class="mr-head-btn"
                    v-tooltip.bottom="'Recarregar'"
                    :disabled="loading"
                    @click="load"
                >
                    <i :class="loading ? 'pi pi-spin pi-spinner' : 'pi pi-refresh'" />
                </button>
                <button class="mr-close" v-tooltip.bottom="'Voltar ao resumo (Esc)'" @click="emit('close')">
                    <i class="pi pi-times" />
                </button>
            </div>
        </header>

        <Popover ref="actionsPopRef" class="mr-actions-pop">
            <div class="mr-actions">
                <div class="mr-actions__group">
                    <div class="mr-actions__label">Status</div>
                    <SelectButton
                        v-model="filterStatus"
                        :options="statusOptions"
                        optionLabel="label"
                        optionValue="value"
                        :allowEmpty="false"
                        size="small"
                        class="w-full"
                        @change="load"
                    />
                </div>
            </div>
        </Popover>

        <div class="mr-body">
            <!-- ═══ COL 1: Stats + filtros ═══════════════════════════════ -->
            <Teleport to="#mr-mobile-drawer-target" :disabled="!isMobile">
            <aside class="mr-side">
                <div class="mr-w">
                    <div class="mr-w__head">
                        <span class="mr-w__title"><i class="pi pi-chart-bar" /> Estatísticas</span>
                    </div>
                    <div class="mr-stats">
                        <template v-if="carregandoInicial">
                            <div v-for="i in 4" :key="`stsk-${i}`" class="mr-stat mr-stat--skeleton" aria-busy="true">
                                <div class="mr-stat__val melissa-skeleton melissa-skeleton--number" />
                                <div class="mr-stat__lbl melissa-skeleton melissa-skeleton--text" style="width: 60%; margin-top: 6px;" />
                            </div>
                        </template>
                        <div
                            v-for="s in aggregateStats"
                            v-else
                            :key="s.key"
                            class="mr-stat"
                            :class="`is-${s.cls}`"
                        >
                            <div class="mr-stat__val">{{ s.value }}</div>
                            <div class="mr-stat__lbl">{{ s.label }}</div>
                        </div>
                    </div>
                </div>

                <div class="mr-w mr-w--side-only">
                    <div class="mr-w__head">
                        <span class="mr-w__title"><i class="pi pi-filter" /> Filtros</span>
                    </div>
                    <div class="mr-side__filters">
                        <div>
                            <div class="mr-side__label">Status</div>
                            <SelectButton
                                v-model="filterStatus"
                                :options="statusOptions"
                                optionLabel="label"
                                optionValue="value"
                                :allowEmpty="false"
                                size="small"
                                class="w-full"
                                @change="load"
                            />
                        </div>
                    </div>
                </div>
            </aside>
            </Teleport>

            <!-- ═══ COL 2: Lista de regras ═══════════════════════════════ -->
            <div class="mr-main">
                <div class="mr-list">
                    <!-- Skeletons (blueprint §9) -->
                    <template v-if="carregandoInicial">
                        <div v-for="i in 3" :key="`rsk-${i}`" class="mr-card mr-card--skeleton" aria-busy="true">
                            <div class="mr-card__head">
                                <span class="mr-card__avatar melissa-skeleton melissa-skeleton--avatar" />
                                <div style="flex:1; display:flex; flex-direction:column; gap:6px;">
                                    <span class="melissa-skeleton melissa-skeleton--title" :style="{ width: `${50 + (i * 13) % 30}%` }" />
                                    <span class="melissa-skeleton melissa-skeleton--text" style="width: 70%;" />
                                </div>
                            </div>
                            <div class="melissa-skeleton" style="height: 6px; margin: 12px 16px;" />
                        </div>
                    </template>

                    <div v-else-if="!rules.length" class="mr-empty">
                        <i class="pi pi-calendar-times mr-empty__icon" />
                        <div class="mr-empty__title">Nenhuma série encontrada</div>
                        <div class="mr-empty__hint">
                            <template v-if="filterStatus === 'ativo'">
                                Crie sessões recorrentes na agenda pra vê-las aqui.
                            </template>
                            <template v-else>
                                Altere o filtro de status pra ver outras séries.
                            </template>
                        </div>
                    </div>

                    <div v-else v-for="rule in rules" :key="rule.id" class="mr-card">
                        <!-- Head: paciente + descrição + período -->
                        <div class="mr-card__head">
                            <span class="mr-card__avatar">
                                <img v-if="rule._patient?.avatar_url" :src="rule._patient.avatar_url" :alt="rule._patient.nome_completo" />
                                <span v-else>{{ pacienteIniciais(rule._patient?.nome_completo) }}</span>
                            </span>
                            <div class="mr-card__info">
                                <div class="mr-card__name-row">
                                    <span class="mr-card__name">
                                        {{ rule._patient?.nome_completo || 'Paciente não encontrado' }}
                                    </span>
                                    <span class="mr-card__badge" :class="rule.status === 'ativo' ? 'mr-card__badge--ok' : 'mr-card__badge--off'">
                                        {{ rule.status === 'ativo' ? 'Ativa' : 'Encerrada' }}
                                    </span>
                                </div>
                                <div class="mr-card__meta">
                                    <span><i class="pi pi-clock" /> {{ fmtRuleDesc(rule) }}</span>
                                    <span><i class="pi pi-calendar" /> {{ fmtPeriod(rule) }}</span>
                                </div>
                            </div>
                        </div>

                        <!-- Stats + progress -->
                        <template v-for="stats in [ruleStats(rule)]" :key="'stats-' + rule.id">
                            <div class="mr-stats-row">
                                <span class="mr-pill is-done">{{ stats.done }} compareceu</span>
                                <span v-if="stats.faltou" class="mr-pill is-missed">{{ stats.faltou }} faltou</span>
                                <span v-if="stats.cancelado" class="mr-pill is-canceled">{{ stats.cancelado }} cancelad{{ stats.cancelado !== 1 ? 'as' : 'a' }}</span>
                                <span class="mr-pill is-pending">{{ stats.pendentes }} pendente{{ stats.pendentes !== 1 ? 's' : '' }}</span>
                                <span class="mr-pill is-total">{{ stats.total }} sessões</span>
                            </div>
                            <div class="mr-progress">
                                <div class="mr-progress__bar" :style="{ width: stats.progress + '%' }" />
                            </div>
                        </template>

                        <!-- Footer: ações -->
                        <div class="mr-card__foot">
                            <button
                                class="mr-card__btn"
                                @click="toggleExpand(rule.id)"
                            >
                                <i :class="expandedId === rule.id ? 'pi pi-chevron-up' : 'pi pi-list'" />
                                <span>{{ expandedId === rule.id ? 'Ocultar sessões' : `Ver sessões (${ruleStats(rule).total})` }}</span>
                            </button>
                            <button
                                v-if="rule.status === 'ativo'"
                                class="mr-card__btn mr-card__btn--danger"
                                @click="onCancelRule(rule)"
                            >
                                <i class="pi pi-times-circle" />
                                <span>Encerrar</span>
                            </button>
                            <button
                                v-else
                                class="mr-card__btn mr-card__btn--success"
                                @click="onReactivateRule(rule)"
                            >
                                <i class="pi pi-undo" />
                                <span>Reativar</span>
                            </button>
                        </div>

                        <!-- Sessões expandidas -->
                        <div v-if="expandedId === rule.id" class="mr-sessions">
                            <div class="mr-sessions__grid">
                                <div
                                    v-for="s in buildSessions(rule)"
                                    :key="s.date"
                                    class="mr-session"
                                    :class="[PILL_CLASS[s.status] || 'is-pending', s.date < TODAY ? 'is-past' : (s.date === TODAY ? 'is-today' : 'is-future')]"
                                >
                                    <div class="mr-session__date">{{ fmtPillDate(s.date) }}</div>
                                    <Select
                                        :modelValue="s.status"
                                        :options="STATUS_OPTS"
                                        optionLabel="label"
                                        optionValue="value"
                                        class="mr-session__sel"
                                        @change="(e) => onPillStatusChange(rule, s, e.value)"
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</template>

<style scoped>
/* Convenção Melissa Page (blueprint §6) */
.mr-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: mr-page-enter 240ms cubic-bezier(0.2, 0.7, 0.3, 1);
}
@keyframes mr-page-enter {
    from { opacity: 0; transform: scale(0.985); }
    to   { opacity: 1; transform: scale(1); }
}

.mr-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;
}
.mr-page__title {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1rem;
    font-weight: 500;
}
.mr-page__title > span:not(.mr-page__count) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mr-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;
}
.mr-page__actions {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
}
.mr-close,
.mr-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;
}
.mr-close:hover,
.mr-head-btn:hover { background: var(--m-bg-soft-hover); }
.mr-head-btn > i { font-size: 0.85rem; }
.mr-head-btn--compact-only { display: none; }

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

/* Body */
.mr-body {
    flex: 1;
    display: flex;
    min-height: 0;
    position: relative;
    gap: 12px;
    padding: 12px;
}

/* Aside */
.mr-side {
    width: 280px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 12px;
    overflow-y: auto;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mr-side::-webkit-scrollbar { width: 5px; }
.mr-side::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

.mr-w {
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-radius: 12px;
    padding: 12px;
}
.mr-w__head { margin-bottom: 10px; }
.mr-w__title {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 0.78rem;
    font-weight: 600;
}
.mr-w__title > i { color: var(--m-text-muted); font-size: 0.78rem; }

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

.mr-side__label {
    text-transform: uppercase;
    letter-spacing: 0.12em;
    color: var(--m-text-muted);
    font-size: 0.62rem;
    font-weight: 600;
    margin-bottom: 6px;
}

/* Main */
.mr-main {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
}
.mr-list {
    flex: 1;
    overflow-y: auto;
    padding: 0 4px 4px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mr-list::-webkit-scrollbar { width: 5px; }
.mr-list::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

/* Card de regra */
.mr-card {
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-radius: 12px;
    overflow: hidden;
    transition: border-color 140ms ease, box-shadow 140ms ease;
}
.mr-card:hover {
    border-color: var(--m-border-strong);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.18);
}
.mr-card--skeleton:hover { border-color: var(--m-border); box-shadow: none; }

.mr-card__head {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 14px 16px 8px;
}
.mr-card__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;
    overflow: hidden;
}
.mr-card__avatar img {
    width: 100%; height: 100%; object-fit: cover;
}
.mr-card__info { flex: 1; min-width: 0; }
.mr-card__name-row {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}
.mr-card__name {
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--m-text);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
}
.mr-card__badge {
    display: inline-flex;
    align-items: center;
    font-size: 0.62rem;
    font-weight: 600;
    padding: 2px 8px;
    border-radius: 999px;
    text-transform: uppercase;
    letter-spacing: 0.04em;
}
.mr-card__badge--ok {
    color: rgb(74, 222, 128);
    background: rgba(74, 222, 128, 0.12);
    border: 1px solid rgba(74, 222, 128, 0.3);
}
.mr-card__badge--off {
    color: var(--m-text-muted);
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
}
.mr-card__meta {
    display: flex;
    flex-direction: column;
    gap: 3px;
    margin-top: 6px;
    font-size: 0.78rem;
    color: var(--m-text-muted);
}
.mr-card__meta > span > i {
    margin-right: 6px;
    font-size: 0.7rem;
}

/* Stats row + progress */
.mr-stats-row {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    padding: 0 16px 8px;
}
.mr-pill {
    font-size: 0.7rem;
    font-weight: 500;
    padding: 3px 9px;
    border-radius: 999px;
    border: 1px solid;
}
.mr-pill.is-done {
    color: rgb(74, 222, 128);
    background: rgba(74, 222, 128, 0.10);
    border-color: rgba(74, 222, 128, 0.25);
}
.mr-pill.is-missed {
    color: rgb(248, 113, 113);
    background: rgba(248, 113, 113, 0.10);
    border-color: rgba(248, 113, 113, 0.25);
}
.mr-pill.is-canceled {
    color: var(--m-text-muted);
    background: var(--m-bg-medium);
    border-color: var(--m-border);
}
.mr-pill.is-pending {
    color: rgb(251, 191, 36);
    background: rgba(251, 191, 36, 0.10);
    border-color: rgba(251, 191, 36, 0.25);
}
.mr-pill.is-total {
    color: var(--m-text);
    background: var(--m-bg-medium);
    border-color: var(--m-border);
    margin-left: auto;
}

.mr-progress {
    height: 4px;
    margin: 0 16px 12px;
    background: var(--m-bg-medium);
    border-radius: 999px;
    overflow: hidden;
}
.mr-progress__bar {
    height: 100%;
    background: linear-gradient(90deg, var(--m-accent), color-mix(in srgb, var(--m-accent) 70%, white));
    border-radius: 999px;
    transition: width 280ms cubic-bezier(0.2, 0.7, 0.3, 1);
}

/* Footer ações */
.mr-card__foot {
    display: flex;
    gap: 6px;
    padding: 8px 12px 12px;
    flex-wrap: wrap;
}
.mr-card__btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    background: transparent;
    border: 1px solid var(--m-border);
    border-radius: 9px;
    color: var(--m-text);
    cursor: pointer;
    font-family: inherit;
    font-size: 0.74rem;
    font-weight: 500;
    transition: background-color 140ms ease, border-color 140ms ease;
}
.mr-card__btn:hover {
    background: var(--m-bg-soft-hover);
}
.mr-card__btn--danger {
    color: rgb(248, 113, 113);
    border-color: rgba(248, 113, 113, 0.3);
    margin-left: auto;
}
.mr-card__btn--danger:hover {
    background: rgba(248, 113, 113, 0.12);
}
.mr-card__btn--success {
    color: rgb(74, 222, 128);
    border-color: rgba(74, 222, 128, 0.3);
    margin-left: auto;
}
.mr-card__btn--success:hover {
    background: rgba(74, 222, 128, 0.12);
}

/* Sessions expand */
.mr-sessions {
    border-top: 1px solid var(--m-border);
    padding: 12px 16px 16px;
    background: color-mix(in srgb, var(--m-bg-medium) 60%, transparent);
}
.mr-sessions__grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 6px;
}
.mr-session {
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 6px 8px;
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    border-radius: 9px;
    border-left: 3px solid;
}
.mr-session.is-done { border-left-color: rgb(74, 222, 128); }
.mr-session.is-missed { border-left-color: rgb(248, 113, 113); }
.mr-session.is-canceled { border-left-color: var(--m-text-muted); }
.mr-session.is-pending { border-left-color: rgb(251, 191, 36); }
.mr-session.is-rescheduled { border-left-color: rgb(96, 165, 250); }
.mr-session.is-past { opacity: 0.85; }
.mr-session.is-today { box-shadow: 0 0 0 1px var(--m-accent); }
.mr-session__date {
    font-size: 0.72rem;
    font-weight: 600;
    color: var(--m-text);
}
.mr-session__sel { font-size: 0.7rem; }
.mr-session__sel :deep(.p-select) { background: transparent; }
.mr-session__sel :deep(.p-select-label) { padding: 4px 8px; font-size: 0.7rem; }

/* Empty */
.mr-empty {
    margin: 24px 0;
    padding: 56px 28px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: 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;
}
.mr-empty__icon {
    font-size: 2rem;
    color: var(--m-text-faint);
    margin-bottom: 4px;
}
.mr-empty__title {
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--m-text);
}
.mr-empty__hint {
    font-size: 0.78rem;
    color: var(--m-text-muted);
}

/* Popover de Ações */
.mr-actions {
    display: flex;
    flex-direction: column;
    gap: 14px;
    min-width: 240px;
    padding: 4px;
}
.mr-actions__group {
    display: flex;
    flex-direction: column;
    gap: 6px;
}
.mr-actions__label {
    text-transform: uppercase;
    letter-spacing: 0.14em;
    color: var(--text-color-secondary, var(--m-text-faint));
    font-size: 0.62rem;
    font-weight: 600;
}

/* Drawer mobile (blueprint §6) */
.mr-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;
}
.mr-mobile-drawer.is-open { transform: translateX(0); }
.mr-mobile-drawer__scroll {
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 12px 12px 24px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mr-mobile-drawer__scroll::-webkit-scrollbar { width: 5px; }
.mr-mobile-drawer__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}
.mr-mobile-drawer__scroll .mr-side {
    width: 100%;
    height: auto;
    overflow: visible;
    padding: 0;
}
.mr-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;
}
.mr-drawer-fade-enter-active,
.mr-drawer-fade-leave-active { transition: opacity 200ms ease; }
.mr-drawer-fade-enter-from,
.mr-drawer-fade-leave-to { opacity: 0; }

/* Compact (<xl) */
@media (max-width: 1279px) {
    .mr-head-btn--compact-only { display: grid; }
}

/* Mobile (<lg) */
@media (max-width: 1023px) {
    .mr-body { flex-direction: column; padding: 8px; }
    .mr-main { width: 100%; }
    .mr-page__title > span:first-of-type { display: none; }
    .mr-menu-btn--mobile-only { display: inline-flex; }
    .mr-card__foot { gap: 4px; }
    .mr-card__btn { font-size: 0.72rem; padding: 5px 9px; }
    .mr-stats-row { padding: 0 12px 6px; }
}
</style>
