<template>
    <Head title="Email Templates" />
    <AppLayout>
        <!-- Page header -->
        <div class="page-header">
            <div class="page-header__left">
                <h1>Email Templates</h1>
                <p>Create, customize, and manage your reusable email templates.</p>
            </div>
            <div class="page-header__actions">
                <button @click="showImportModal = true" class="btn btn-outline" style="display:inline-flex;align-items:center;gap:6px;">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
                    </svg>
                    Import
                </button>
                <button @click="showGalleryModal = true" class="btn btn-outline" style="display:inline-flex;align-items:center;gap:6px;">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="14" height="14">
                        <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>
                    Template Gallery
                </button>
                <Link :href="route('templates.create')" class="btn btn-primary" style="display:inline-flex;align-items:center;gap:6px;">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                    </svg>
                    Create New Template
                </Link>
            </div>
        </div>

        <!-- Template list -->
        <div class="table-wrap">
            <div class="table-toolbar" :class="{ 'has-selection': selected.length > 0 }">
                <div v-if="selected.length === 0" class="table-toolbar-left">
                    <div class="table-search">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
                        </svg>
                        <input
                            type="search"
                            v-model="search"
                            placeholder="Search templates…"
                            @input="onSearchInput"
                            @keydown.enter="doSearch"
                        />
                    </div>
                    <CwSelect
                        v-model="tabFilter"
                        :options="tabOptions"
                        @change="onTabChange"
                        style="width: 170px;"
                    />
                </div>
                <div v-else class="table-toolbar-left">
                    <div class="selection-status">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" width="16" height="16" style="color: var(--active-text);"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                        <span class="selection-count">{{ selected.length }} template{{ selected.length === 1 ? '' : 's' }} selected</span>
                    </div>
                </div>
                <div class="table-toolbar-right">
                    <template v-if="selected.length > 0">
                        <button class="btn btn-outline" style="color: var(--danger); border-color: var(--danger-border);" @click="confirmBulkDelete">Delete</button>
                        <button class="btn btn-outline" @click="selected = []">Cancel</button>
                    </template>
                    <template v-else>
                        <span class="cw-pagination-info">
                            {{ templates.from ?? 0 }}–{{ templates.to ?? 0 }} of {{ templates.total }}
                        </span>
                        <button class="cw-pg-btn" :disabled="!templates.prev_page_url" @click="goPage(templates.current_page - 1)">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5"/></svg>
                        </button>
                        <button class="cw-pg-btn" :disabled="!templates.next_page_url" @click="goPage(templates.current_page + 1)">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14"><path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5"/></svg>
                        </button>
                    </template>
                </div>
            </div>

            <div class="table-scroll">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th style="width:40px">
                                <input type="checkbox" class="table-checkbox" :checked="allSelected" @change="toggleAll" />
                            </th>
                            <th>
                                <button @click="sortTable('title')" class="tm-sort-btn">
                                    Title
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" style="width:10px;height:10px">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 15L12 18.75 15.75 15m-7.5-6L12 5.25 15.75 9" />
                                    </svg>
                                </button>
                            </th>
                            <th style="width:200px">
                                <button @click="sortTable('created_at')" class="tm-sort-btn">
                                    Created At
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" style="width:10px;height:10px">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 15L12 18.75 15.75 15m-7.5-6L12 5.25 15.75 9" />
                                    </svg>
                                </button>
                            </th>
                            <th style="width:120px;text-align:right">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="templates.data.length === 0">
                            <td colspan="4" style="text-align:center;padding:48px 24px;color:#9ca3af">
                                No templates yet. <button class="link-btn" @click="showGalleryModal = true">Select from gallery</button> or <Link :href="route('templates.create')" class="link-btn">Create one.</Link>
                            </td>
                        </tr>
                        <tr v-for="t in templates.data" :key="t.id" :class="{ 'is-selected': selected.includes(t.id) }">
                            <td class="cell-checkbox">
                                <input type="checkbox" class="table-checkbox" :value="t.id" v-model="selected" />
                            </td>
                            <td data-label="Title" class="cell-title">
                                <div class="automation-title-container">
                                    <Link :href="route('templates.edit', t.id)" class="automation-title-link">
                                        {{ t.title }}
                                    </Link>
                                </div>
                                <div v-if="t.email_subject" class="automation-title-sub">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" style="width:12px;height:12px;margin-right:4px;display:inline-block;vertical-align:middle;"><path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"/></svg>
                                    Subject: {{ t.email_subject }}
                                </div>
                            </td>
                            <td data-label="Created At" style="font-size:13px;color:var(--text-secondary)">
                                {{ formatDate(t.created_at) }}
                            </td>
                            <td class="cell-actions">
                                <div style="display:flex;gap:6px;justify-content:flex-end">
                                    <!-- Edit -->
                                    <Link :href="route('templates.edit', t.id)" class="re-action-btn" title="Edit Template">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#2563eb" style="width:18px;height:18px"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z"/></svg>
                                    </Link>
                                    <!-- Duplicate -->
                                    <button @click="duplicateTemplate(t)" class="re-action-btn" title="Duplicate Template">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#0f766e" style="width:18px;height:18px">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 01-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 011.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 00-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 01-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 00-3.375-3.375h-1.5a1.125 1.125 0 01-1.125-1.125v-1.5a3.375 3.375 0 00-3.375-3.375H9.75"/>
                                        </svg>
                                    </button>
                                    <!-- Delete -->
                                    <button class="re-action-btn" title="Delete Template" @click="deleteTemplate(t)">
