<template>
    <Head :title="isEdit ? 'Edit Template' : 'Create Email Template'" />
    <AppLayout :no-padding="true">
        <div class="tc-container">

            <!-- ── Top fields strip ── -->
            <div class="tc-fields-strip">
                <!-- Page title & Actions row -->
                <div class="tc-page-hdr">
                    <div class="tc-page-hdr-left">
                        <Link :href="route('templates.index')" class="tc-back-link">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:14px;height:14px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
                            </svg>
                            Back to Templates
                        </Link>
                        <h1 class="tc-page-title">{{ isEdit ? 'Edit Email Template' : 'Create Email Template' }}</h1>
                    </div>
                    <div class="tc-actions-flex">
                        <button class="btn btn-outline btn-icon-mobile" title="Template Gallery" @click="showGalleryModal = true">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" style="width:14px;height:14px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z" />
                            </svg>
                            <span class="btn-text">Template Gallery</span>
                        </button>
                        <button class="btn btn-outline btn-icon-mobile" title="Save" @click="saveAndKeepEditing" :disabled="saving">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" style="width:14px;height:14px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M17.59 2.5H6a2 2 0 0 0-2 2v15a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6.41a2 2 0 0 0-.59-1.42l-2.42-2.42zM12 18a3 3 0 1 1 0-6 3 3 0 0 1 0 6zm3-10H6V4h9v4z" />
                            </svg>
                            <span class="btn-text">Save</span>
                        </button>
                        <button class="btn btn-outline btn-icon-mobile" title="Send Test" @click="openSendTestModal">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" style="width:14px;height:14px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" />
                            </svg>
                            <span class="btn-text">Send Test</span>
                        </button>
                        <button class="btn btn-primary btn-icon-mobile" :title="saving ? 'Saving…' : isEdit ? 'Update Template' : 'Create Template'" @click="saveTemplate" :disabled="saving">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:14px;height:14px">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                            </svg>
                            <span class="btn-text">{{ saving ? 'Saving…' : isEdit ? 'Update Template' : 'Create Template' }}</span>
                        </button>
                    </div>
                </div>

                <!-- Fields grid row -->
                <div class="tc-fields-row">
                    <div class="tc-field-group tc-field-group--title">
                        <label class="tc-label">Template Title <span class="tc-required">*</span></label>
                        <input
                            type="text"
                            class="tc-input"
                            v-model="form.title"
                            placeholder="Enter template title…"
                            :class="{ 'is-invalid': errors.title }"
                        />
                        <span v-if="errors.title" class="tc-error-text">{{ errors.title }}</span>
                    </div>

                    <div class="tc-field-group">
                        <label class="tc-label">Email Subject</label>
                        <div class="tc-subject-wrap">
                            <input
                                type="text"
                                class="tc-input tc-input--subject"
                                v-model="form.email_subject"
                                placeholder="Your email subject…"
                                ref="subjectInputRef"
                            />
                            <button
                                type="button"
                                class="tc-subject-personalize"
                                title="Insert personalization tag"
                                @click="showTagModal = true"
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" style="width:16px;height:16px">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" />
                                </svg>
                            </button>
                        </div>
                    </div>

                    <div class="tc-field-group">
                        <label class="tc-label">Email Pre-Header</label>
                        <input
                            type="text"
                            class="tc-input"
                            v-model="form.email_pre_header"
                            placeholder="Preview text shown in inbox…"
                        />
                    </div>
                </div>
            </div>

            <!-- ── Email Body Editor (using EmailEditor component suite) ── -->
            <div class="tc-editor-area">
                <EmailEditor v-model="form.email_body" :global-settings="globalSettings" />
            </div>

        </div>

        <!-- Personalization Tags Modal -->
        <div v-if="showTagModal" class="modal-overlay is-open" @click.self="showTagModal = false">
            <div class="modal" style="max-width:400px;width:100%">
                <div class="modal-header">
                    <span class="modal-title">Insert Personalization Tag</span>
                    <button type="button" class="modal-close" @click="showTagModal = false">✕</button>
                </div>
                <div class="modal-body" style="padding:16px">
                    <div class="tag-list">
                        <button
                            v-for="t in personalizationTags"
                            :key="t.tag"
                            type="button"
                            class="tag-item"
                            @click="insertTag(t.tag)"
                        >
                            <span class="tag-name">{{ t.name }}</span>
                            <code class="tag-code">{{ t.tag }}</code>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Template Preview Modal -->
        <div v-if="showPreviewModal" class="modal-overlay is-open" @click.self="showPreviewModal = false">
            <div class="modal" style="max-width:800px;width:100%;height:85vh;display:flex;flex-direction:column">
                <div class="modal-header">
                    <div style="display:flex;align-items:center;gap:12px">
                        <span class="modal-title">Template Preview</span>
                        <div class="device-toggle">
                            <button
                                type="button"
                                class="device-btn"
                                :class="{ 'is-active': previewDevice === 'desktop' }"
                                @click="previewDevice = 'desktop'"
                            >
                                Desktop
                            </button>
                            <button
                                type="button"
                                class="device-btn"
                                :class="{ 'is-active': previewDevice === 'mobile' }"
                                @click="previewDevice = 'mobile'"
                            >
                                Mobile
                            </button>
                        </div>
                    </div>
                    <button type="button" class="modal-close" @click="showPreviewModal = false">✕</button>
                </div>
                <div class="modal-body" style="flex:1;padding:20px;background:var(--bg-page);overflow-y:auto;display:flex;justify-content:center">
                    <div
                        class="preview-container"
                        :style="{ width: previewDevice === 'mobile' ? '375px' : '100%', maxWidth: '640px' }"
                    >
                        <div class="preview-inbox-header">
                            <div class="preview-subject"><strong>Subject:</strong> {{ form.email_subject || '(No Subject)' }}</div>
                            <div class="preview-preheader" v-if="form.email_pre_header"><strong>Pre-header:</strong> {{ form.email_pre_header }}</div>
                        </div>
                        <div class="preview-body-content" v-html="renderedBodyHtml"></div>
                    </div>
                </div>
                <div class="modal-footer" style="padding:12px 16px;display:flex;justify-content:flex-end;border-top:1px solid var(--border-color)">
                    <button type="button" class="btn btn-ghost btn-sm" @click="showPreviewModal = false">Close</button>
                </div>
            </div>
        </div>

        <!-- Send Test Email Modal -->
        <div v-if="showSendTestModal" class="modal-overlay is-open" @click.self="closeSendTestModal">
            <div class="modal" style="max-width:420px;width:100%">
                <div class="modal-header">
                    <span class="modal-title">Send a Test Email</span>
                    <button type="button" class="modal-close" @click="closeSendTestModal">✕</button>
                </div>
                <div class="modal-body" style="padding:20px">
                    <p style="font-size:13px;color:#6b7280;margin:0 0 14px">
                        Send this template as a test to any email address to preview how it looks in an inbox.
                    </p>
                    <label style="font-size:12px;font-weight:600;color:var(--text-secondary);display:block;margin-bottom:6px">Recipient email address</label>
                    <input
                        v-model="testEmailAddress"
                        type="email"
                        placeholder="you@example.com"
                        class="tc-input"
                        style="height:38px;font-size:13px;width:100%;box-sizing:border-box"
                        @keydown.enter="doSendTestEmail"
                        ref="testEmailInputRef"
                    />
                    <p v-if="testEmailError" style="font-size:12px;color:var(--danger);margin:6px 0 0">{{ testEmailError }}</p>
                    <p v-if="testEmailSuccess" style="font-size:12px;color:var(--success);margin:6px 0 0">{{ testEmailSuccess }}</p>
                </div>
                <div class="modal-footer" style="display:flex;justify-content:flex-end;gap:8px;padding:12px 16px;border-top:1px solid var(--border-color)">
                    <button type="button" class="btn btn-ghost btn-sm" @click="closeSendTestModal">Cancel</button>
                    <button type="button" class="btn btn-primary btn-sm" @click="doSendTestEmail" :disabled="testEmailSending">
                        <svg v-if="testEmailSending" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13" class="cw-spin" style="margin-right: 4px; display: inline-block; vertical-align: middle;">
                            <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
                        </svg>
                        {{ testEmailSending ? 'Sending…' : 'Send Test' }}
                    </button>
                </div>
            </div>
        </div>

        <!-- Template Gallery Modal -->
        <TemplateGalleryModal
            :open="showGalleryModal"
            :builtin-templates="builtinTemplates"
            :custom-templates="customTemplates"
            @close="showGalleryModal = false"
            @select="onGallerySelect"
        />
    </AppLayout>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import EmailEditor from '@/Components/EmailEditor/EmailEditor.vue';
