<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Arquivo: src/features/documents/components/DocumentTemplateEditor.vue
| Editor de template: edicao HTML, insercao de variaveis, preview ao vivo.
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, watch, computed, onMounted, onBeforeUnmount } from 'vue'
import { useDocumentTemplates } from '../composables/useDocumentTemplates'
import JoditEmailEditor from '@/components/ui/JoditEmailEditor.vue'

const props = defineProps({
    modelValue: { type: Object, default: () => ({}) },
    mode: { type: String, default: 'create' } // create | edit
})

const emit = defineEmits(['update:modelValue', 'save', 'cancel'])

const { TIPOS_TEMPLATE, TEMPLATE_VARIABLES, variablesGrouped, previewHtml } = useDocumentTemplates()

const activeTab = ref('editor')  // editor | preview
// Sub-tab do editor (centro do layout 3-col): qual seção renderiza
const editorTab = ref('corpo')  // cabecalho | corpo | rodape

// ── Form reativo synced com modelValue ──────────────────────

const form = ref({ ...defaultForm(), ...props.modelValue })

function defaultForm() {
    return {
        nome_template: '',
        tipo: 'outro',
        descricao: '',
        corpo_html: '',
        cabecalho_html: '',
        rodape_html: '',
        variaveis: [],
        logo_url: ''
    }
}

watch(() => props.modelValue, (val) => {
    form.value = { ...defaultForm(), ...val }
}, { deep: true })

watch(form, (val) => {
    emit('update:modelValue', { ...val })
}, { deep: true })

// ── Preview ─────────────────────────────────────────────────

const renderedPreview = computed(() => previewHtml(form.value.corpo_html))
const renderedCabecalho = computed(() => previewHtml(form.value.cabecalho_html || ''))
const renderedRodape = computed(() => previewHtml(form.value.rodape_html || ''))

// ── Inserir variavel no corpo ───────────────────────────────

const cursorField = ref('corpo_html') // qual campo esta ativo
const editorCabecalho = ref(null)
const editorCorpo = ref(null)
const editorRodape = ref(null)

function insertVariable(varKey) {
    const tag = `{{${varKey}}}`
    const editorMap = {
        cabecalho_html: editorCabecalho,
        corpo_html: editorCorpo,
        rodape_html: editorRodape
    }
    const editorRef = editorMap[cursorField.value]

    // No mobile: fecha drawer + defere insertHTML pós-transição.
    // Restaura a selection capturada quando o drawer abriu (cursor
    // original do usuário) antes de inserir → variável aparece no
    // ponto certo do texto, não no final.
    if (isMobile.value) {
        drawerOpen.value = false;
        const markers = savedSelection.value;
        setTimeout(() => {
            try {
                if (markers && editorRef?.value?.restoreSelection) {
                    editorRef.value.restoreSelection(markers);
                }
                if (editorRef?.value?.insertHTML) {
                    editorRef.value.insertHTML(tag);
                } else {
                    // Fallback se a API expose falhar
                    form.value[cursorField.value] = (form.value[cursorField.value] || '') + tag;
                }
            } catch {
                form.value[cursorField.value] = (form.value[cursorField.value] || '') + tag;
            }
            if (!form.value.variaveis.includes(varKey)) {
                form.value.variaveis = [...form.value.variaveis, varKey];
            }
            savedSelection.value = null;
        }, 280);
        return;
    }

    // Desktop: insertHTML mantém posição do cursor (foco já tá no editor)
    if (editorRef?.value?.insertHTML) {
        editorRef.value.insertHTML(tag)
    } else {
        form.value[cursorField.value] = (form.value[cursorField.value] || '') + tag
    }

    if (!form.value.variaveis.includes(varKey)) {
        form.value.variaveis = [...form.value.variaveis, varKey]
    }
}

// ── Save ────────────────────────────────────────────────────

function onSave() {
    emit('save', { ...form.value })
}

