<script setup>
/*
 * MelissaCompromissos — Sessão "Compromissos determinados" como página
 * fullscreen dentro de Melissa. Segue o blueprint melissa-page-blueprint.md.
 *
 * Layout 2-col:
 *   - COL 1 — Aside esquerda (~280px): stats compactos + filtros (tipo + busca)
 *   - COL 2 — Lista central (flex 1): cards de compromisso (cor, nome, desc,
 *            tempo total, nº de campos, toggle ativo, editar/excluir)
 *
 * Mobile (<lg): aside vai pro drawer off-canvas, lista ocupa 100%, botão
 * "Menu Compromissos" no header esquerda + filtros via popover de "Ações".
 *
 * Reusa DeterminedCommitmentDialog pra criar/editar (mesmo dialog da página
 * antiga em src/features/agenda/pages/CompromissosDeterminados.vue).
 */
import { ref, computed, reactive, 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';
import DeterminedCommitmentDialog from '@/features/agenda/components/DeterminedCommitmentDialog.vue';
// Dialog/SelectButton/InputText/Button/Toggle: auto-importados 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; }

// ── Estado ─────────────────────────────────────────────────
const loading = ref(false);
const hasLoaded = ref(false);
const saving = ref(false);

const commitments = ref([]);
const totalsByCommitmentId = ref({});

const typeFilter = ref('all');
const typeOptions = [
    { label: 'Todos', value: 'all' },
    { label: 'Nativos', value: 'native' },
    { label: 'Meus', value: 'custom' }
];

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

// ── Carregando inicial (blueprint §9) ──────────────────────
const carregandoInicial = computed(
    () => loading.value && commitments.value.length === 0
);

// ── Filtragem ──────────────────────────────────────────────
const visibleCommitments = computed(() => {
    let list = commitments.value;
    if (typeFilter.value === 'native') list = list.filter((c) => !!c.is_native);
    if (typeFilter.value === 'custom') list = list.filter((c) => !c.is_native);
    const q = String(filters.global?.value ?? '').trim().toLowerCase();
    if (q) {
        list = list.filter((c) =>
            String(c.name || '').toLowerCase().includes(q) ||
            String(c.description || '').toLowerCase().includes(q)
        );
    }
    return list;
});

// ── Stats ──────────────────────────────────────────────────
const stats = computed(() => {
    const all = commitments.value;
    const ativos = all.filter((c) => c.active).length;
    const inativos = all.filter((c) => !c.active).length;
    const totalMin = Object.values(totalsByCommitmentId.value).reduce((a, b) => a + b, 0);
    return [
        { key: 'total', label: 'Total', value: all.length, cls: '' },
        { key: 'ativos', label: 'Ativos', value: ativos, cls: ativos > 0 ? 'is-ok' : '' },
        { key: 'inativos', label: 'Inativos', value: inativos, cls: inativos > 0 ? 'is-warn' : '' },
        { key: 'tempo', label: 'Tempo', value: formatMinutes(totalMin), cls: '' }
    ];
});

function formatMinutes(minutes) {
    const m = Math.max(0, Number(minutes) || 0);
    const h = Math.floor(m / 60);
    const mm = m % 60;
    if (h <= 0) return `${mm}m`;
    return `${h}h${String(mm).padStart(2, '0')}`;
}
function getTotalMinutes(id) {
    return Number(totalsByCommitmentId.value?.[id] ?? 0);
}

// ── Fetch ──────────────────────────────────────────────────
function getTenantId() {
    return tenantStore.activeTenantId || tenantStore.tenantId || null;
}

async function fetchAll() {
    const tenantId = getTenantId();
    if (!tenantId) {
        toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Tenant inválido.', life: 3000 });
        return;
    }
    loading.value = true;
    try {
        const { data: cData, error: cErr } = await supabase
            .from('determined_commitments')
            .select('id, tenant_id, is_native, native_key, is_locked, active, name, description, bg_color, text_color, created_at, updated_at')
            .eq('tenant_id', tenantId)
            .order('is_native', { ascending: false })
            .order('created_at', { ascending: false });
        if (cErr) throw cErr;

        const ids = (cData || []).map((x) => x.id);
        let fieldsByCommitmentId = {};
        if (ids.length > 0) {
            const { data: fData, error: fErr } = await supabase
                .from('determined_commitment_fields')
                .select('id, tenant_id, commitment_id, key, label, field_type, required, sort_order')
                .eq('tenant_id', tenantId)
                .in('commitment_id', ids)
                .order('sort_order', { ascending: true });
            if (fErr) throw fErr;
            fieldsByCommitmentId = (fData || []).reduce((acc, row) => {
                if (!acc[row.commitment_id]) acc[row.commitment_id] = [];
                acc[row.commitment_id].push({
                    id: row.id, key: row.key, label: row.label,
                    type: row.field_type, required: !!row.required, sort_order: row.sort_order
                });
                return acc;
            }, {});
        }

        const { data: lData, error: lErr } = await supabase
            .from('commitment_time_logs').select('commitment_id, minutes').eq('tenant_id', tenantId);
        if (lErr) throw lErr;
        const totals = {};
        for (const row of lData || []) {
            const cid = row.commitment_id;
            totals[cid] = (totals[cid] || 0) + (Number(row.minutes ?? 0) || 0);
        }
        totalsByCommitmentId.value = totals;

        commitments.value = (cData || []).map((c) => ({
            ...c,
            fields: fieldsByCommitmentId[c.id] || []
        }));
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao carregar.', life: 4500 });
    } finally {
        loading.value = false;
        hasLoaded.value = true;
    }
}

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 fetchAll();
});
onBeforeUnmount(() => {
    if (_mqMobile) _mqMobile.removeEventListener('change', _onMqMobileChange);
    if (_mqCompact) _mqCompact.removeEventListener('change', _onMqCompactChange);
});

