<script setup>
/*
 * MelissaLinkExterno — Página nativa Melissa pra "Link externo de cadastro"
 * (substitui o embed via MelissaEmbed que duplicava headers).
 *
 * Layout 2-col:
 *   - COL 1 — Esquerda (flex 1): card "Seu link público" + card
 *            "Mensagem pronta"
 *   - COL 2 — Direita (~280px): card "Como funciona" + card "Boas práticas"
 *
 * Lógica idêntica à PatientsExternalLinkPage (RPC issue_patient_invite +
 * rotate_patient_invite_token_v2 + copy/openLink). Só o chrome muda pra
 * casar com o blueprint Melissa (1 header só, sem hero sticky redundante).
 */
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useToast } from 'primevue/usetoast';
import { supabase } from '@/lib/supabase/client';
import CadastroExternoPreview from '@/components/cadastro/CadastroExternoPreview.vue';
// Button/InputText/InputGroup/InputGroupAddon/Message: auto via PrimeVueResolver

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

// ── Estado ─────────────────────────────────────────────────
const inviteToken = ref('');
const rotating = ref(false);
const loading = ref(false);

// ── Breakpoints + drawer ───────────────────────────────────
const drawerOpen = ref(false);
const isMobile = ref(false);
const isWideDesktop = ref(false); // >= 1340px — preview vira painel flutuante fora do fake dialog
let _mqMobile = null;
let _mqWide = null;
function _onMqMobileChange(e) {
    isMobile.value = e.matches;
    if (!e.matches) drawerOpen.value = false;
}
function _onMqWideChange(e) { isWideDesktop.value = e.matches; }
function toggleDrawer() { drawerOpen.value = !drawerOpen.value; }
function fecharDrawer() { drawerOpen.value = false; }

// Onde o preview do celular e renderizado:
//   - mobile: dentro do main, no topo do conteudo (acima de tudo)
//   - mid-desktop (1024-1339): dentro da sidebar inline (apos cards info)
//   - wide-desktop (>=1340): painel flutuante fora do fake dialog
const previewTarget = computed(() => {
    if (isMobile.value) return '#ml-main-preview-target';
    if (isWideDesktop.value) return '#ml-floating-preview-target';
    return '#ml-sidebar-preview-target';
});

// ── Conteúdo estático ─────────────────────────────────────
const howItWorks = [
    { n: 1, title: 'Você envia o link', desc: 'Por WhatsApp, e-mail ou mensagem direta.' },
    { n: 2, title: 'O paciente preenche', desc: 'Campos opcionais podem ficar em branco. Menos fricção, mais adesão.' },
    { n: 3, title: 'Você recebe e converte', desc: 'O cadastro aparece em "Cadastros recebidos". Revise e converta em paciente quando quiser.' }
];

const goodPractices = [
    'Gere um novo link se suspeitar que ele foi repassado indevidamente.',
    'Informe o paciente que campos opcionais podem ficar em branco.',
    'Evite divulgar em público; é um link para compartilhamento individual.'
];

// ── URL base ──────────────────────────────────────────────
const origin = computed(() => {
    return typeof window !== 'undefined' ? window.location.origin : '';
});

const publicUrl = computed(() => {
    if (!inviteToken.value) return '';
    return `${origin.value}/cadastro/paciente?t=${encodeURIComponent(inviteToken.value)}`;
});

// ── RPC: issue + rotate ───────────────────────────────────
// Tokens são gerados no SERVIDOR via gen_random_uuid() — cliente nunca
// gera (segurança: elimina fallback Math.random).
async function loadOrCreateInvite() {
    loading.value = true;
    try {
        const { data, error } = await supabase.rpc('issue_patient_invite');
        if (error) throw error;
        inviteToken.value = data;
    } catch (err) {
        toast.add({ severity: 'error', summary: 'Erro', detail: err?.message || 'Falha ao carregar link.', life: 3500 });
    } finally {
        loading.value = false;
    }
}

async function rotateLink() {
    rotating.value = true;
    try {
        const { data, error } = await supabase.rpc('rotate_patient_invite_token_v2');
        if (error) throw error;
        inviteToken.value = data;
        toast.add({ severity: 'success', summary: 'Pronto', detail: 'Novo link gerado. O anterior foi revogado.', life: 2500 });
    } catch (err) {
        toast.add({ severity: 'error', summary: 'Erro', detail: err?.message || 'Falha ao gerar novo link.', life: 3500 });
    } finally {
        rotating.value = false;
    }
}