import CwSelect from '@/Components/CwSelect.vue';
import CwDateTimePicker from '@/Components/CwDateTimePicker.vue';
import TemplateGalleryModal from '@/Components/TemplateGalleryModal.vue';

const props = defineProps({
    template: { type: Object, default: null },
    builtinTemplates: { type: Array, default: () => [] },
    customTemplates: { type: Array, default: () => [] },
    globalSettings: { type: Object, default: () => ({}) }
});

const isEdit = computed(() => !!props.template?.id);

const form = reactive({
    title: props.template?.title || '',
    email_subject: props.template?.email_subject || '',
    email_pre_header: props.template?.email_pre_header || '',
    email_body: Array.isArray(props.template?.email_body) ? props.template.email_body : [],
});

const errors = reactive({
    title: '',
});

const saving = ref(false);
const showTagModal = ref(false);
const showPreviewModal = ref(false);
const showGalleryModal = ref(false);

function onGallerySelect(selectedTpl) {
    if (selectedTpl === 'scratch') {
        form.email_subject = '';
        form.email_pre_header = '';
        form.email_body = [];
    } else if (selectedTpl?.id) {
        if (!form.title) {
            form.title = selectedTpl.title + (selectedTpl.is_custom ? ' (Copy)' : ' (Customized)');
        }
        form.email_subject = selectedTpl.email_subject || '';
        form.email_pre_header = selectedTpl.email_pre_header || '';
        form.email_body = Array.isArray(selectedTpl.email_body) ? JSON.parse(JSON.stringify(selectedTpl.email_body)) : [];
    }
}
const previewDevice = ref('desktop');
const subjectInputRef = ref(null);