// ── CRUD (espelhado da CompromissosDeterminados.vue) ───────
const dlgOpen = ref(false);
const dlgMode = ref('create');
const editing = ref(null);

function openCreate() {
    dlgMode.value = 'create';
    editing.value = null;
    dlgOpen.value = true;
}
function openEdit(c) {
    dlgMode.value = 'edit';
    editing.value = JSON.parse(JSON.stringify(c));
    dlgOpen.value = true;
}

function isActiveLocked(c) { return !!c.is_locked; }
function isDeleteLocked(c) { return !!c.is_native; }

async function onToggleActive(c) {
    if (isActiveLocked(c)) return;
    const tenantId = getTenantId();
    if (!tenantId) return;
    saving.value = true;
    try {
        const { error } = await supabase.from('determined_commitments').update({ active: !!c.active }).eq('tenant_id', tenantId).eq('id', c.id);
        if (error) throw error;
        toast.add({ severity: 'success', summary: 'Atualizado', detail: `"${c.name}" ${c.active ? 'ativo' : 'inativo'}.`, life: 2200 });
    } catch (e) {
        c.active = !c.active;
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao atualizar.', life: 4500 });
    } finally {
        saving.value = false;
    }
}

async function onSave(payload) {
    const tenantId = getTenantId();
    if (!tenantId) return;
    saving.value = true;
    try {
        if (dlgMode.value === 'create') {
            const { data: newC, error: cErr } = await supabase
                .from('determined_commitments')
                .insert({
                    tenant_id: tenantId,
                    is_native: false,
                    native_key: null,
                    is_locked: false,
                    active: !!payload.active,
                    name: payload.name,
                    description: payload.description,
                    bg_color: payload.bg_color || null,
                    text_color: payload.text_color || null
                })
                .select('id').single();
            if (cErr) throw cErr;

            const fields = Array.isArray(payload.fields) ? payload.fields : [];
            if (fields.length > 0) {
                const { error: fErr } = await supabase.from('determined_commitment_fields').insert(
                    fields.map((f, idx) => ({
                        tenant_id: tenantId,
                        commitment_id: newC.id,
                        key: f.key,
                        label: f.label,
                        field_type: f.type,
                        required: !!f.required,
                        sort_order: f.sort_order ?? idx
                    }))
                );
                if (fErr) throw fErr;
            }
            toast.add({ severity: 'success', summary: 'Criado', detail: 'Compromisso criado.', life: 2200 });
        } else if (editing.value?.id) {
            const cid = editing.value.id;
            const { error: uErr } = await supabase.from('determined_commitments')
                .update({
                    active: !!payload.active,
                    name: payload.name,
                    description: payload.description,
                    bg_color: payload.bg_color || null,
                    text_color: payload.text_color || null
                })
                .eq('tenant_id', tenantId).eq('id', cid);
            if (uErr) throw uErr;

            // Re-sync fields (delete all + insert)
            const { error: dErr } = await supabase.from('determined_commitment_fields')
                .delete().eq('tenant_id', tenantId).eq('commitment_id', cid);
            if (dErr) throw dErr;
            const fields = Array.isArray(payload.fields) ? payload.fields : [];
            if (fields.length > 0) {
                const { error: fErr } = await supabase.from('determined_commitment_fields').insert(
                    fields.map((f, idx) => ({
                        tenant_id: tenantId,
                        commitment_id: cid,
                        key: f.key,
                        label: f.label,
                        field_type: f.type,
                        required: !!f.required,
                        sort_order: f.sort_order ?? idx
                    }))
                );
                if (fErr) throw fErr;
            }
            toast.add({ severity: 'success', summary: 'Atualizado', detail: 'Compromisso atualizado.', life: 2200 });
        }
        dlgOpen.value = false;
        await fetchAll();
    } catch (e) {
        const msg = e?.message || '';
        const detail = e?.code === '23505' || /duplicate key value/i.test(msg)
            ? 'Já existe um compromisso com esse nome. Escolha outro.'
            : msg || 'Falha ao salvar.';
        toast.add({ severity: 'error', summary: 'Erro', detail, life: 4500 });
    } finally {
        saving.value = false;
    }
}