// ── Copy/open helpers ─────────────────────────────────────
async function copyLink() {
    try {
        if (!publicUrl.value) return;
        await navigator.clipboard.writeText(publicUrl.value);
        toast.add({ severity: 'success', summary: 'Copiado', detail: 'Link copiado para a área de transferência.', life: 1500 });
    } catch {
        window.prompt('Copie o link:', publicUrl.value);
    }
}

function openLink() {
    if (!publicUrl.value) return;
    window.open(publicUrl.value, '_blank', 'noopener');
}

async function copyInviteMessage() {
    try {
        if (!publicUrl.value) return;
        const msg = `Olá! Segue o link para seu pré-cadastro. Preencha com calma — campos opcionais podem ficar em branco:\n${publicUrl.value}`;
        await navigator.clipboard.writeText(msg);
        toast.add({ severity: 'success', summary: 'Copiado', detail: 'Mensagem copiada para a área de transferência.', life: 1500 });
    } catch {
        toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Não foi possível copiar automaticamente.', life: 2500 });
    }
}

// ── Lifecycle ──────────────────────────────────────────────
onMounted(async () => {
    if (typeof window !== 'undefined' && window.matchMedia) {
        _mqMobile = window.matchMedia('(max-width: 1023px)');
        isMobile.value = _mqMobile.matches;
        try { _mqMobile.addEventListener('change', _onMqMobileChange); }
        catch { _mqMobile.addListener(_onMqMobileChange); }

        _mqWide = window.matchMedia('(min-width: 1340px)');
        isWideDesktop.value = _mqWide.matches;
        try { _mqWide.addEventListener('change', _onMqWideChange); }
        catch { _mqWide.addListener(_onMqWideChange); }
    }
    await loadOrCreateInvite();
});

onBeforeUnmount(() => {
    if (_mqMobile) {
        try { _mqMobile.removeEventListener('change', _onMqMobileChange); }
        catch { _mqMobile.removeListener(_onMqMobileChange); }
    }
    if (_mqWide) {
        try { _mqWide.removeEventListener('change', _onMqWideChange); }
        catch { _mqWide.removeListener(_onMqWideChange); }
    }
});
</script>