<svg data-v-36f8d284="" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#ef4444" style="width: 18px; height: 18px;"><path data-v-36f8d284="" stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"></path></svg>                                    </button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <TemplateGalleryModal
            :open="showGalleryModal"
            :builtin-templates="builtinTemplates"
            :custom-templates="customTemplates"
            @close="showGalleryModal = false"
            @select="onGallerySelect"
        />

        <!-- Import Modal -->
        <div v-if="showImportModal" class="modal-overlay is-open" @click.self="showImportModal = false">
            <div class="modal" style="max-width:440px;width:100%">
                <div class="modal-header">
                    <span class="modal-title">Import Template</span>
                    <button type="button" class="modal-close" @click="showImportModal = false">✕</button>
                </div>
                <form @submit.prevent="doImport">
                    <div class="modal-body" style="padding:20px">
                        <p style="font-size:13px;color:var(--text-secondary);margin:0 0 14px">
                            Upload a template JSON file exported from CRMfic Email Editor.
                        </p>
                        <input
                            type="file"
                            accept=".json,.txt"
                            @change="onFileSelected"
                            class="cw-field-input"
                            style="font-size:13px;width:100%;box-sizing:border-box"
                        />
                        <p v-if="importError" style="font-size:12px;color:var(--danger);margin:6px 0 0">{{ importError }}</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="showImportModal = false">Cancel</button>
                        <button type="submit" class="btn btn-primary btn-sm" :disabled="!importFile || importing">
                            {{ importing ? 'Importing…' : 'Import Template' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <ConfirmModal
            v-if="showConfirmModal"
            :title="confirmModalTitle"
            :message="confirmModalMessage"
            :confirmText="confirmModalLabel"
            :isDestructive="confirmModalIsDanger"
            @resolve="val => val ? onModalConfirm() : showConfirmModal = false"
        />
    </AppLayout>
</template>

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

const props = defineProps({
    templates: { type: Object, required: true },
    builtinTemplates: { type: Array, default: () => [] },
    customTemplates: { type: Array, default: () => [] },
    filters: { type: Object, required: true },
    counts: { type: Object, required: true },
});

const collapsed = ref(false);
const search = ref(props.filters.search || '');
const perPage = ref(props.filters.per_page || 20);
const selected = ref([]);
const showGalleryModal = ref(false);

function onGallerySelect(template) {
    if (template === 'scratch') {
        router.visit(route('templates.create'));
    } else if (template?.id) {
        router.visit(route('templates.create', { from_template: template.id }));
    }
}
const activeCategory = ref('all');
const selectedGalleryTemplate = ref(null);

const tabFilter = ref(props.filters.tab || 'my');
const tabOptions = [
    { value: 'my', label: 'My Templates' },
    { value: 'builtin', label: 'Built-in Templates' }
];

function onTabChange() {
    switchTab(tabFilter.value);
}

watch(() => props.filters.tab, (val) => {
    tabFilter.value = val || 'my';
});

const categories = [
    { id: 'all', label: 'All Templates', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><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>` },
    { id: 'onboarding', label: 'Onboarding & Welcome', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"/></svg>` },
    { id: 'sales', label: 'Sales & Promotions', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 10.5V6a3.75 3.75 0 10-7.5 0v4.5m11.356-1.993l1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 01-1.12-1.243l1.264-12A1.125 1.125 0 015.513 7.5h12.974c.576 0 1.059.435 1.119 1.007z"/></svg>` },
    { id: 'newsletter', label: 'Newsletters & Updates', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M12 7.5h1.5m-1.5 3h1.5m-7.5 3h7.5m-7.5 3h7.5m3-9h3.75m-3.75 3h3.75m-3.75 3h3.75m-3.75 3h3.75M3 21h18M3 3h18v18H3V3z"/></svg>` },
    { id: 'feedback', label: 'Feedback & Security', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 01.865-.501 48.172 48.172 0 003.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"/></svg>` },
    { id: 'events', label: 'Events & Resources', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"/></svg>` },
];

const perPageOptions = [
    { value: 20, label: '20/page' },
    { value: 50, label: '50/page' },
    { value: 100, label: '100/page' },
];

const filteredBuiltinTemplates = computed(() => {
    if (activeCategory.value === 'all') return props.builtinTemplates;
    return props.builtinTemplates.filter(t => {
        const cat = getIconMeta(t).category;
        return cat === activeCategory.value;
    });
});

function getCategoryCount(catId) {
    if (catId === 'all') return props.builtinTemplates.length;
    return props.builtinTemplates.filter(t => getIconMeta(t).category === catId).length;
}

function getIconMeta(tpl) {
    const title = (tpl.title || '').toLowerCase();
    if (title.includes('welcome') || title.includes('onboarding') || title.includes('trial') || title.includes('getting started')) {
        return {
            category: 'onboarding',
            categoryLabel: 'Onboarding & Welcome',
            bg: '#e8f0fe',
            color: '#1a73e8',
            icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"/></svg>`
        };
    }
    if (title.includes('sale') || title.includes('offer') || title.includes('cart') || title.includes('friday') || title.includes('receipt') || title.includes('order') || title.includes('subscription') || title.includes('renewal') || title.includes('vip') || title.includes('loyalty')) {
        return {
            category: 'sales',
            categoryLabel: 'Sales & Promotions',
            bg: '#fce8e6',
            color: '#ea4335',
            icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 10.5V6a3.75 3.75 0 10-7.5 0v4.5m11.356-1.993l1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 01-1.12-1.243l1.264-12A1.125 1.125 0 015.513 7.5h12.974c.576 0 1.059.435 1.119 1.007z"/></svg>`
        };
    }
    if (title.includes('digest') || title.includes('newsletter') || title.includes('updates') || title.includes('feature') || title.includes('launch') || title.includes('story') || title.includes('case study')) {
        return {
            category: 'newsletter',
            categoryLabel: 'Newsletters & Updates',
            bg: '#e6f4ea',
            color: '#34a853',
            icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M12 7.5h1.5m-1.5 3h1.5m-7.5 3h7.5m-7.5 3h7.5m3-9h3.75m-3.75 3h3.75m-3.75 3h3.75m-3.75 3h3.75M3 21h18M3 3h18v18H3V3z"/></svg>`
        };
    }
    if (title.includes('feedback') || title.includes('miss you') || title.includes('survey') || title.includes('nps') || title.includes('security') || title.includes('password')) {
        return {
            category: 'feedback',
            categoryLabel: 'Feedback & Security',
            bg: '#fef7e0',
            color: '#f9ab00',
            icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 01.865-.501 48.172 48.172 0 003.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"/></svg>`
        };
    }
    return {
        category: 'events',
        categoryLabel: 'Events & Resources',
        bg: '#f3e8ff',
        color: '#9333ea',
        icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"/></svg>`
    };
}

function useGalleryTemplate() {
    if (selectedGalleryTemplate.value === 'scratch') {
        router.visit(route('templates.create'));
    } else if (selectedGalleryTemplate.value?.id) {
        router.visit(route('templates.create', { from_template: selectedGalleryTemplate.value.id }));
    }
}

function renderBlocksHtml(blocks) {
    if (!blocks || !Array.isArray(blocks) || !blocks.length) {
        return '<div style="padding:40px;text-align:center;color:#9ca3af;">Empty template blocks</div>';
    }
    return blocks.map(block => {
        if (block.type === 'header') {
            return `<div style="padding:16px;text-align:${block.align || 'center'};background:${block.bgColor || '#ffffff'}"><h2 style="color:${block.textColor || '#111827'};margin:0;font-size:20px">${block.title || ''}</h2></div>`;
        }
        if (block.type === 'text') {
            return `<div style="padding:12px 16px;color:${block.textColor || '#374151'};line-height:1.5;font-size:13px">${block.content || block.html || ''}</div>`;
        }
        if (block.type === 'button') {
            return `<div style="padding:16px;text-align:${block.align || 'center'}"><span style="display:inline-block;padding:10px 20px;background:${block.btnColor || '#4285f4'};color:${block.textColor || '#ffffff'};border-radius:6px;font-weight:600;font-size:13px">${block.text || 'Button'}</span></div>`;
        }
        if (block.type === 'divider') {
            return `<hr style="border:none;border-top:1px solid ${block.lineColor || '#e5e7eb'};margin:16px 0"/>`;
        }
        return `<div style="padding:12px">${block.html || ''}</div>`;
    }).join('');
}

const allSelected = computed(() => {
    return props.templates.data.length > 0 && selected.value.length === props.templates.data.length;
});

function toggleAll(e) {
    if (e.target.checked) {
        selected.value = props.templates.data.map(t => t.id);
    } else {
        selected.value = [];
    }
}

let searchTimer = null;
function onSearchInput() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        doSearch();
    }, 400);
}

function doSearch() {
    router.get(route('templates.index'), {
        tab: props.filters.tab,
        search: search.value,
        per_page: perPage.value,
    }, { preserveState: true, replace: true });
}

function switchTab(tabName) {
    router.get(route('templates.index'), {
        tab: tabName,
        search: search.value,
        per_page: perPage.value,
    }, { preserveState: true });
}

function changePerPage(val) {
    perPage.value = val;
    doSearch();
}

function sortTable(field) {
    const currentSort = props.filters.sort || 'id';
    const currentDir = props.filters.direction || 'desc';
    const nextDir = currentSort === field && currentDir === 'asc' ? 'desc' : 'asc';
    router.get(route('templates.index'), {
        tab: props.filters.tab,
        search: search.value,
        per_page: perPage.value,
        sort: field,
        direction: nextDir,
    }, { preserveState: true });
}

function goPage(p) {
    if (p < 1 || p > props.templates.last_page) return;
    router.get(route('templates.index'), {
        tab: props.filters.tab,
        search: search.value,
        per_page: perPage.value,
        page: p,
    }, { preserveState: true });
}

function duplicateTemplate(template) {
    router.post(route('templates.duplicate', template.id), {}, {
        preserveScroll: true,
    });
}

function deleteTemplate(template) {
    openConfirm({
        title: 'Delete Template',
        message: `Are you sure you want to delete "${template.title}"?`,
        confirmLabel: 'Delete',
        isDanger: true,
        onConfirm: () => {
            router.delete(route('templates.destroy', template.id), {
                preserveScroll: true,
            });
        }
    });
}

function confirmBulkDelete() {
    openConfirm({
        title: 'Delete Selected Templates',
        message: `Are you sure you want to delete ${selected.value.length} selected template(s)?`,
        confirmLabel: 'Delete All',
        isDanger: true,
        onConfirm: () => {
            router.post(route('templates.bulk-destroy'), { ids: selected.value }, {
                onSuccess: () => { selected.value = []; }
            });
        }
    });
}

// Confirmation modal logic
const showConfirmModal = ref(false);
const confirmModalTitle = ref('');
const confirmModalMessage = ref('');
const confirmModalLabel = ref('');
const confirmModalIsDanger = ref(true);
let activeConfirmCallback = null;

function openConfirm({ title, message, confirmLabel, isDanger, onConfirm }) {
    confirmModalTitle.value = title;
    confirmModalMessage.value = message;
    confirmModalLabel.value = confirmLabel;
    confirmModalIsDanger.value = isDanger;
    activeConfirmCallback = onConfirm;
    showConfirmModal.value = true;
}

function onModalConfirm() {
    showConfirmModal.value = false;
    if (activeConfirmCallback) activeConfirmCallback();
}

// Import Modal logic
const showImportModal = ref(false);
const importFile = ref(null);
const importError = ref('');
const importing = ref(false);

function onFileSelected(e) {
    importFile.value = e.target.files[0] || null;
    importError.value = '';
}

function doImport() {
    if (!importFile.value) return;
    importing.value = true;
    const formData = new FormData();
    formData.append('file', importFile.value);

    router.post(route('templates.import'), formData, {
        onError: (err) => {
            importing.value = false;
            importError.value = err.file || 'Import failed.';
        },
        onSuccess: () => {
            importing.value = false;
            showImportModal.value = false;
            importFile.value = null;
        }
    });
}

function formatDate(isoStr) {
    if (!isoStr) return '-';
    const d = new Date(isoStr);
    return d.toLocaleString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}
</script>

<style scoped>
.link-btn { background: none; border: none; color: #4285f4; cursor: pointer; font-size: inherit; padding: 0; }

/* ── Wrapper ── */
.table-wrap {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    overflow: visible;
}

/* ── Toolbar ── */
.table-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    border-bottom: 1px solid var(--border-color);
    gap: 10px;
}
.table-toolbar-left { display: flex; align-items: center; gap: 8px; }
.table-toolbar-right { display: flex; align-items: center; gap: 6px; }

.table-search {
    display: flex;
    align-items: center;
    gap: 8px;
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 0 12px;
    height: 36px;
    width: 260px;
    transition: border-color 0.15s, box-shadow 0.15s;
}
.table-search:focus-within {
    border-color: #4285f4;
    box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.12);
}
.table-search svg { color: var(--text-muted); flex-shrink: 0; }
.table-search input {
    border: none;
    background: transparent;
    outline: none;
    font-size: 13px;
    color: var(--text-primary);
    width: 100%;
    height: 100%;
}
.table-search input::placeholder { color: var(--text-muted); }
.table-search input::-webkit-search-cancel-button { -webkit-appearance: none; }

.table-filter-select {
    font-size: 13px;
    color: var(--text-primary);
    border: 1px solid var(--border-color);
    background: var(--bg-surface);
    border-radius: 8px;
    padding: 0 10px;
    height: 36px;
    cursor: pointer;
    outline: none;
}
.table-filter-select:focus {
    border-color: #4285f4;
    box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.12);
}

@media (max-width: 640px) {
    .table-toolbar {
        flex-direction: column;
        align-items: stretch;
        padding: 10px 12px;
        gap: 10px;
    }
    .table-toolbar-left {
        flex-wrap: wrap;
        width: 100%;
        gap: 8px;
    }
    .table-search {
        width: 100%;
        flex: 1;
        min-width: 0;
    }
    .table-filter-select {
        flex-shrink: 0;
        max-width: 130px;
    }
    .table-toolbar-right {
        width: 100%;
        justify-content: space-between;
    }
}

/* ── Bulk actions ── */
.re-selected-count {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
    white-space: nowrap;
    padding: 0 4px;
}
.cw-pagination-info { font-size: 12px; color: var(--text-secondary); }
.cw-pg-btn {
    width: 28px; height: 28px;
    display: flex; align-items: center; justify-content: center;
    border: 1px solid var(--border-color);
    background: var(--bg-surface);
    border-radius: 6px;
    cursor: pointer;
    color: var(--text-primary);
}
.cw-pg-btn:disabled { opacity: 0.4; cursor: not-allowed; }

/* Table styling */
.table-scroll {
    overflow-x: auto;
}
.tm-sort-btn {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    background: none;
    border: none;
    cursor: pointer;
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
    padding: 0;
}
.automation-title-container { display: flex; flex-direction: column; gap: 3px; }
.automation-title-link {
    font-size: 14px;
    font-weight: 600;
    color: var(--text-primary);
    text-decoration: none;
    line-height: 1.3;
}
.automation-title-link:hover {
    color: var(--primary);
    text-decoration: underline;
}
.automation-title-sub {
    font-size: 12px;
    color: var(--text-muted);
    display: flex;
    align-items: center;
    gap: 4px;
    margin-top: 2px;
}

/* ── Actions ── */
.cell-actions { display: flex; align-items: center; justify-content: flex-end; gap: 4px; }
.re-action-btn {
    width: 30px; height: 30px;
    display: flex; align-items: center; justify-content: center;
    border: 1px solid transparent;
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    color: var(--text-secondary);
    text-decoration: none;
    transition: background 0.1s, border-color 0.1s, color 0.1s;
}
.re-action-btn:hover { background: var(--bg-hover); border-color: var(--border-color); color: var(--text-primary); }
/* .re-action-btn:hover svg { stroke: currentColor; } */

/* ── aft-modal design matching Automation/Index.vue ── */
.aft-modal {
    width: 90vw;
    max-width: 1040px;
    height: 82vh;
    max-height: 720px;
    background: var(--bg-surface);
    border-radius: 16px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
    border: 1px solid var(--border-color);
}
.aft-modal__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px 16px;
    border-bottom: 1px solid var(--border-color);
}
.aft-modal__title {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0 0 2px;
}
.aft-modal__sub {
    font-size: 12.5px;
    color: var(--text-secondary);
    margin: 0;
}
.aft-modal__body {
    display: flex;
    flex: 1;
    min-height: 0;
    overflow: hidden;
}