function confirmDelete(c) {
    if (isDeleteLocked(c)) return;
    if (!window.confirm(`Excluir "${c.name}"? Essa ação não pode ser desfeita.`)) return;
    onDelete(c);
}

async function onDelete(c) {
    if (isDeleteLocked(c)) return;
    const tenantId = getTenantId();
    if (!tenantId) return;
    saving.value = true;
    try {
        const { error: fErr } = await supabase.from('determined_commitment_fields')
            .delete().eq('tenant_id', tenantId).eq('commitment_id', c.id);
        if (fErr) throw fErr;
        const { error: lErr } = await supabase.from('commitment_time_logs')
            .delete().eq('tenant_id', tenantId).eq('commitment_id', c.id);
        if (lErr) throw lErr;
        const { data: delRows, error: dErr } = await supabase.from('determined_commitments')
            .delete().eq('tenant_id', tenantId).eq('id', c.id).eq('is_native', false).select('id');
        if (dErr) throw dErr;
        if (!delRows?.length) throw new Error('DELETE bloqueado por RLS.');
        toast.add({ severity: 'success', summary: 'Excluído', detail: 'Compromisso removido.', life: 2200 });
        dlgOpen.value = false;
        await fetchAll();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao excluir.', life: 4500 });
    } finally {
        saving.value = false;
    }
}