const personalizationTags = [
    { name: 'First Name', tag: '{{first_name}}' },
    { name: 'Last Name', tag: '{{last_name}}' },
    { name: 'Email Address', tag: '{{email}}' },
    { name: 'Company Name', tag: '{{company}}' },
    { name: 'Unsubscribe URL', tag: '{{unsubscribe_url}}' },
];

function insertTag(tag) {
    form.email_subject = (form.email_subject || '') + ' ' + tag;
    showTagModal.value = false;
}

function saveTemplate() {
    errors.title = '';
    if (!form.title.trim()) {
        errors.title = 'Template title is required';
        return;
    }

    saving.value = true;

    if (isEdit.value) {
        router.put(route('templates.update', props.template.id), form, {
            onError: (err) => {
                saving.value = false;
                if (err.title) errors.title = err.title;
            },
            onFinish: () => {
                saving.value = false;
            }
        });
    } else {
        router.post(route('templates.store'), form, {
            onError: (err) => {
                saving.value = false;
                if (err.title) errors.title = err.title;
            },
            onFinish: () => {
                saving.value = false;
            }
        });
    }
}

function saveAndKeepEditing() {
    errors.title = '';
    if (!form.title.trim()) {
        errors.title = 'Template title is required';
        return;
    }

    saving.value = true;

    const payload = { ...form, stay: true };

    if (isEdit.value) {
        router.put(route('templates.update', props.template.id), payload, {
            onError: (err) => {
                if (err.title) errors.title = err.title;
            },
            onFinish: () => {
                saving.value = false;
            }
        });
    } else {
        router.post(route('templates.store'), payload, {
            onError: (err) => {
                if (err.title) errors.title = err.title;
            },
            onFinish: () => {
                saving.value = false;
            }
        });
    }
}