<template>
    <Transition name="ml-drawer-fade">
        <div
            v-show="isMobile && drawerOpen"
            class="ml-mobile-drawer"
            :class="{ 'is-open': drawerOpen }"
        >
            <div id="ml-mobile-drawer-target" class="ml-mobile-drawer__scroll" />
        </div>
    </Transition>
    <Transition name="ml-drawer-fade">
        <div
            v-show="isMobile && drawerOpen"
            class="ml-mobile-drawer__backdrop"
            @click="fecharDrawer"
        />
    </Transition>

    <!-- Painel flutuante do Preview (wide-desktop >=1340px). Vive FORA do
         fake dialog, ancorado a sua right edge + 14px gap. Em mobile o
         preview teleporta pro #ml-main-preview-target (topo do main); em
         mid-desktop (1024-1339) teleporta pro #ml-sidebar-preview-target. -->
    <aside id="ml-floating-preview-target" class="ml-floating-preview" aria-label="Pré-visualização do link externo"></aside>

    <section class="ml-page">
        <!-- Header único (sem hero sticky — só o chrome Melissa) -->
        <header class="ml-page__head">
            <button
                class="ml-menu-btn ml-menu-btn--mobile-only"
                v-tooltip.bottom="'Como funciona & Boas práticas'"
                @click="toggleDrawer"
            >
                <i class="pi pi-bars" />
                <span>Menu</span>
            </button>
            <div class="ml-page__title">
                <i class="pi pi-share-alt ml-page__title-icon" />
                <span>Link externo de cadastro</span>
                <span
                    class="ml-page__status"
                    :class="inviteToken ? 'is-active' : 'is-loading'"
                >
                    <span class="ml-page__status-dot" />
                    {{ inviteToken ? 'Link ativo' : 'Gerando…' }}
                </span>
            </div>
            <div class="ml-page__actions">
                <button
                    class="ml-act-btn ml-act-btn--primary"
                    v-tooltip.bottom="'Gera um novo token e revoga o anterior'"
                    :disabled="rotating || !inviteToken"
                    @click="rotateLink"
                >
                    <i :class="rotating ? 'pi pi-spin pi-spinner' : 'pi pi-refresh'" />
                    <span>Gerar novo link</span>
                </button>
                <button
                    class="ml-head-btn"
                    v-tooltip.bottom="'Recarregar'"
                    :disabled="loading"
                    @click="loadOrCreateInvite"
                >
                    <i :class="loading ? 'pi pi-spin pi-spinner' : 'pi pi-refresh'" />
                </button>
                <button class="ml-close" v-tooltip.bottom="'Voltar (Esc)'" @click="emit('close')">
                    <i class="pi pi-times" />
                </button>
            </div>
        </header>

        <!-- Subheader explicativo -->
        <div class="ml-subheader">
            <i class="pi pi-info-circle ml-subheader__icon" />
            <span class="ml-subheader__text">
                Link público pra pacientes preencherem o pré-cadastro online.
                <strong>Compartilhe</strong> por WhatsApp/email; o cadastro chega em
                <strong>Cadastros Recebidos</strong> pra você converter em paciente.
            </span>
        </div>

        <!-- Body 2-col -->
        <div class="ml-body">
            <!-- ═══ COL 1: Sidebar (Como funciona / Boas práticas) — esquerda ═══ -->
            <Teleport to="#ml-mobile-drawer-target" :disabled="!isMobile">
                <aside class="ml-side">
                    <!-- Como funciona -->
                    <div class="ml-card">
                        <div class="ml-card__head ml-card__head--simple">
                            <div class="ml-info-head">
                                <span class="ml-info-head__icon ml-info-head__icon--primary">
                                    <i class="pi pi-list-check" />
                                </span>
                                <div>
                                    <div class="ml-info-head__title">Como funciona</div>
                                    <div class="ml-info-head__sub">Simples e sem fricção pro paciente</div>
                                </div>
                            </div>
                        </div>
                        <ol class="ml-steps">
                            <li v-for="step in howItWorks" :key="step.n" class="ml-steps__item">
                                <div class="ml-steps__num">{{ step.n }}</div>
                                <div class="ml-steps__text">
                                    <div class="ml-steps__title">{{ step.title }}</div>
                                    <div class="ml-steps__desc">{{ step.desc }}</div>
                                </div>
                            </li>
                        </ol>
                    </div>

                    <!-- Boas práticas -->
                    <div class="ml-card">
                        <div class="ml-card__head ml-card__head--simple">
                            <div class="ml-info-head">
                                <span class="ml-info-head__icon ml-info-head__icon--success">
                                    <i class="pi pi-shield" />
                                </span>
                                <div>
                                    <div class="ml-info-head__title">Boas práticas</div>
                                    <div class="ml-info-head__sub">Segurança e privacidade</div>
                                </div>
                            </div>
                        </div>
                        <ul class="ml-tips">
                            <li v-for="tip in goodPractices" :key="tip" class="ml-tips__item">
                                <i class="pi pi-check ml-tips__check" />
                                <span>{{ tip }}</span>
                            </li>
                        </ul>
                    </div>

                    <!-- Target do Teleport do Preview pra modo sidebar (mid-desktop 1024-1339).
                         Em mobile vai pro #ml-main-preview-target; em wide-desktop pro floating. -->
                    <div id="ml-sidebar-preview-target" class="ml-sidebar-preview-target" />
                </aside>
            </Teleport>

            <!-- ═══ COL 2: Main (Link + Mensagem) ═══ -->
            <div class="ml-main">
                <!-- Target do Teleport do Preview pra modo mobile (acima de tudo no main).
                     Em desktop fica oculto via CSS e o preview teleporta pra sidebar/floating. -->
                <div id="ml-main-preview-target" class="ml-main-preview-target" />

                <!-- Card: Seu link público -->
                <div class="ml-card">
                    <div class="ml-card__head">
                        <div class="ml-card__title">
                            <span class="ml-card__title-text">Seu link público</span>
                            <span class="ml-card__sub">Envie ao paciente por WhatsApp, e-mail ou mensagem direta</span>
                        </div>
                        <span
                            class="ml-card__status"
                            :class="inviteToken ? 'is-active' : 'is-loading'"
                        >
                            <span class="ml-card__status-dot" />
                            {{ inviteToken ? 'Ativo' : 'Gerando…' }}
                        </span>
                    </div>

                    <div class="ml-card__body">
                        <!-- Skeleton enquanto carrega -->
                        <div v-if="!inviteToken" class="ml-skel">
                            <div class="ml-skel__bar" />
                            <div class="ml-skel__bar" />
                        </div>

                        <div v-else class="flex flex-col gap-4">
                            <!-- InputGroup do link -->
                            <InputGroup>
                                <InputGroupAddon><i class="pi pi-link" /></InputGroupAddon>
                                <InputText
                                    readonly
                                    :value="publicUrl"
                                    class="font-mono text-[0.78rem]"
                                />
                                <Button icon="pi pi-copy" severity="secondary" v-tooltip.top="'Copiar'" @click="copyLink" />
                                <Button icon="pi pi-external-link" severity="secondary" v-tooltip.top="'Abrir'" @click="openLink" />
                            </InputGroup>

                            <div class="ml-token-line">
                                Token: <span class="font-mono select-all opacity-60">{{ inviteToken }}</span>
                            </div>

                            <!-- 2 CTAs grandes -->
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                                <button class="ml-cta" @click="copyLink">
                                    <div class="ml-cta__icon ml-cta__icon--primary">
                                        <i class="pi pi-copy" />
                                    </div>
                                    <div class="ml-cta__text">
                                        <div class="ml-cta__title">Copiar link</div>
                                        <div class="ml-cta__sub">Cole no WhatsApp ou e-mail</div>
                                    </div>
                                </button>

                                <button class="ml-cta" @click="copyInviteMessage">
                                    <div class="ml-cta__icon ml-cta__icon--success">
                                        <i class="pi pi-comment" />
                                    </div>
                                    <div class="ml-cta__text">
                                        <div class="ml-cta__title">Copiar mensagem pronta</div>
                                        <div class="ml-cta__sub">Texto formatado com o link incluso</div>
                                    </div>
                                </button>
                            </div>

                            <!-- Aviso -->
                            <Message severity="warn" :closable="false">
                                <b>Dica:</b> ao gerar um novo link, o anterior é revogado.
                                Use isso quando quiser invalidar um link já compartilhado.
                            </Message>
                        </div>
                    </div>
                </div>

                <!-- Card: Mensagem pronta -->
                <div class="ml-card">
                    <div class="ml-card__head ml-card__head--simple">
                        <div class="ml-card__title">
                            <span class="ml-card__title-text">
                                <i class="pi pi-comment ml-card__title-icon" />
                                Mensagem pronta para envio
                            </span>
                            <span class="ml-card__sub">Copie e cole ao enviar o link ao paciente</span>
                        </div>
                    </div>
                    <div class="ml-card__body">
                        <div class="ml-msg-preview">
                            Olá! Segue o link para seu pré-cadastro. Preencha com calma —
                            campos opcionais podem ficar em branco:
                            <span class="ml-msg-preview__link">{{ publicUrl || '…aguardando link…' }}</span>
                        </div>
                        <div class="mt-3">
                            <Button
                                icon="pi pi-copy"
                                label="Copiar mensagem"
                                severity="secondary"
                                outlined
                                class="rounded-full"
                                :disabled="!publicUrl"
                                @click="copyInviteMessage"
                            />
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </section>

    <!-- ── Card de Pré-visualização (Teleport). O target alterna conforme o
         viewport: topo do main (mobile) / sidebar (mid-desktop) / painel
         flutuante fora do fake dialog (wide-desktop). -->
    <Teleport :to="previewTarget">
        <div class="ml-card ml-card--preview">
            <div class="ml-card__head ml-card__head--simple">
                <div class="ml-info-head">
                    <span class="ml-info-head__icon ml-info-head__icon--primary">
                        <i class="pi pi-mobile" />
                    </span>
                    <div>
                        <div class="ml-info-head__title">Pré-visualização</div>
                        <div class="ml-info-head__sub">Como o paciente vê o link</div>
                    </div>
                </div>
            </div>
            <div class="ml-card__body ml-card__body--preview">
                <CadastroExternoPreview :token="inviteToken" />
            </div>
        </div>
    </Teleport>