// ── Popover de Ações (mobile compact, blueprint §10) ───────
const actionsPopRef = ref(null);
function openActions(e) { actionsPopRef.value?.toggle(e); }
function clearSearch() { filters.global.value = null; }
</script>

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

    <section class="mc-page">
        <header class="mc-page__head">
            <button
                class="mc-menu-btn mc-menu-btn--mobile-only"
                v-tooltip.bottom="'Filtros & estatísticas'"
                @click="toggleDrawer"
            >
                <i class="pi pi-bars" />
                <span>Menu Compromissos</span>
            </button>
            <div class="mc-page__title">
                <i class="pi pi-list text-indigo-300" />
                <span>Compromissos</span>
                <span class="mc-page__count">{{ visibleCommitments.length }}</span>
            </div>
            <div class="mc-page__actions">
                <button
                    class="mc-act-btn mc-act-btn--primary"
                    v-tooltip.bottom="'Novo compromisso'"
                    :disabled="loading"
                    @click="openCreate()"
                >
                    <i :class="saving ? 'pi pi-spin pi-spinner' : 'pi pi-plus'" />
                    <span>Novo</span>
                </button>
                <button
                    class="mc-head-btn mc-head-btn--compact-only"
                    v-tooltip.bottom="'Ações & filtros'"
                    @click="openActions"
                >
                    <i class="pi pi-sliders-h" />
                </button>
                <button
                    class="mc-head-btn"
                    v-tooltip.bottom="'Recarregar'"
                    :disabled="loading"
                    @click="fetchAll"
                >
                    <i :class="loading ? 'pi pi-spin pi-spinner' : 'pi pi-refresh'" />
                </button>
                <button class="mc-close" v-tooltip.bottom="'Voltar ao resumo (Esc)'" @click="emit('close')">
                    <i class="pi pi-times" />
                </button>
            </div>
        </header>

        <!-- Popover de filtros (compact + mobile) -->
        <Popover ref="actionsPopRef" class="mc-actions-pop">
            <div class="mc-actions">
                <div class="mc-actions__group">
                    <div class="mc-actions__label">Tipo</div>
                    <SelectButton
                        v-model="typeFilter"
                        :options="typeOptions"
                        optionLabel="label"
                        optionValue="value"
                        :allowEmpty="false"
                        size="small"
                        class="w-full"
                    />
                </div>
                <div class="mc-actions__group">
                    <div class="mc-actions__label">Buscar</div>
                    <InputText
                        v-model="filters.global.value"
                        placeholder="Nome ou descrição…"
                        class="w-full"
                    />
                </div>
            </div>
        </Popover>

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

                <div class="mc-w mc-w--side-only">
                    <div class="mc-w__head">
                        <span class="mc-w__title"><i class="pi pi-filter" /> Filtros</span>
                    </div>
                    <div class="mc-side__filters">
                        <div>
                            <div class="mc-side__label">Tipo</div>
                            <SelectButton
                                v-model="typeFilter"
                                :options="typeOptions"
                                optionLabel="label"
                                optionValue="value"
                                :allowEmpty="false"
                                size="small"
                                class="w-full"
                            />
                        </div>
                        <div>
                            <div class="mc-side__label">Buscar</div>
                            <InputText
                                v-model="filters.global.value"
                                placeholder="Nome ou descrição…"
                                class="w-full"
                            />
                        </div>
                        <button
                            v-if="filters.global.value"
                            class="mc-side__clear-btn"
                            @click="clearSearch"
                        >
                            <i class="pi pi-times text-[0.65rem]" />
                            Limpar busca
                        </button>
                    </div>
                </div>
            </aside>
            </Teleport>

            <!-- ═══ COL 2: Lista central ═══════════════════════════════ -->
            <div class="mc-main">
                <div class="mc-list">
                    <!-- Skeletons na 1ª carga (blueprint §9) -->
                    <template v-if="carregandoInicial">
                        <div v-for="i in 5" :key="`csk-${i}`" class="mc-card mc-card--skeleton" aria-busy="true">
                            <span class="mc-card__color melissa-skeleton" style="border-radius: 6px;" />
                            <div class="mc-card__main">
                                <span class="melissa-skeleton melissa-skeleton--title" :style="{ width: `${50 + (i * 7) % 30}%` }" />
                                <span class="melissa-skeleton melissa-skeleton--text" style="width: 70%; margin-top: 8px;" />
                            </div>
                        </div>
                    </template>

                    <div v-else-if="visibleCommitments.length === 0" class="mc-empty">
                        <i class="pi pi-list mc-empty__icon" />
                        <div class="mc-empty__title">Nenhum compromisso encontrado</div>
                        <div class="mc-empty__hint">
                            <template v-if="filters.global.value || typeFilter !== 'all'">
                                Ajuste os filtros pra ver mais resultados.
                            </template>
                            <template v-else>
                                Crie seu primeiro tipo de compromisso.
                            </template>
                        </div>
                        <button class="mc-act-btn mc-act-btn--primary" @click="openCreate()">
                            <i class="pi pi-plus" />
                            <span>Novo compromisso</span>
                        </button>
                    </div>

                    <div
                        v-for="c in visibleCommitments"
                        v-else
                        :key="c.id"
                        class="mc-card"
                        :class="{ 'is-inactive': !c.active }"
                        @click="openEdit(c)"
                    >
                        <span
                            class="mc-card__color"
                            :style="{ background: c.bg_color ? `#${c.bg_color}` : 'var(--m-bg-soft-hover)' }"
                        />
                        <div class="mc-card__main">
                            <div class="mc-card__name-row">
                                <span class="mc-card__name">{{ c.name }}</span>
                                <span v-if="c.is_native" class="mc-card__badge mc-card__badge--native">
                                    <i class="pi pi-shield" /> Nativo
                                </span>
                                <span v-if="!c.active" class="mc-card__badge mc-card__badge--off">Inativo</span>
                            </div>
                            <div v-if="c.description" class="mc-card__desc">{{ c.description }}</div>
                            <div class="mc-card__meta">
                                <span class="mc-card__meta-item" v-tooltip.top="'Tempo total registrado'">
                                    <i class="pi pi-clock" />
                                    {{ formatMinutes(getTotalMinutes(c.id)) }}
                                </span>
                                <span class="mc-card__meta-item" v-tooltip.top="'Campos extras'">
                                    <i class="pi pi-list" />
                                    {{ (c.fields || []).length }} {{ (c.fields || []).length === 1 ? 'campo' : 'campos' }}
                                </span>
                            </div>
                        </div>
                        <div class="mc-card__actions" @click.stop>
                            <ToggleSwitch
                                v-model="c.active"
                                :disabled="isActiveLocked(c) || saving"
                                @change="onToggleActive(c)"
                                v-tooltip.left="isActiveLocked(c) ? 'Bloqueado' : (c.active ? 'Desativar' : 'Ativar')"
                            />
                            <button
                                class="mc-card__btn"
                                v-tooltip.left="'Editar'"
                                @click="openEdit(c)"
                            >
                                <i class="pi pi-pencil" />
                            </button>
                            <button
                                class="mc-card__btn mc-card__btn--danger"
                                v-tooltip.left="isDeleteLocked(c) ? 'Não pode excluir compromissos nativos' : 'Excluir'"
                                :disabled="isDeleteLocked(c)"
                                @click="confirmDelete(c)"
                            >
                                <i class="pi pi-trash" />
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Dialog de criar/editar — reutiliza o componente existente -->
        <DeterminedCommitmentDialog
            v-model="dlgOpen"
            :mode="dlgMode"
            :commitment="editing"
            :saving="saving"
            @save="onSave"
            @delete="onDelete"
        />
    </section>