// ── Mobile drawer (espelha padrão MelissaBloqueios/Templates) ─
// No mobile, form (col 1) + variáveis (col 3) viram tabs dentro
// de um drawer único. Só o editor (col 2) fica visível na tela.
const drawerOpen = ref(false);
const drawerTab = ref('form'); // form | vars
const isMobile = ref(false);
let _mqMobile = null;
function _onMqMobileChange(e) {
    isMobile.value = e.matches;
    if (!e.matches) drawerOpen.value = false;
}
// Selection salva do editor ativo no momento de abrir o drawer de
// variáveis. Permite inserir na posição original do cursor mesmo
// depois do user navegar pelo drawer/perder foco.
const savedSelection = ref(null);

function openDrawer(tab) {
    drawerTab.value = tab || 'form';
    // Quando abre "Variáveis", salva selection do editor ativo agora
    // (cursor original do usuário) pra restaurar depois da inserção.
    if (tab === 'vars') {
        const editorMap = {
            cabecalho_html: editorCabecalho,
            corpo_html: editorCorpo,
            rodape_html: editorRodape
        };
        const editorRef = editorMap[cursorField.value];
        savedSelection.value = editorRef?.value?.saveSelection?.() || null;
    } else {
        savedSelection.value = null;
    }
    drawerOpen.value = true;
}
function fecharDrawer() {
    drawerOpen.value = false;
    savedSelection.value = null;
}

onMounted(() => {
    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); }
    }
});

onBeforeUnmount(() => {
    if (_mqMobile) {
        try { _mqMobile.removeEventListener('change', _onMqMobileChange); }
        catch { _mqMobile.removeListener(_onMqMobileChange); }
    }
});

</script>

<style scoped>
/* ═══════ Page chrome (preenche o espaço do container pai) ═══════ */
.dte-page {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 12px;
    min-height: 0;
    /* padding pra não grudar nas bordas do container pai (mdt-body) */
    padding: 12px;
    /* fallback pra quando o pai não é flex */
    height: 100%;
}