</template>

<style scoped>
/* ─── Page chrome (espelha demais Melissa Pages) ─── */
.ml-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: ml-page-enter 240ms cubic-bezier(0.2, 0.7, 0.3, 1);
}
@keyframes ml-page-enter {
    from { opacity: 0; transform: scale(0.985); }
    to   { opacity: 1; transform: scale(1); }
}

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

/* Status pill no header (Link ativo / Gerando) */
.ml-page__status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 0.7rem;
    font-weight: 600;
    padding: 2px 10px;
    border-radius: 999px;
    border: 1px solid;
    text-transform: none;
    letter-spacing: 0;
}
.ml-page__status.is-active {
    color: rgb(22, 163, 74);
    background: rgba(22, 163, 74, 0.10);
    border-color: rgba(22, 163, 74, 0.35);
}
.ml-page__status.is-loading {
    color: var(--m-text-muted);
    background: var(--m-bg-soft);
    border-color: var(--m-border);
}
.ml-page__status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: currentColor;
}
.ml-page__status.is-active .ml-page__status-dot {
    animation: ml-pulse 1.6s ease-in-out infinite;
}
@keyframes ml-pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.45; }
}

.ml-page__actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

.ml-close, .ml-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;
}
.ml-close:hover, .ml-head-btn:hover { background: var(--m-bg-soft-hover); }
.ml-head-btn > i { font-size: 0.85rem; }
.ml-head-btn:disabled { opacity: 0.5; cursor: not-allowed; }

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