</template>

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

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

/* Botões header (blueprint §11) */
.mc-close,
.mc-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;
}
.mc-close:hover,
.mc-head-btn:hover { background: var(--m-bg-soft-hover); }
.mc-head-btn > i { font-size: 0.85rem; }
.mc-head-btn--compact-only { display: none; }

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

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

/* Body — flex row em desktop, column em mobile */
.mc-body {
    flex: 1;
    display: flex;
    min-height: 0;
    position: relative;
    gap: 12px;
    padding: 12px;
}

/* ═══ COL 1: aside esquerda ═══ */
.mc-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;
}
.mc-side::-webkit-scrollbar { width: 5px; }
.mc-side::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

/* Widget container (blueprint §12 — radius 12px) */
.mc-w {
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-radius: 12px;
    padding: 12px;
}
.mc-w__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}
.mc-w__title {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 0.78rem;
    font-weight: 600;
    color: var(--m-text);
}
.mc-w__title > i { color: var(--m-text-muted); font-size: 0.78rem; }

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

/* Filtros side */
.mc-side__filters {
    display: flex;
    flex-direction: column;
    gap: 10px;
}
.mc-side__label {
    text-transform: uppercase;
    letter-spacing: 0.12em;
    color: var(--m-text-muted);
    font-size: 0.62rem;
    font-weight: 600;
    margin-bottom: 6px;
}
.mc-side__clear-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: transparent;
    border: 1px solid var(--m-border);
    color: var(--m-text-muted);
    padding: 6px 10px;
    border-radius: 8px;
    font-family: inherit;
    font-size: 0.72rem;
    cursor: pointer;
    transition: background-color 140ms ease, color 140ms ease;
    align-self: flex-start;
}
.mc-side__clear-btn:hover {
    background: var(--m-bg-soft-hover);
    color: var(--m-text);
}

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

/* Card (blueprint §12 — item dentro de card 10px) */
.mc-card {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 14px;
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-radius: 10px;
    cursor: pointer;
    transition: background-color 140ms ease, border-color 140ms ease, transform 140ms ease;
    text-align: left;
}
.mc-card:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    transform: translateY(-1px);
}
.mc-card.is-inactive { opacity: 0.6; }
.mc-card--skeleton { cursor: default; pointer-events: none; opacity: 0.95; }
.mc-card--skeleton:hover { background: var(--m-bg-soft); transform: none; }