.dte-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    padding: 12px 16px;
    background: var(--surface-card);
    border: 1px solid var(--surface-border);
    border-radius: 10px;
    flex-shrink: 0;
}
.dte-toolbar__title {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 0.92rem;
    font-weight: 600;
    color: var(--text-color);
}
.dte-toolbar__title > i {
    color: var(--text-color-secondary);
    opacity: 0.7;
}
.dte-toolbar__tabs {
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

/* ═══════ 3-col grid (form / editor / variáveis) ═══════ */
.dte-cols {
    flex: 1;
    min-height: 0;
    display: grid;
    grid-template-columns: minmax(240px, 280px) minmax(0, 1fr) minmax(220px, 260px);
    gap: 12px;
    align-items: stretch;
}

/* COL 1 — Form metadados */
.dte-side {
    background: var(--surface-card);
    border: 1px solid var(--surface-border);
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    min-height: 0;
    overflow: hidden;
}
.dte-side__head {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 14px;
    border-bottom: 1px solid var(--surface-border);
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--text-color);
    flex-shrink: 0;
}
.dte-side__head > i {
    color: var(--text-color-secondary);
    opacity: 0.7;
}
.dte-side__body {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    padding: 14px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    scrollbar-width: thin;
}
.dte-field {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.dte-field label {
    font-size: 0.72rem;
    font-weight: 600;
    color: var(--text-color-secondary);
}

/* COL 2 — Editor com sub-tabs */
.dte-main {
    background: var(--surface-card);
    border: 1px solid var(--surface-border);
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    min-height: 0;
    overflow: hidden;
}
.dte-main__tabs {
    display: flex;
    align-items: center;
    gap: 0;
    border-bottom: 1px solid var(--surface-border);
    background: var(--surface-ground);
    flex-shrink: 0;
}
.dte-tab {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 18px;
    background: transparent;
    border: none;
    border-bottom: 2px solid transparent;
    color: var(--text-color-secondary);
    font-size: 0.85rem;
    font-weight: 600;
    cursor: pointer;
    transition: color 140ms ease, border-color 140ms ease, background-color 140ms ease;
    font-family: inherit;
}
.dte-tab:hover {
    color: var(--text-color);
    background: color-mix(in srgb, var(--p-primary-color) 4%, transparent);
}
.dte-tab.is-active {
    color: var(--p-primary-color);
    border-bottom-color: var(--p-primary-color);
    background: color-mix(in srgb, var(--p-primary-color) 6%, transparent);
}
.dte-tab > i { font-size: 0.82rem; }

.dte-main__editor {
    flex: 1;
    min-height: 0;
    overflow: hidden;
    padding: 14px;
    background: var(--surface-card);
    display: flex;
    flex-direction: column;
}
.dte-editor-wrap {
    flex: 1;
    min-height: 450px;
    display: flex;
    flex-direction: column;
}
.dte-editor-wrap > * {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
}

/* Força o Jodit interno a expandir 100% da altura disponível
   (substitui o height: minHeight em pixels que o JoditEmailEditor seta) */
.dte-editor-wrap :deep(.jodit-container) {
    flex: 1 !important;
    height: 100% !important;
    min-height: 450px !important;
    display: flex !important;
    flex-direction: column !important;
}
.dte-editor-wrap :deep(.jodit-workplace) {
    flex: 1 !important;
    min-height: 0 !important;
}
.dte-editor-wrap :deep(.jodit-wysiwyg) {
    min-height: 100% !important;
}

/* COL 3 — Variáveis */
.dte-vars {
    background: var(--surface-card);
    border: 1px solid var(--surface-border);
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    min-height: 0;
    overflow: hidden;
}
.dte-vars__head {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 14px 8px;
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--text-color);
    flex-shrink: 0;
}
.dte-vars__head > i {
    color: var(--p-primary-color);
}
.dte-vars__hint {
    margin: 0 14px 6px;
    font-size: 0.72rem;
    color: var(--text-color-secondary);
    line-height: 1.4;
    flex-shrink: 0;
}
.dte-vars__hint strong {
    color: var(--text-color);
}
.dte-vars__list {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    padding: 4px 10px 12px;
    display: flex;
    flex-direction: column;
    gap: 14px;
    scrollbar-width: thin;
}
.dte-vars__group {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.dte-vars__group-title {
    font-size: 0.62rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    color: var(--text-color-secondary);
    opacity: 0.75;
    padding: 0 4px;
}
.dte-vars__group-items {
    display: flex;
    flex-direction: column;
    gap: 2px;
}
.dte-vars__btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 6px 8px;
    background: transparent;
    border: none;
    border-radius: 6px;
    color: var(--text-color);
    font-size: 0.74rem;
    text-align: left;
    cursor: pointer;
    transition: background-color 120ms ease, color 120ms ease;
    font-family: inherit;
}
.dte-vars__btn:hover {
    background: color-mix(in srgb, var(--p-primary-color) 10%, transparent);
    color: var(--p-primary-color);
}
.dte-vars__btn-brace {
    font-family: 'JetBrains Mono', 'Consolas', monospace;
    font-size: 0.66rem;
    color: var(--p-primary-color);
    opacity: 0.6;
}
.dte-vars__btn-label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* ═══════ Preview ═══════ */
/* Container externo: scroll vertical interno + fundo sutil.
   NÃO usa flex (que limitava a altura intrínseca do doc) — usa
   block normal com o doc centralizado via margin auto. */
.dte-preview {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    background: var(--surface-ground);
    border: 1px solid var(--surface-border);
    border-radius: 10px;
    padding: 24px;
}
.dte-preview__doc {
    background: white;
    color: #1a1a1a;
    border-radius: 6px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    width: 100%;
    max-width: 794px; /* ≈ A4 a 96dpi */
    margin: 0 auto;
    padding: 48px 56px;
    font-family: 'Segoe UI', Arial, sans-serif;
    font-size: 12pt;
    line-height: 1.6;
    min-height: 500px;
    /* Garante que o background-white cresce com o conteúdo
       (em vez de ficar travado no min-height quando o doc é grande) */
    box-sizing: border-box;
    height: auto;
    overflow: visible;
}
.dte-preview__header {
    text-align: center;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ccc;
}
.dte-preview__body {
    min-height: 300px;
}
.dte-preview__footer {
    margin-top: 32px;
    padding-top: 12px;
    border-top: 1px solid #ccc;
    text-align: center;
    font-size: 10pt;
    color: #666;
}