/* Botao "Menu" mobile (abre drawer com Como funciona / Boas praticas) */
.ml-menu-btn {
    display: none;
    align-items: center;
    gap: 6px;
    padding: 6px 10px;
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-radius: 8px;
    color: var(--m-text);
    cursor: pointer;
    font-family: inherit;
    font-size: 0.78rem;
    font-weight: 600;
    transition: background-color 140ms ease;
}
.ml-menu-btn:hover { background: var(--m-bg-soft-hover); }
.ml-menu-btn > i { font-size: 0.78rem; color: var(--p-primary-color); }

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

/* Body 2-col */
.ml-body {
    flex: 1;
    display: flex;
    min-height: 0;
    gap: 12px;
    padding: 12px;
    overflow-y: auto;
}

/* ─── Col 1: Main (link + mensagem) ─── */
.ml-main {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 12px;
}

/* ─── Col 1: Aside (instruções) — agora à ESQUERDA, drawer no mobile ─── */
.ml-side {
    width: 320px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 12px;
    overflow-y: auto;
    overflow-x: hidden;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.ml-side::-webkit-scrollbar { width: 5px; }
.ml-side::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}

/* Card-base */
.ml-card {
    background: var(--m-bg-soft);
    border: 1px solid var(--m-border);
    border-radius: 12px;
    overflow: hidden;
}
.ml-card__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 14px 16px 12px;
    border-bottom: 1px solid var(--m-border);
    flex-wrap: wrap;
}
.ml-card__head--simple { border-bottom: 1px solid var(--m-border); }
.ml-card__title {
    display: flex;
    flex-direction: column;
    gap: 2px;
    min-width: 0;
    flex: 1;
}
.ml-card__title-text {
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--m-text);
    display: inline-flex;
    align-items: center;
    gap: 6px;
}
.ml-card__title-icon {
    font-size: 0.92rem;
    color: var(--m-text-muted);
}
.ml-card__sub {
    font-size: 0.74rem;
    color: var(--m-text-muted);
}
.ml-card__body {
    padding: 16px;
}

.ml-card__status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 0.7rem;
    font-weight: 600;
    padding: 3px 10px;
    border-radius: 999px;
    border: 1px solid;
    flex-shrink: 0;
}
.ml-card__status.is-active {
    color: rgb(22, 163, 74);
    background: rgba(22, 163, 74, 0.10);
    border-color: rgba(22, 163, 74, 0.35);
}
.ml-card__status.is-loading {
    color: var(--m-text-muted);
    background: var(--m-bg-medium);
    border-color: var(--m-border);
}
.ml-card__status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: currentColor;
}
.ml-card__status.is-active .ml-card__status-dot {
    animation: ml-pulse 1.6s ease-in-out infinite;
}

