<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 { supabase } from '@/lib/supabase/client';
import { tenantDb } from '@/lib/supabase/tenantClient';
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');

// Button list de status (icons + cores). Ativa = verde / Encerrada = vermelho.
// Todas = neutral. O blueprint pede botões coloridos por status (§7).
const STATUS_FILTER_OPTIONS = [
    { key: 'ativo', label: 'Ativas', icon: 'pi pi-check-circle' },
    { key: 'cancelado', label: 'Encerradas', icon: 'pi pi-times-circle' },
    { key: 'all', label: 'Todas', icon: 'pi pi-list' }
];

const busca = ref('');

function setStatusFilter(s) {
    filterStatus.value = s;
    load();
}

const hasActiveFilters = computed(() =>
    !!(busca.value || filterStatus.value !== 'ativo')
);
function clearAllFilters() {
    busca.value = '';
    if (filterStatus.value !== 'ativo') {
        filterStatus.value = 'ativo';
        load();
    }
}

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

// Filtragem client-side por nome do paciente (status é server-side via load).
const filteredRules = computed(() => {
    const q = String(busca.value || '').trim().toLowerCase();
    if (!q) return rules.value;
    return rules.value.filter((r) =>
        String(r._patient?.nome_completo || '').toLowerCase().includes(q)
    );
});

// ── 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 = tenantDb().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 tenantDb().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([
        tenantDb().from('recurrence_exceptions').select('*').in('recurrence_id', ruleIds).order('original_date'),
        tenantDb().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 tenantDb().from('agenda_eventos').update({ status: newStatus }).eq('id', s.real_id);
        } else {
            const { data: ex } = await tenantDb().from('agenda_eventos')
                .select('id').eq('recurrence_id', rule.id).eq('recurrence_date', s.date).maybeSingle();
            if (ex?.id) {
                await tenantDb().from('agenda_eventos').update({ status: newStatus }).eq('id', ex.id);
            } else {
                await tenantDb().from('agenda_eventos').insert({
                    recurrence_id: rule.id,
                    recurrence_date: s.date,
                    owner_id: rule.owner_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 tenantDb().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 tenantDb().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;
}

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 mr-page__title-icon" />
                <span>Recorrências</span>
                <span class="mr-page__count">{{ filteredRules.length }}</span>
            </div>
            <div class="mr-page__actions">
                <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>

        <!-- Subheader explicativo (blueprint §9) -->
        <div class="mr-subheader">
            <i class="pi pi-info-circle mr-subheader__icon" />
            <span class="mr-subheader__text">
                Séries de sessões que se repetem (semanal, quinzenal, dias específicos).
                Acompanhe o <strong>progresso</strong> de cada uma e marque como
                <strong>encerrada</strong> quando o paciente terminar o tratamento.
            </span>
        </div>

        <div class="mr-body">
            <!-- ═══ COL 1: Stats + filtros ═══════════════════════════════ -->
            <Teleport to="#mr-mobile-drawer-target" :disabled="!isMobile">
            <aside class="mr-side">
                <div class="mr-side__scroll">
                    <!-- Stats -->
                    <div class="mr-w mr-w--side">
                        <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>

                    <!-- Filtro de status (button list colorido) -->
                    <div class="mr-w mr-w--side">
                        <div class="mr-w__head">
                            <span class="mr-w__title"><i class="pi pi-filter" /> Status</span>
                            <button
                                v-if="filterStatus !== 'ativo'"
                                class="mr-side__clear-inline"
                                v-tooltip.top="'Voltar pro filtro padrão (Ativas)'"
                                aria-label="Voltar pro filtro padrão"
                                @click="setStatusFilter('ativo')"
                            >
                                <i class="pi pi-times" />
                            </button>
                        </div>
                        <div class="mr-side__list">
                            <button
                                v-for="o in STATUS_FILTER_OPTIONS"
                                :key="o.key"
                                class="mr-side__item"
                                :class="[`is-status-${o.key}`, { 'is-active': filterStatus === o.key }]"
                                @click="setStatusFilter(o.key)"
                            >
                                <i :class="o.icon" />
                                <span>{{ o.label }}</span>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Footer fixo: Limpar filtros (Transition fade+collapse) -->
                <Transition name="mr-clear">
                    <div v-if="hasActiveFilters" class="mr-side__footer">
                        <button class="mr-side__clear-all" @click="clearAllFilters">
                            <i class="pi pi-filter-slash" />
                            <span>Limpar filtros</span>
                        </button>
                    </div>
                </Transition>
            </aside>
            </Teleport>

            <!-- ═══ COL 2: Lista de regras ═══════════════════════════════ -->
            <div class="mr-main">
                <!-- Toolbar: busca por nome do paciente -->
                <div class="mr-toolbar">
                    <div class="mr-search">
                        <i class="pi pi-search mr-search__icon" />
                        <input
                            v-model="busca"
                            type="text"
                            placeholder="Buscar por nome do paciente…"
                            class="mr-search__input"
                        />
                        <button
                            v-if="busca"
                            class="mr-search__clear"
                            v-tooltip.bottom="'Limpar busca'"
                            @click="busca = ''"
                        >
                            <i class="pi pi-times" />
                        </button>
                    </div>
                </div>

                <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="!filteredRules.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="busca">
                                Nenhum paciente corresponde à busca. Ajuste ou limpe os filtros.
                            </template>
                            <template v-else-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 filteredRules" :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-icon {
    color: var(--p-primary-color);
    font-size: 1.05rem;
}
.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; }

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

/* Body — sidebar fica colada à esquerda com border-right; main com
   padding interno. Espelha Grupos/Tags/Médicos/Conversas. */
.mr-body {
    flex: 1;
    display: flex;
    min-height: 0;
    position: relative;
    gap: 0;
    padding: 0;
}

/* Aside — 2 zonas: __scroll (cards) + __footer (Limpar filtros fixo) */
.mr-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;
}
.mr-side__scroll {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.mr-side__scroll::-webkit-scrollbar { width: 5px; }
.mr-side__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

/* Footer fixo: Limpar filtros (espelha Grupos/Tags/Médicos/Conversas) */
.mr-side__footer {
    flex-shrink: 0;
    padding: 12px;
    background: var(--m-bg-soft);
    border-top: 1px solid var(--m-border);
}
.mr-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;
}
.mr-side__clear-all:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    color: var(--m-text);
}
.mr-side__clear-all > i {
    font-size: 0.78rem;
    color: var(--m-text-muted);
    transition: color 140ms ease;
}
.mr-side__clear-all:hover > i { color: var(--m-text); }