/* Left sidebar */
.aft-sidebar {
    width: 320px;
    border-right: 1px solid var(--border-color);
    display: flex;
    flex-direction: column;
    background: var(--bg-page);
    flex-shrink: 0;
}
.aft-categories {
    display: flex;
    flex-direction: column;
    gap: 2px;
    padding: 10px;
    border-bottom: 1px solid var(--border-color);
    background: var(--bg-surface);
}
.aft-cat-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 7px 10px;
    border: none;
    background: none;
    border-radius: 7px;
    font-size: 12.5px;
    font-weight: 500;
    color: var(--text-secondary);
    cursor: pointer;
    text-align: left;
    transition: background 0.12s, color 0.12s;
    width: 100%;
}
.aft-cat-btn:hover {
    background: var(--bg-hover);
    color: var(--text-primary);
}
.aft-cat-btn.is-active {
    background: var(--active-bg);
    color: var(--active-text);
    font-weight: 600;
}
.aft-cat-icon {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    opacity: 0.75;
}
.aft-cat-count {
    margin-left: auto;
    font-size: 11px;
    background: var(--bg-hover-strong);
    color: var(--text-muted);
    border-radius: 10px;
    padding: 1px 7px;
    font-weight: 500;
}
.aft-cat-btn.is-active .aft-cat-count {
    background: var(--active-bg);
    color: var(--active-text);
}