/* Skeleton */
.ml-skel {
    display: flex;
    flex-direction: column;
    gap: 12px;
}
.ml-skel__bar {
    height: 40px;
    border-radius: 8px;
    background: linear-gradient(90deg,
        var(--m-bg-medium) 0%,
        var(--m-bg-soft-hover) 50%,
        var(--m-bg-medium) 100%);
    background-size: 200% 100%;
    animation: ml-skel-shimmer 1.4s ease-in-out infinite;
}
@keyframes ml-skel-shimmer {
    0% { background-position: 200% 0; }
    100% { background-position: -200% 0; }
}

/* InputGroup tweaks */
.ml-card :deep(.p-inputgroup) {
    width: 100%;
}

/* Token line */
.ml-token-line {
    font-size: 0.74rem;
    color: var(--m-text-muted);
}

/* CTAs grandes */
.ml-cta {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 14px;
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    border-radius: 10px;
    cursor: pointer;
    text-align: left;
    font-family: inherit;
    color: var(--m-text);
    transition: background-color 140ms ease, border-color 140ms ease, transform 140ms ease, box-shadow 140ms ease;
}
.ml-cta:hover {
    background: var(--m-bg-soft-hover);
    border-color: var(--m-border-strong);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}
.ml-cta__icon {
    width: 36px;
    height: 36px;
    display: grid;
    place-items: center;
    border-radius: 9px;
    flex-shrink: 0;
    font-size: 1rem;
}
.ml-cta__icon--primary {
    background: color-mix(in srgb, var(--p-primary-color) 15%, transparent);
    color: var(--p-primary-color);
}
.ml-cta__icon--success {
    background: rgba(22, 163, 74, 0.15);
    color: rgb(22, 163, 74);
}
.ml-cta__text {
    flex: 1;
    min-width: 0;
}
.ml-cta__title {
    font-size: 0.88rem;
    font-weight: 600;
    color: var(--m-text);
}
.ml-cta__sub {
    font-size: 0.74rem;
    color: var(--m-text-muted);
    margin-top: 2px;
}

/* Mensagem preview */
.ml-msg-preview {
    background: var(--m-bg-medium);
    border: 1px solid var(--m-border);
    border-radius: 10px;
    padding: 14px 16px;
    font-size: 0.85rem;
    color: var(--m-text);
    line-height: 1.55;
}
.ml-msg-preview__link {
    display: block;
    margin-top: 8px;
    font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
    font-size: 0.74rem;
    color: var(--m-text-muted);
    word-break: break-all;
}

/* Side: Instructions cards */
.ml-info-head {
    display: flex;
    align-items: center;
    gap: 10px;
    min-width: 0;
}
.ml-info-head__icon {
    width: 32px;
    height: 32px;
    display: grid;
    place-items: center;
    border-radius: 8px;
    flex-shrink: 0;
    font-size: 0.92rem;
}
.ml-info-head__icon--primary {
    background: color-mix(in srgb, var(--p-primary-color) 15%, transparent);
    color: var(--p-primary-color);
}
.ml-info-head__icon--success {
    background: rgba(22, 163, 74, 0.15);
    color: rgb(22, 163, 74);
}
.ml-info-head__title {
    font-size: 0.88rem;
    font-weight: 700;
    color: var(--m-text);
}
.ml-info-head__sub {
    font-size: 0.7rem;
    color: var(--m-text-muted);
    margin-top: 2px;
}

/* Steps (Como funciona) */
.ml-steps {
    list-style: none;
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
}
.ml-steps__item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 12px 16px;
    border-bottom: 1px solid var(--m-border);
}
.ml-steps__item:last-child { border-bottom: none; }
.ml-steps__num {
    width: 26px;
    height: 26px;
    display: grid;
    place-items: center;
    border-radius: 8px;
    background: color-mix(in srgb, var(--p-primary-color) 15%, transparent);
    color: var(--p-primary-color);
    font-size: 0.78rem;
    font-weight: 700;
    flex-shrink: 0;
    margin-top: 1px;
}
.ml-steps__text { flex: 1; min-width: 0; }
.ml-steps__title {
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--m-text);
}
.ml-steps__desc {
    font-size: 0.74rem;
    color: var(--m-text-muted);
    margin-top: 2px;
    line-height: 1.5;
}