/* ═══════ Toolbar mobile actions (botões "Identificação" / "Variáveis") ═══════ */
.dte-toolbar__mobile-actions {
    display: none;
    align-items: center;
    gap: 6px;
}
.dte-mobile-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 7px 12px;
    border-radius: 8px;
    border: 1px solid var(--surface-border);
    background: var(--surface-ground);
    color: var(--text-color);
    cursor: pointer;
    font-size: 0.78rem;
    font-weight: 600;
    flex-shrink: 0;
    font-family: inherit;
    transition: background-color 120ms ease;
}
.dte-mobile-btn:hover { background: color-mix(in srgb, var(--p-primary-color) 8%, transparent); }
.dte-mobile-btn > i { color: var(--p-primary-color); font-size: 0.82rem; }

/* ═══════ Mobile drawer (form + variáveis em tabs) ═══════ */
.dte-mobile-drawer {
    position: fixed;
    top: 0; left: 0;
    height: 100vh;
    height: 100dvh;
    width: min(360px, 92vw);
    z-index: 80;
    background: var(--surface-card);
    border-right: 1px solid var(--surface-border);
    transform: translateX(-100%);
    transition: transform 250ms cubic-bezier(0.4, 0, 0.2, 1);
    color: var(--text-color);
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
    display: flex;
    flex-direction: column;
    box-shadow: 4px 0 24px rgba(0, 0, 0, 0.18);
}
.dte-mobile-drawer.is-open { transform: translateX(0); }
/* Durante a transição de saída, drawer ignora eventos pra não capturar
   touch/click "perdidos" e prevenir trava no Jodit. */
.dte-mobile-drawer:not(.is-open) { pointer-events: none; }

.dte-mobile-drawer__tabs {
    display: flex;
    align-items: stretch;
    gap: 0;
    border-bottom: 1px solid var(--surface-border);
    background: var(--surface-ground);
    flex-shrink: 0;
}
.dte-drawer-tab {
    flex: 1;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 12px 14px;
    background: transparent;
    border: none;
    border-bottom: 2px solid transparent;
    color: var(--text-color-secondary);
    font-size: 0.82rem;
    font-weight: 600;
    cursor: pointer;
    font-family: inherit;
    transition: color 140ms ease, border-color 140ms ease, background-color 140ms ease;
}
.dte-drawer-tab:hover {
    color: var(--text-color);
    background: color-mix(in srgb, var(--p-primary-color) 4%, transparent);
}
.dte-drawer-tab.is-active {
    color: var(--p-primary-color);
    border-bottom-color: var(--p-primary-color);
}
.dte-drawer-tab > i { font-size: 0.82rem; }

.dte-drawer-close {
    width: 44px;
    display: grid;
    place-items: center;
    background: transparent;
    border: none;
    color: var(--text-color-secondary);
    cursor: pointer;
    border-left: 1px solid var(--surface-border);
    transition: background-color 120ms ease, color 120ms ease;
}
.dte-drawer-close:hover {
    background: var(--surface-ground);
    color: var(--text-color);
}

.dte-mobile-drawer__pane {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    scrollbar-width: thin;
}
.dte-mobile-drawer__pane > .dte-side,
.dte-mobile-drawer__pane > .dte-vars {
    border: none;
    border-radius: 0;
    flex: 1;
    width: 100%;
}

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

/* ═══════ Mobile (<1024px): só o editor visível ═══════ */
@media (max-width: 1023px) {
    /* Editor ocupa tela inteira — col 1 e col 3 viram drawer */
    .dte-cols {
        grid-template-columns: 1fr;
        overflow: hidden;
    }
    .dte-cols > .dte-side,
    .dte-cols > .dte-vars { display: none; }

    /* Mostra os botões "Identificação" / "Variáveis" no header */
    .dte-toolbar__mobile-actions { display: inline-flex; }

    /* Esconde o título canônico no mobile (espaço pros botões) */
    .dte-toolbar__title > span { display: none; }
    .dte-toolbar__title > i { display: none; }

    .dte-preview {
        padding: 12px;
    }
    .dte-preview__doc {
        padding: 24px 18px;
    }
}
</style>