.mc-card__color {
    width: 6px;
    height: 40px;
    border-radius: 3px;
    flex-shrink: 0;
}
.mc-card__main {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 2px;
}
.mc-card__name-row {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}
.mc-card__name {
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--m-text);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mc-card__desc {
    font-size: 0.78rem;
    color: var(--m-text-muted);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mc-card__meta {
    display: flex;
    gap: 14px;
    margin-top: 4px;
    font-size: 0.7rem;
    color: var(--m-text-muted);
}
.mc-card__meta-item {
    display: inline-flex;
    align-items: center;
    gap: 5px;
}
.mc-card__meta-item > i { font-size: 0.7rem; }

.mc-card__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;
}
.mc-card__badge--native {
    color: rgb(96, 165, 250);
    background: rgba(96, 165, 250, 0.12);
    border: 1px solid rgba(96, 165, 250, 0.3);
}
.mc-card__badge--off {
    color: var(--m-text-muted);
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
}
.mc-card__badge > i { font-size: 0.55rem; }

.mc-card__actions {
    display: flex;
    align-items: center;
    gap: 6px;
    flex-shrink: 0;
}
.mc-card__btn {
    width: 28px;
    height: 28px;
    display: grid;
    place-items: center;
    background: transparent;
    border: 1px solid var(--m-border);
    color: var(--m-text-muted);
    border-radius: 9px;
    cursor: pointer;
    font-family: inherit;
    transition: background-color 140ms ease, color 140ms ease, border-color 140ms ease;
}
.mc-card__btn:hover {
    background: var(--m-bg-soft-hover);
    color: var(--m-text);
}
.mc-card__btn--danger:hover {
    background: rgba(239, 68, 68, 0.15);
    border-color: rgba(239, 68, 68, 0.4);
    color: rgb(248, 113, 113);
}
.mc-card__btn:disabled { opacity: 0.4; cursor: not-allowed; }
.mc-card__btn > i { font-size: 0.7rem; }

/* Empty state (blueprint §12 — teto 12px) */
.mc-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;
}
.mc-empty__icon {
    font-size: 2rem;
    color: var(--m-text-faint);
    margin-bottom: 4px;
}
.mc-empty__title {
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--m-text);
}
.mc-empty__hint {
    font-size: 0.78rem;
    color: var(--m-text-muted);
    margin-bottom: 8px;
}

/* Popover de Ações (blueprint §10) */
.mc-actions {
    display: flex;
    flex-direction: column;
    gap: 14px;
    min-width: 240px;
    padding: 4px;
}
.mc-actions__group {
    display: flex;
    flex-direction: column;
    gap: 6px;
}
.mc-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) */
.mc-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;
}
.mc-mobile-drawer.is-open { transform: translateX(0); }
.mc-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;
}
.mc-mobile-drawer__scroll::-webkit-scrollbar { width: 5px; }
.mc-mobile-drawer__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}
.mc-mobile-drawer__scroll .mc-side {
    width: 100%;
    height: auto;
    overflow: visible;
    padding: 0;
    flex-shrink: 0;
}

.mc-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;
}
.mc-drawer-fade-enter-active,
.mc-drawer-fade-leave-active { transition: opacity 200ms ease; }
.mc-drawer-fade-enter-from,
.mc-drawer-fade-leave-to { opacity: 0; }

/* ═══ Compact (<xl) — botão "Ações" e remover busca inline da side ═══ */
@media (max-width: 1279px) {
    .mc-head-btn--compact-only { display: grid; }
    .mc-act-btn--primary span { display: inline; } /* mantém label "Novo" */
}

/* ═══ Mobile (<lg) — drawer + lista 100% ═══ */
@media (max-width: 1023px) {
    .mc-body { flex-direction: column; padding: 8px; }
    .mc-main { width: 100%; }
    .mc-page__title > span:first-of-type { display: none; }
    .mc-menu-btn--mobile-only { display: inline-flex; }
    .mc-card__actions { gap: 4px; }
    .mc-card__desc { white-space: normal; }
    /* Em mobile o "Novo" só ícone pra economizar espaço */
    .mc-act-btn--primary span { display: none; }
    .mc-act-btn--primary { width: 32px; padding: 0; justify-content: center; }
}
</style>