/* Tips (Boas práticas) */
.ml-tips {
    list-style: none;
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
}
.ml-tips__item {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 10px 16px;
    border-bottom: 1px solid var(--m-border);
    font-size: 0.82rem;
    color: var(--m-text-muted);
    line-height: 1.5;
}
.ml-tips__item:last-child { border-bottom: none; }
.ml-tips__check {
    color: rgb(22, 163, 74);
    margin-top: 3px;
    flex-shrink: 0;
    font-size: 0.78rem;
}

/* Mobile: 2-col vira 1-col, instruções viraram drawer (escondido por default) */
@media (max-width: 1023px) {
    .ml-body {
        flex-direction: column;
        padding: 8px;
    }
    /* Em mobile, sidebar inline e escondida (vai pro drawer via Teleport) */
    .ml-body > .ml-side { display: none; }
    .ml-page__title > span:not(.ml-page__title-icon):not(.ml-page__status) {
        font-size: 0.92rem;
    }
    .ml-page__status { display: none; }
    .ml-act-btn--primary span { display: none; }
    .ml-act-btn--primary { width: 32px; padding: 0; justify-content: center; }
    .ml-menu-btn { display: inline-flex; }
}

/* ═══════ Mobile drawer (esquerda, com Como funciona / Boas práticas) ═══════ */
.ml-mobile-drawer {
    position: fixed;
    top: 0; left: 0;
    height: 100vh;
    height: 100dvh;
    width: min(380px, 90vw);
    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;
}
.ml-mobile-drawer.is-open { transform: translateX(0); }
.ml-mobile-drawer__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;
}
.ml-mobile-drawer__scroll::-webkit-scrollbar { width: 5px; }
.ml-mobile-drawer__scroll::-webkit-scrollbar-thumb {
    background: var(--m-border-strong);
    border-radius: 3px;
}
.ml-mobile-drawer__scroll .ml-side {
    width: 100%;
    overflow: visible;
}

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

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

/* ═══════ Painel flutuante do Preview (wide-desktop >= 1340px) ═══════
   Vive FORA do fake dialog, ancorado a sua right edge + 14px gap.
   Largura 320px pra acomodar o phone-frame (260px + bordas + padding). */
.ml-floating-preview {
    display: none; /* default: oculto. Wide-desktop ativa via @media abaixo. */
    position: absolute;
    top: 6px;
    max-height: calc(100% - var(--m-dock-h, 76px) - 12px);
    width: 320px;
    z-index: 39;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0;
    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);
    color: var(--m-text);
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
    scrollbar-width: thin;
    scrollbar-color: var(--m-border-strong) transparent;
}
.ml-floating-preview::-webkit-scrollbar { width: 5px; }
.ml-floating-preview::-webkit-scrollbar-thumb { background: var(--m-border-strong); border-radius: 3px; }

/* Card de preview ganha estilo distinto pra destacar do .ml-card padrao */
.ml-card--preview {
    background: var(--m-bg-medium);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.16);
}
.ml-card__body--preview {
    padding: 14px;
}

/* Placeholders do preview na sidebar/main: nao introduzem wrapper visivel.
   Os filhos teleportados se posicionam como flex items diretos do parent. */
.ml-sidebar-preview-target,
.ml-main-preview-target { display: contents; }

/* Hide rules por breakpoint */
@media (max-width: 1023px) {
    .ml-sidebar-preview-target { display: none; }
}
@media (min-width: 1024px) {
    .ml-main-preview-target { display: none; }
}

/* Dentro do painel flutuante, o card perde o "card-em-card":
   sem fundo/borda/sombra propria (o glass do painel ja faz esse papel). */
.ml-floating-preview > .ml-card--preview {
    background: transparent;
    border: none;
    box-shadow: none;
    border-radius: 0;
}
.ml-floating-preview > .ml-card--preview > .ml-card__head {
    border-bottom: 1px solid var(--m-border);
    padding: 14px 18px;
}
.ml-floating-preview > .ml-card--preview > .ml-card__body--preview {
    padding: 14px 18px;
}

/* Wide-desktop: floating ativo, ancorado a right edge da .ml-page + 14px gap */
@media (min-width: 1340px) {
    .ml-floating-preview {
        display: block;
        left: calc(100% - max(6px, min(50%, calc(100% - 1006px))) + 14px);
    }
    .ml-sidebar-preview-target { display: none; }
}
</style>