<template>
    <!-- ══ Mobile drawer (form + variáveis em tabs) ════════════ -->
    <Transition name="dte-drawer-fade">
        <div
            v-show="isMobile && drawerOpen"
            class="dte-mobile-drawer"
            :class="{ 'is-open': drawerOpen }"
        >
            <div class="dte-mobile-drawer__tabs">
                <button
                    type="button"
                    class="dte-drawer-tab"
                    :class="{ 'is-active': drawerTab === 'form' }"
                    @click="drawerTab = 'form'"
                >
                    <i class="pi pi-tag" />
                    <span>Identificação</span>
                </button>
                <button
                    type="button"
                    class="dte-drawer-tab"
                    :class="{ 'is-active': drawerTab === 'vars' }"
                    @click="drawerTab = 'vars'"
                >
                    <i class="pi pi-code" />
                    <span>Variáveis</span>
                </button>
                <button
                    type="button"
                    class="dte-drawer-close"
                    v-tooltip.bottom="'Fechar'"
                    @click="fecharDrawer"
                >
                    <i class="pi pi-times" />
                </button>
            </div>
            <div id="dte-mobile-drawer-form" v-show="drawerTab === 'form'" class="dte-mobile-drawer__pane" />
            <div id="dte-mobile-drawer-vars" v-show="drawerTab === 'vars'" class="dte-mobile-drawer__pane" />
        </div>
    </Transition>
    <Transition name="dte-drawer-fade">
        <div
            v-show="isMobile && drawerOpen"
            class="dte-mobile-drawer__backdrop"
            @click="fecharDrawer"
        />
    </Transition>

    <div class="dte-page">
        <!-- ══ Toggle Editor / Preview no topo ══════════════════ -->
        <div class="dte-toolbar">
            <!-- Botões "Identificação" e "Variáveis" — mobile-only -->
            <div class="dte-toolbar__mobile-actions">
                <button
                    type="button"
                    class="dte-mobile-btn"
                    v-tooltip.bottom="'Identificação do template'"
                    @click="openDrawer('form')"
                >
                    <i class="pi pi-tag" />
                    <span>Identificação</span>
                </button>
                <button
                    type="button"
                    class="dte-mobile-btn"
                    v-tooltip.bottom="'Inserir variáveis'"
                    @click="openDrawer('vars')"
                >
                    <i class="pi pi-code" />
                    <span>Variáveis</span>
                </button>
            </div>
            <div class="dte-toolbar__title">
                <i class="pi pi-file-edit" />
                <span>Conteúdo do documento</span>
            </div>
            <div class="dte-toolbar__tabs">
                <Button
                    label="Editor"
                    icon="pi pi-pencil"
                    :severity="activeTab === 'editor' ? undefined : 'secondary'"
                    :outlined="activeTab !== 'editor'"
                    size="small"
                    class="rounded-full"
                    @click="activeTab = 'editor'"
                />
                <Button
                    label="Preview"
                    icon="pi pi-eye"
                    :severity="activeTab === 'preview' ? undefined : 'secondary'"
                    :outlined="activeTab !== 'preview'"
                    size="small"
                    class="rounded-full"
                    @click="activeTab = 'preview'"
                />
            </div>
        </div>

        <!-- ══ EDITOR — 3 colunas (form / editor / variáveis) ══ -->
        <div v-show="activeTab === 'editor'" class="dte-cols">
            <!-- ─── COL 1 (esquerda): Form de metadados — teleporta pro drawer no mobile ─── -->
            <Teleport to="#dte-mobile-drawer-form" :disabled="!isMobile">
            <aside class="dte-side">
                <div class="dte-side__head">
                    <i class="pi pi-tag" />
                    <span>Identificação</span>
                </div>
                <div class="dte-side__body">
                    <div class="dte-field">
                        <label>Nome do template</label>
                        <InputText v-model="form.nome_template" placeholder="Ex: Declaração de comparecimento" class="w-full" />
                    </div>
                    <div class="dte-field">
                        <label>Tipo</label>
                        <Select v-model="form.tipo" :options="TIPOS_TEMPLATE" optionLabel="label" optionValue="value" class="w-full" />
                    </div>
                    <div class="dte-field">
                        <label>Descrição</label>
                        <Textarea v-model="form.descricao" placeholder="Breve descrição do template" class="w-full" rows="3" autoResize />
                    </div>
                    <div class="dte-field">
                        <label>URL do logo (opcional)</label>
                        <InputText v-model="form.logo_url" placeholder="https://..." class="w-full" />
                    </div>
                </div>
            </aside>
            </Teleport>

            <!-- ─── COL 2 (centro): Tabs Cabeçalho/Corpo/Rodapé + editor ─── -->
            <main class="dte-main">
                <div class="dte-main__tabs">
                    <button
                        type="button"
                        class="dte-tab"
                        :class="{ 'is-active': editorTab === 'cabecalho' }"
                        @click="editorTab = 'cabecalho'"
                    >
                        <i class="pi pi-align-left" />
                        <span>Cabeçalho</span>
                    </button>
                    <button
                        type="button"
                        class="dte-tab"
                        :class="{ 'is-active': editorTab === 'corpo' }"
                        @click="editorTab = 'corpo'"
                    >
                        <i class="pi pi-align-justify" />
                        <span>Corpo</span>
                    </button>
                    <button
                        type="button"
                        class="dte-tab"
                        :class="{ 'is-active': editorTab === 'rodape' }"
                        @click="editorTab = 'rodape'"
                    >
                        <i class="pi pi-align-center" />
                        <span>Rodapé</span>
                    </button>
                </div>

                <div class="dte-main__editor">
                    <div v-show="editorTab === 'cabecalho'" class="dte-editor-wrap" @focusin="cursorField = 'cabecalho_html'">
                        <JoditEmailEditor ref="editorCabecalho" v-model="form.cabecalho_html" :minHeight="450" layoutButtons :logoUrl="form.logo_url" />
                    </div>
                    <div v-show="editorTab === 'corpo'" class="dte-editor-wrap" @focusin="cursorField = 'corpo_html'">
                        <JoditEmailEditor ref="editorCorpo" v-model="form.corpo_html" :minHeight="450" />
                    </div>
                    <div v-show="editorTab === 'rodape'" class="dte-editor-wrap" @focusin="cursorField = 'rodape_html'">
                        <JoditEmailEditor ref="editorRodape" v-model="form.rodape_html" :minHeight="450" layoutButtons :logoUrl="form.logo_url" />
                    </div>
                </div>
            </main>

            <!-- ─── COL 3 (direita): Variáveis disponíveis — teleporta pro drawer no mobile ─── -->
            <Teleport to="#dte-mobile-drawer-vars" :disabled="!isMobile">
            <aside class="dte-vars">
                <div class="dte-vars__head">
                    <i class="pi pi-code" />
                    <span>Variáveis</span>
                </div>
                <p class="dte-vars__hint">
                    Clique para inserir no
                    <strong>{{ editorTab === 'cabecalho' ? 'Cabeçalho' : editorTab === 'rodape' ? 'Rodapé' : 'Corpo' }}</strong>.
                </p>
                <div class="dte-vars__list">
                    <div v-for="(vars, grupo) in variablesGrouped" :key="grupo" class="dte-vars__group">
                        <div class="dte-vars__group-title">{{ grupo }}</div>
                        <div class="dte-vars__group-items">
                            <button
                                v-for="v in vars"
                                :key="v.key"
                                class="dte-vars__btn"
                                :title="v.key"
                                @click="insertVariable(v.key)"
                            >
                                <span class="dte-vars__btn-brace">&lbrace;&lbrace;</span>
                                <span class="dte-vars__btn-label">{{ v.label }}</span>
                                <span class="dte-vars__btn-brace">&rbrace;&rbrace;</span>
                            </button>
                        </div>
                    </div>
                </div>
            </aside>
            </Teleport>
        </div>

        <!-- ══ PREVIEW — full width ════════════════════════════ -->
        <div v-show="activeTab === 'preview'" class="dte-preview">
            <div class="dte-preview__doc">
                <div v-if="form.cabecalho_html" class="dte-preview__header" v-html="renderedCabecalho" />
                <div class="dte-preview__body" v-html="renderedPreview" />
                <div v-if="form.rodape_html" class="dte-preview__footer" v-html="renderedRodape" />
            </div>
        </div>
    </div>
</template>