/* X inline ao lado do título do filter card */
.mr-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;
}
.mr-side__clear-inline:hover {
    background: rgba(220, 38, 38, 0.10);
    border-color: rgba(220, 38, 38, 0.55);
}
.mr-side__clear-inline > i { font-size: 0.6rem; }

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

.mr-w {
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    border-radius: 12px;
    padding: 12px;
}
/* Modifier pros cards dentro da sidebar — margem lateral + sombra */
.mr-w--side {
    margin: 12px 12px 0;
    flex-shrink: 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}
.mr-w--side:last-of-type { margin-bottom: 12px; }

.mr-w__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    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-soft);
    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(22, 163, 74); }

/* Filter button list (blueprint §8) */
.mr-side__list {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.mr-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;
}
.mr-side__item > i {
    font-size: 0.78rem;
    width: 14px;
    text-align: center;
}

/* Status: Ativas verde / Encerradas vermelho / Todas neutral */
.mr-side__item.is-status-ativo {
    background: rgba(22, 163, 74, 0.05);
    border-color: rgba(22, 163, 74, 0.18);
}
.mr-side__item.is-status-ativo > i { color: rgb(22, 163, 74); }
.mr-side__item.is-status-ativo:hover {
    background: rgba(22, 163, 74, 0.10);
    border-color: rgba(22, 163, 74, 0.30);
}
.mr-side__item.is-active.is-status-ativo {
    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);
}

.mr-side__item.is-status-cancelado {
    background: rgba(220, 38, 38, 0.05);
    border-color: rgba(220, 38, 38, 0.18);
}
.mr-side__item.is-status-cancelado > i { color: rgb(220, 38, 38); }
.mr-side__item.is-status-cancelado:hover {
    background: rgba(220, 38, 38, 0.10);
    border-color: rgba(220, 38, 38, 0.30);
}
.mr-side__item.is-active.is-status-cancelado {
    background: rgba(220, 38, 38, 0.16);
    border-color: rgba(220, 38, 38, 0.55);
    box-shadow: 0 0 0 1px rgba(220, 38, 38, 0.35);
}

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

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

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

/* 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;
    display: flex;
    flex-direction: column;
}
.mr-mobile-drawer.is-open { transform: translateX(0); }
.mr-mobile-drawer__scroll {
    flex: 1;
    min-height: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}
.mr-mobile-drawer__scroll .mr-side {
    flex: 1;
    min-height: 0;
    width: 100%;
    overflow: hidden;
    background: transparent;
    border-right: none;
    display: flex;
    flex-direction: column;
}
.mr-mobile-drawer__scroll .mr-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;
}
.mr-mobile-drawer__scroll .mr-side__scroll::-webkit-scrollbar { width: 5px; }
.mr-mobile-drawer__scroll .mr-side__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}
.mr-mobile-drawer__scroll .mr-w--side {
    margin: 0;
    flex-shrink: 0;
}
.mr-mobile-drawer__scroll .mr-w--side:last-of-type { margin-bottom: 0; }
.mr-mobile-drawer__scroll .mr-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%);
}
.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; }

/* Mobile (<lg) */
@media (max-width: 1023px) {
    .mr-body { flex-direction: column; padding: 0; }
    .mr-main { width: 100%; padding: 8px; }
    .mr-page__title > span:first-of-type { display: none; }
    .mr-page__title-icon { 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; }
}

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