const showSendTestModal = ref(false);
const testEmailAddress = ref('');
const testEmailSending = ref(false);
const testEmailError = ref('');
const testEmailSuccess = ref('');
const testEmailInputRef = ref(null);

function openSendTestModal() {
    testEmailError.value = '';
    testEmailSuccess.value = '';
    showSendTestModal.value = true;
    setTimeout(() => testEmailInputRef.value?.focus(), 100);
}

function closeSendTestModal() {
    showSendTestModal.value = false;
    testEmailError.value = '';
    testEmailSuccess.value = '';
}

async function doSendTestEmail() {
    testEmailError.value = '';
    testEmailSuccess.value = '';

    const email = testEmailAddress.value.trim();
    if (!email) {
        testEmailError.value = 'Please enter a recipient email address.';
        return;
    }

    testEmailSending.value = true;
    try {
        await window.axios.post(route('templates.send-test'), {
            email,
            title: form.title,
            email_subject: form.email_subject,
            blocks: form.email_body
        });
        testEmailSuccess.value = `Test email sent to ${email}`;
    } catch (err) {
        testEmailError.value = err.response?.data?.message ?? 'Failed to send test email. Please check your mail settings.';
    } finally {
        testEmailSending.value = false;
    }
}

// Simple HTML compiler for preview
const renderedBodyHtml = computed(() => {
    if (!form.email_body || !form.email_body.length) {
        return '<div style="padding:40px;text-align:center;color:#9ca3af;">Empty Email Body</div>';
    }
    return form.email_body.map(block => {
        const s = block.styles || {};
        const getStyle = () => {
            let style = `padding:${s.paddingTop ?? 16}px ${s.paddingRight ?? 24}px ${s.paddingBottom ?? 16}px ${s.paddingLeft ?? 24}px;`;
            if (s.bgColor) style += `background-color:${s.bgColor};`;
            if (s.borderRadius) style += `border-radius:${s.borderRadius}px;`;
            if (s.borderWidth) style += `border:${s.borderWidth}px solid ${s.borderColor || '#e5e7eb'};`;
            return style;
        };

        if (block.type === 'heading' || block.type === 'header') {
            const align = s.textAlign || block.align || 'left';
            const color = s.color || block.textColor || '#111827';
            const size = s.fontSize || 24;
            const weight = s.fontWeight || 700;
            const content = block.content || block.title || '';
            return `<div style="${getStyle()}"><h2 style="margin:0;text-align:${align};color:${color};font-size:${size}px;font-weight:${weight};">${content}</h2></div>`;
        }
        if (block.type === 'text') {
            const align = s.textAlign || block.align || 'left';
            const color = s.color || block.textColor || '#374151';
            const size = s.fontSize || 14;
            const lh = s.lineHeight || 1.6;
            const content = (block.content || block.html || '').replace(/\n/g, '<br>');
            return `<div style="${getStyle()}"><p style="margin:0;text-align:${align};color:${color};font-size:${size}px;line-height:${lh};">${content}</p></div>`;
        }
        if (block.type === 'button') {
            const text = block.text || 'Click here';
            const href = block.href || block.url || '#';
            const bg = s.backgroundColor || block.btnColor || '#4285f4';
            const color = s.textColor || block.textColor || '#ffffff';
            const radius = s.borderRadius ?? 6;
            const size = s.fontSize ?? 14;
            const align = s.blockAlign || s.textAlign || block.align || 'center';
            return `<div style="${getStyle()}text-align:${align}"><a href="${href}" target="_blank" style="display:inline-block;background:${bg};color:${color};border-radius:${radius}px;font-size:${size}px;font-weight:600;padding:10px 24px;text-decoration:none;">${text}</a></div>`;
        }
        if (block.type === 'image') {
            const src = block.src || block.url || '';
            const alt = block.alt || '';
            const align = s.blockAlign || s.textAlign || block.align || 'center';
            const width = s.width ?? 100;
            const widthVal = width === 'auto' ? 'auto' : `${width}%`;
            if (!src) return '';
            return `<div style="${getStyle()}text-align:${align}"><img src="${src}" alt="${alt}" style="max-width:100%;width:${widthVal};display:inline-block;vertical-align:top;" /></div>`;
        }
        if (block.type === 'divider') {
            const color = s.borderColor || block.lineColor || '#e5e7eb';
            const thickness = s.dividerThickness ?? s.borderWidth ?? 1;
            const align = s.blockAlign || s.textAlign || 'center';
            const width = s.width ?? 100;
            const margin = align === 'center' ? '0 auto' : (align === 'right' ? '0 0 0 auto' : '0 auto 0 0');
            return `<div style="${getStyle()}"><hr style="border:none;border-top:${thickness}px solid ${color};width:${width}%;margin:${margin};" /></div>`;
        }
        if (block.type === 'spacer') {
            const height = s.height ?? 24;
            return `<div style="height:${height}px;"></div>`;
        }
        if (block.type === 'logo') {
            const align = s.blockAlign || s.textAlign || 'center';
            const brandText = block.brandText || 'BrandName';
            const src = block.src || '';
            const logoType = block.logoType || 'image';
            let innerHtml = '';
            if (logoType === 'text') {
                const ff = s.fontFamily || 'sans-serif';
                const fw = s.fontWeight || 'bold';
                const fs = s.fontSize || 24;
                const color = s.color || '#333333';
                innerHtml = `<span style="font-family:${ff};font-weight:${fw};font-size:${fs}px;color:${color};line-height:1;">${brandText}</span>`;
            } else {
                const width = s.width ?? 50;
                if (src) {
                    innerHtml = `<img src="${src}" alt="Logo" style="max-width:100%;width:${width}%;display:inline-block;" />`;
                }
            }
            return `<div style="${getStyle()}text-align:${align}">${innerHtml}</div>`;
        }
        if (block.type === 'footer') {
            const align = s.textAlign || 'center';
            const color = s.color || '#9ca3af';
            const size = s.fontSize || 11;
            const lh = s.lineHeight || 1.8;
            const content = block.content || "You're receiving this email because you subscribed to our newsletter.";
            const copyright = block.copyright || "© 2026 Your Company · All rights reserved";
            return `<div style="${getStyle()}text-align:${align};line-height:${lh};font-size:${size}px;color:${color};">
                <p style="margin:0 0 4px 0;">${content}</p>
                <p style="margin:0 0 4px 0;"><a href="#" style="color:#4285f4;text-decoration:none;">Unsubscribe</a> · <a href="#" style="color:#4285f4;text-decoration:none;">Privacy Policy</a></p>
                <p style="margin:0;">${copyright}</p>
            </div>`;
        }
        if (block.type === 'column') {
            const cols = block.columns || [];
            const colWidths = block.colWidths || [];
            const tds = cols.map((col, idx) => {
                const pct = colWidths[idx] || (100 / cols.length);
                const colContent = (col.blocks || []).map(b => {
                    return `<div style="font-size:11px;color:#6b7280;">Nested Block: ${b.type}</div>`;
                }).join('');
                return `<td style="width:${pct}%;vertical-align:top;padding:0 6px;">${colContent}</td>`;
            }).join('');
            return `<div style="${getStyle()}"><table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;table-layout:fixed;"><tr>${tds}</tr></table></div>`;
        }
        return `<div style="padding:16px">${block.html || ''}</div>`;
    }).join('');
});
</script>