/* Template list */
.aft-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.aft-list::-webkit-scrollbar { width: 4px; }
.aft-list::-webkit-scrollbar-track { background: transparent; }
.aft-list::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 2px; }

.aft-card {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 12px;
    border-radius: 9px;
    border: 1.5px solid transparent;
    cursor: pointer;
    transition: background 0.12s, border-color 0.12s, box-shadow 0.12s;
    position: relative;
    background: none;
    text-align: left;
}
.aft-card:hover {
    background: var(--bg-hover);
    border-color: var(--border-color);
}
.aft-card.is-active {
    background: var(--active-bg);
    border-color: var(--active-text, #C5D9FD);
}
.aft-card--scratch {
    border-style: dashed;
    border-color: var(--border-color);
    background: none;
}
.aft-card--scratch:hover {
    background: var(--bg-hover);
    border-color: var(--active-text);
}
.aft-card--scratch.is-active {
    border-color: var(--active-text);
    background: var(--active-bg);
}
.aft-card__icon {
    width: 38px;
    height: 38px;
    border-radius: 9px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    background: var(--bg-hover);
    color: var(--text-secondary);
}
.aft-card__icon--scratch {
    background: linear-gradient(135deg, #4285F4 0%, #b3c7e6 100%);
    color: #fff;
}
.aft-card__body {
    flex: 1;
    min-width: 0;
}
.aft-card__name {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 1px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.aft-card__desc {
    font-size: 11.5px;
    color: var(--text-muted);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.aft-card__badge {
    position: absolute;
    right: 10px;
    top: 8px;
    font-size: 10px;
    font-weight: 600;
    color: var(--active-text);
    background: var(--active-bg);
    border-radius: 6px;
    padding: 1px 6px;
    letter-spacing: 0.02em;
}

/* Right preview */
.aft-preview {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    overflow: hidden;
    background: var(--bg-surface);
}
.aft-preview__scroll {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    display: flex;
    flex-direction: column;
}
.aft-preview__empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;
    text-align: center;
    gap: 10px;
    padding: 40px 20px;
    color: var(--text-muted);
}
.aft-preview__empty-icon, .aft-preview__scratch-icon {
    width: 64px;
    height: 64px;
    border-radius: 16px;
    background: var(--bg-hover-strong);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text-muted);
    margin-bottom: 4px;
}
.aft-preview__header {
    display: flex;
    align-items: center;
    gap: 14px;
    margin-bottom: 14px;
}
.aft-preview__tpl-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}
.aft-preview__tpl-name {
    font-size: 16px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0 0 4px;
}
.aft-preview__tpl-cat {
    font-size: 11px;
    font-weight: 600;
    color: var(--active-text);
    background: var(--active-bg);
    padding: 2px 8px;
    border-radius: 6px;
}
.aft-preview__meta {
    display: flex;
    flex-direction: column;
    gap: 4px;
    margin-bottom: 16px;
    padding: 10px 14px;
    background: var(--bg-hover);
    border-radius: 8px;
    font-size: 12px;
    color: var(--text-secondary);
}
.gallery-preview-frame {
    border: 1px solid var(--border-color);
    border-radius: 8px;
    overflow: hidden;
    background: #ffffff;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.gallery-rendered-body {
    background: #ffffff;
    color: #111827;
    min-height: 240px;
}
.aft-preview__footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 12px;
    padding: 14px 24px;
    border-top: 1px solid var(--border-color);
    background: var(--bg-surface);
    flex-shrink: 0;
}
.aft-preview__footer-meta {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: var(--text-muted);
    margin-right: auto;
}
.aft-import-btn {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13.5px;
    padding: 9px 20px;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .aft-modal {
        width: 95vw;
        height: auto;
        max-height: 90vh;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    .aft-modal__body {
        flex-direction: column;
        overflow: visible;
        height: auto;
        flex: none;
    }
    .aft-sidebar {
        width: 100%;
        max-height: none;
        flex-shrink: 0;
    }
    .aft-categories {
        flex-direction: row;
        overflow-x: auto;
        white-space: nowrap;
        padding: 8px 10px;
        gap: 6px;
        flex-shrink: 0;
        -webkit-overflow-scrolling: touch;
    }
    .aft-categories::-webkit-scrollbar {
        display: none;
    }
    .aft-cat-btn {
        width: auto;
        white-space: nowrap;
        padding: 6px 12px;
        flex-shrink: 0;
    }
    .aft-cat-count {
        margin-left: 6px;
    }
    .tm-top-bar {
        flex-direction: column;
        align-items: stretch;
    }
    .tm-top-right {
        justify-content: flex-start;
    }
    .tm-search-input {
        width: 100%;
    }
}
</style>