<style scoped>
.tc-container {
    display: flex;
    flex-direction: column;
    height: calc(100vh - var(--topbar-height, 58px));
    overflow: hidden;
    background: var(--bg-page);
}

.tc-fields-strip {
    background: var(--bg-surface);
    border-bottom: 1px solid var(--border-color);
    padding: 16px 24px;
    flex-shrink: 0;
}

.tc-page-hdr {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 14px;
}

.tc-page-hdr-left {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.tc-back-link {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: var(--text-secondary);
    text-decoration: none;
}
.tc-back-link:hover {
    color: var(--primary);
}

.tc-page-title {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0;
}

.tc-actions-flex {
    display: flex;
    align-items: center;
    gap: 10px;
}

.tc-fields-row {
    display: grid;
    grid-template-columns: 1.2fr 1fr 1fr;
    gap: 16px;
    align-items: start;
}

.tc-field-group {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.tc-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
}

.tc-required {
    color: var(--danger);
}

.tc-input {
    height: 38px;
    padding: 0 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 13px;
    color: var(--text-primary);
    background: var(--bg-surface);
    outline: none;
    transition: border-color .15s ease;
}

.tc-input:focus {
    border-color: var(--primary);
}

.tc-input.is-invalid {
    border-color: var(--danger);
}

.tc-error-text {
    font-size: 11px;
    color: var(--danger);
}

.tc-subject-wrap {
    position: relative;
    display: flex;
    align-items: center;
}

.tc-input--subject {
    width: 100%;
    padding-right: 36px;
}

.tc-subject-personalize {
    position: absolute;
    right: 8px;
    background: none;
    border: none;
    color: var(--text-muted);
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.tc-subject-personalize:hover {
    color: var(--primary);
    background: var(--bg-hover);
}

.tc-editor-area {
    flex: 1;
    min-height: 0;
    position: relative;
    overflow: hidden;
}

/* Personalization tag modal styling */
.tag-list {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.tag-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 12px;
    border-radius: 6px;
    border: 1px solid var(--border-color);
    background: var(--bg-surface);
    cursor: pointer;
    transition: background .15s ease;
}

.tag-item:hover {
    background: var(--bg-hover);
    border-color: var(--primary);
}

.tag-name {
    font-size: 13px;
    color: var(--text-primary);
    font-weight: 500;
}

.tag-code {
    font-size: 12px;
    background: var(--bg-hover-strong);
    padding: 2px 6px;
    border-radius: 4px;
    color: var(--primary);
}

/* Preview Modal */
.device-toggle {
    display: flex;
    background: var(--bg-hover-strong);
    padding: 2px;
    border-radius: 6px;
}
.device-btn {
    border: none;
    background: none;
    padding: 4px 10px;
    font-size: 12px;
    font-weight: 500;
    color: var(--text-secondary);
    border-radius: 4px;
    cursor: pointer;
}
.device-btn.is-active {
    background: var(--bg-surface);
    color: var(--text-primary);
    box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.preview-container {
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    overflow: hidden;
    transition: width .2s ease;
}

.preview-inbox-header {
    padding: 12px 16px;
    background: #f8fafc;
    border-bottom: 1px solid #e2e8f0;
    font-size: 12px;
    color: #475569;
}

.preview-body-content {
    background: #ffffff;
    color: #1e293b;
    min-height: 300px;
}

/* Responsive viewports */
@media (max-width: 900px) {
    .tc-page-hdr {
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
        flex-wrap: wrap;
    }
    .tc-page-hdr-left {
        flex: 1;
        min-width: 140px;
    }
    .tc-actions-flex {
        width: auto;
        display: flex;
        align-items: center;
        gap: 6px;
        flex-wrap: nowrap;
    }
    .tc-actions-flex .btn {
        flex: 0 0 auto !important;
        min-width: 36px !important;
        width: 36px !important;
        height: 36px !important;
        padding: 0 !important;
        justify-content: center !important;
        align-items: center !important;
        border-radius: 8px;
    }
    .tc-actions-flex .btn .btn-text {
        display: none !important;
    }
    .tc-actions-flex .btn svg {
        margin: 0 !important;
        width: 16px !important;
        height: 16px !important;
    }
    .tc-fields-row {
        grid-template-columns: 1fr;
    }
    .tc-container {
        height: auto;
        overflow: visible;
    }
}
</style>
