<template>
    <Head title="Automation - CRMfic" />

    <AppLayout>
        <!-- Page header -->
        <div class="page-header">
            <div class="page-header__left">
                <h1>Automation</h1>
                <p>Build visual, trigger-based workflows to engage contacts automatically.</p>
            </div>
            <div class="page-header__actions">
                <button class="btn btn-primary" @click="showTemplateModal = true">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="16" height="16">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                    </svg>
                    Create Automation
                </button>
            </div>
        </div>

        <!-- Table -->
        <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"><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 v-model="search" type="search" placeholder="Search automations…" @input="onSearch">
                    </div>
                </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 }} automation{{ selected.length === 1 ? '' : 's' }} selected</span>
                    </div>
                </div>
                <div class="table-toolbar-right" style="overflow: visible;">
                    <template v-if="selected.length > 0">
                        <button class="btn btn-outline" style="color:#dc2626;border-color:#fecaca" @click="showBulkDelete = true">Delete</button>
                        <button class="btn btn-outline" @click="selected = []">Cancel</button>
                    </template>
                    <template v-else>
                        <CwSelect
                            v-model="statusFilter"
                            :options="statusOptions"
                            @change="onSearch"
                            placeholder="All statuses"
                            style="width: 160px;"
                        />
                    </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>Name</th>
                            <th>Enrolled</th>
                            <th>Active</th>
                            <th>Completed</th>
                            <th>Status</th>
                            <th style="width:120px">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="automations.data.length === 0">
                            <td colspan="7" style="text-align:center;padding:48px 24px;color:#9ca3af">
                                No automations yet. <button class="link-btn" @click="showTemplateModal = true">Create your first one.</button>
                            </td>
                        </tr>
                        <tr v-for="a in automations.data" :key="a.id" :class="{ 'is-selected': selected.includes(a.id) }">
                            <td class="cell-check" data-label=""><input type="checkbox" class="table-checkbox" :value="a.id" v-model="selected"></td>
                            <td class="cell-name cell-title" data-label="Automation">
                                <div class="automation-title-container">
                                    <Link :href="`/automation/${a.id}/edit`" class="automation-title-link">
                                        {{ a.title }}
                                    </Link>
                                </div>
                                <div style="font-size:11px;color:var(--text-muted);display:flex;align-items:center;gap:4px;margin-top:2px">
                                    <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">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z" />
                                    </svg>
                                    Trigger: {{ triggerLabel(a.trigger) }}
                                </div>
                            </td>
                            <td class="cell-enrolled" data-label="Enrolled" style="font-size:13px">{{ (a.enrolled ?? 0).toLocaleString() }}</td>
                            <td class="cell-active" data-label="Active" style="font-size:13px">{{ (a.active ?? 0).toLocaleString() }}</td>
                            <td class="cell-completed" data-label="Completed" style="font-size:13px">{{ (a.completed ?? 0).toLocaleString() }}</td>
                            <td class="cell-status" data-label="Status">
                                <span :class="['badge', a.status === 'active' ? 'badge--success' : a.status === 'paused' ? 'badge--warning' : 'badge--gray']">
                                    {{ a.status.charAt(0).toUpperCase() + a.status.slice(1) }}
                                </span>
                            </td>
                            <td class="cell-actions" data-label="">
                                <div style="display:flex;gap:6px">
                                    <!-- Edit -->
                                    <Link :href="`/automation/${a.id}/edit`" class="re-action-btn"  title="Edit">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#2563eb"><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>
                                    
                                    <!-- Report -->
                                    <Link :href="`/automation/${a.id}/report`" class="re-action-btn"  title="View Report">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#0f766e">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v5.25c0 .621-.504 1.125-1.125 1.125h-2.25A1.125 1.125 0 013 18.375v-5.25zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125v-9.75zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v14.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z" />
                                        </svg>
                                    </Link>
                                    
                                    <!-- Pause / Resume -->
                                    <button v-if="a.status === 'active'" class="re-action-btn" title="Pause" @click="updateAutomationStatus(a, 'paused')">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#f59e0b"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25v13.5m-7.5-13.5v13.5"/></svg>
                                    </button>
                                    <button v-else class="re-action-btn" title="Resume" @click="updateAutomationStatus(a, 'active')">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#16a34a"><path stroke-linecap="round" stroke-linejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.348a1.125 1.125 0 010 1.971l-11.54 6.347a1.125 1.125 0 01-1.667-.985V5.653z"/></svg>
                                    </button>
                                    
                                    <!-- Delete -->
                                    <button class="re-action-btn" title="Delete" @click="confirmDelete(a)">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#ef4444"><path 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"/></svg>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Pagination (Outside table-wrap) -->
        <div v-if="automations.links && automations.links.length > 3" class="table-pagination" style="margin-top: 16px;">
            <template v-for="link in automations.links" :key="link.label">
                <Link v-if="link.url" :href="link.url" class="page-link" :class="{ active: link.active }" v-html="link.label" />
                <span v-else class="page-link disabled" v-html="link.label" />
            </template>
        </div>

        <!-- ── Create Automation Template Modal ── -->
        <Teleport to="body">
            <div v-if="showTemplateModal" class="modal-overlay is-open" @click.self="closeTemplateModal">
                <div class="aft-modal">
                    <!-- Modal header -->
                    <div class="aft-modal__header">
                        <div class="aft-modal__header-left">
                            <h3 class="aft-modal__title">Create an Automation</h3>
                            <p class="aft-modal__subtitle">Choose a pre-built template or start from scratch</p>
                        </div>
                        <button class="modal-close" @click="closeTemplateModal">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="18" height="18"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                        </button>
                    </div>

                    <!-- Modal body: split layout -->
                    <div class="aft-modal__body">
                        <!-- Left: Category + Template list -->
                        <div class="aft-sidebar">
                            <!-- Category filters -->
                            <div class="aft-categories" :class="{ 'is-mobile-open': catMobileOpen }">
                                <!-- Mobile Category Toggle Button -->
                                <button type="button" class="aft-cat-mobile-toggle" @click="catMobileOpen = !catMobileOpen">
                                    <div class="aft-cat-mobile-toggle-left">
                                        <span class="aft-cat-icon" v-html="currentCatObj.icon"></span>
                                        <span class="aft-cat-mobile-label">{{ currentCatObj.label }}</span>
                                        <span class="aft-cat-count">{{ filteredTemplates.filter(t => currentCatObj.id === 'all' || t.category === currentCatObj.id).length }}</span>
                                    </div>
                                    <div class="aft-cat-mobile-toggle-right">
                                        <span class="aft-cat-mobile-hint">{{ catMobileOpen ? 'Close' : 'Categories' }}</span>
                                        <svg class="aft-cat-chevron" :class="{ 'is-open': catMobileOpen }" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                                        </svg>
                                    </div>
                                </button>

                                <!-- Category list -->
                                <div class="aft-cat-list" :class="{ 'is-open': catMobileOpen }">
                                    <button
                                        v-for="cat in templateCategories"
                                        :key="cat.id"
                                        class="aft-cat-btn"
                                        :class="{ 'is-active': activeCategory === cat.id }"
                                        @click="activeCategory = cat.id; previewTemplate = null; catMobileOpen = false"
                                    >
                                        <span class="aft-cat-icon" v-html="cat.icon"></span>
                                        <span class="aft-cat-label-text">{{ cat.label }}</span>
                                        <span class="aft-cat-count">{{ filteredTemplates.filter(t => cat.id === 'all' || t.category === cat.id).length }}</span>
                                    </button>
                                </div>
                            </div>

                            <!-- Template grid -->
                            <div class="aft-list">
                                <!-- Create from Scratch -->
                                <div
                                    class="aft-card aft-card--scratch"
                                    :class="{ 'is-active': previewTemplate === null && activeCategory === 'all' }"
                                    @click="previewTemplate = 'scratch'"
                                >
                                    <div class="aft-card__icon aft-card__icon--scratch">
                                        <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 4.5v15m7.5-7.5h-15"/></svg>
                                    </div>
                                    <div class="aft-card__body">
                                        <div class="aft-card__name">Build from Scratch</div>
                                        <div class="aft-card__desc">Start with a blank canvas</div>
                                    </div>
                                </div>

                                <!-- Template cards -->
                                <div
                                    v-for="tpl in visibleTemplates"
                                    :key="tpl.id"
                                    class="aft-card"
                                    :class="{ 'is-active': previewTemplate?.id === tpl.id }"
                                    @click="previewTemplate = tpl"
                                >
                                    <div class="aft-card__icon" :style="{ background: tpl.iconBg, color: tpl.iconColor }">
                                        <span v-html="tpl.icon"></span>
                                    </div>
                                    <div class="aft-card__body">
                                        <div class="aft-card__name">{{ tpl.name }}</div>
                                        <div class="aft-card__desc">{{ tpl.shortDesc }}</div>
                                    </div>
                                    <span v-if="tpl.popular" class="aft-card__badge">Popular</span>
                                </div>
                            </div>
                        </div>

                        <!-- Right: Preview panel -->
                        <div class="aft-preview">
                            <!-- Scrollable content area -->
                            <div class="aft-preview__scroll">

                                <!-- Scratch preview -->
                                <template v-if="previewTemplate === 'scratch'">
                                    <div class="aft-preview__empty">
                                        <div class="aft-preview__scratch-icon">
                                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" width="40" height="40"><path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                        </div>
                                        <h4>Build your own workflow</h4>
                                        <p>Design a custom automation from the ground up. You have full control over every trigger, condition, and action.</p>
                                    </div>
                                </template>

                                <!-- Template preview -->
                                <template v-else-if="previewTemplate">
                                    <div class="aft-preview__header">
                                        <div class="aft-preview__tpl-icon" :style="{ background: previewTemplate.iconBg, color: previewTemplate.iconColor }">
                                            <span v-html="previewTemplate.icon"></span>
                                        </div>
                                        <div>
                                            <h4 class="aft-preview__tpl-name">{{ previewTemplate.name }}</h4>
                                            <span class="aft-preview__tpl-cat">{{ categoryLabel(previewTemplate.category) }}</span>
                                        </div>
                                    </div>

                                    <p class="aft-preview__desc">{{ previewTemplate.desc }}</p>

                                    <!-- Workflow steps preview -->
                                    <div class="aft-preview__steps">
                                        <div class="aft-step" v-for="(step, i) in previewTemplate.steps" :key="i">
                                            <div class="aft-step__connector" v-if="i > 0"></div>
                                            <div class="aft-step__node" :class="`aft-step__node--${step.type}`">
                                                <span class="aft-step__node-icon" v-html="stepIcon(step.type)"></span>
                                                <div class="aft-step__node-body">
                                                    <div class="aft-step__node-type">{{ step.type.toUpperCase() }}</div>
                                                    <div class="aft-step__node-label">{{ step.label }}</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="aft-preview__meta">
                                        <div class="aft-preview__meta-item">
                                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="13" height="13"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 010 3.75H5.625a1.875 1.875 0 010-3.75z"/></svg>
                                            {{ previewTemplate.steps.length }} steps
                                        </div>
                                        <div class="aft-preview__meta-item">
                                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="13" height="13"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z"/></svg>
                                            {{ previewTemplate.trigger }}
                                        </div>
                                        <div class="aft-preview__meta-item">
                                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="13" height="13"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                                            ~{{ previewTemplate.setupTime }} to set up
                                        </div>
                                    </div>
                                </template>

                                <!-- Default empty state -->
                                <template v-else>
                                    <div class="aft-preview__empty">
                                        <div class="aft-preview__empty-icon">
                                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" width="40" height="40"><path stroke-linecap="round" stroke-linejoin="round" d="M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zm-7.518-.267A8.25 8.25 0 1120.25 10.5M8.288 14.212A5.25 5.25 0 1117.25 10.5"/></svg>
                                        </div>
                                        <h4>Select a template</h4>
                                        <p>Click any template on the left to preview its workflow before importing it.</p>
                                    </div>
                                </template>

                            </div>

                            <!-- Sticky footer: action button always visible on right -->
                            <div class="aft-preview__footer" v-if="previewTemplate">
                                <div class="aft-preview__footer-meta" v-if="previewTemplate !== 'scratch' && previewTemplate">
                                    <span>{{ previewTemplate.steps?.length ?? 0 }} steps</span>
                                    <span>·</span>
                                    <span>~{{ previewTemplate.setupTime }} to set up</span>
                                </div>
                                <button
                                    class="btn btn-primary aft-import-btn"
                                    @click="previewTemplate === 'scratch' ? createAutomation(null) : createAutomation(previewTemplate.id)"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="15" height="15"><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.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"/></svg>
                                    {{ previewTemplate === 'scratch' ? 'Start building' : 'Use this template' }}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </Teleport>

        <!-- Delete Confirm Modal -->
        <ConfirmModal
            v-if="showDeleteConfirm"
            title="Delete Automation"
            :message="`Are you sure you want to delete '${deleteTarget?.title}'? This cannot be undone.`"
            confirmText="Delete"
            isDestructive
            @resolve="val => val ? doDelete() : showDeleteConfirm = false"
        />

        <!-- Bulk Delete Confirm -->
        <ConfirmModal
            v-if="showBulkDelete"
            title="Delete Automations"
            :message="`Delete ${selected.length} selected automation(s)? This cannot be undone.`"
            confirmText="Delete All"
            isDestructive
            @resolve="val => val ? doBulkDelete() : showBulkDelete = false"
        />
    </AppLayout>
</template>

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

const props = defineProps({
    automations: Object,
    filters: Object,
});

const search = ref(props.filters?.search || '');
const statusFilter = ref(props.filters?.status || '');
const selected = ref([]);
const openMenuId = ref(null);
const showTemplateModal = ref(false);
const showDeleteConfirm = ref(false);
const showBulkDelete = ref(false);
const deleteTarget = ref(null);
const previewTemplate = ref(null);
const activeCategory = ref('all');
const catMobileOpen = ref(false);

const currentCatObj = computed(() => {
    return templateCategories.find(c => c.id === activeCategory.value) || templateCategories[0];
});

// ── Template Categories ──────────────────────────────────────────────────────
const templateCategories = [
    {
        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="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>`,
    },
    {
        id: 'welcome',
        label: 'Welcome & Onboarding',
        icon: `<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="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: 'engagement',
        label: 'Engagement',
        icon: `<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="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z"/></svg>`,
    },
    {
        id: 'sales',
        label: 'Sales & Revenue',
        icon: `<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="M2.25 18.75a60.07 60.07 0 0115.797 2.101c.727.198 1.453-.342 1.453-1.096V18.75M3.75 4.5v.75A.75.75 0 013 6h-.75m0 0v-.375c0-.621.504-1.125 1.125-1.125H20.25M2.25 6v9m18-10.5v.75c0 .414.336.75.75.75h.75m-1.5-1.5h.375c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-.375m1.5-1.5H21a.75.75 0 00-.75.75v.75m0 0H3.75m0 0h-.375a1.125 1.125 0 01-1.125-1.125V15m1.5 1.5v-.75A.75.75 0 003 15h-.75M15 10.5a3 3 0 11-6 0 3 3 0 016 0zm3 0h.008v.008H18V10.5zm-12 0h.008v.008H6V10.5z"/></svg>`,
    },
    {
        id: 'retention',
        label: 'Retention & Win-Back',
        icon: `<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="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"/></svg>`,
    },
    {
        id: 'lead',
        label: 'Lead Nurturing',
        icon: `<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 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v5.25c0 .621-.504 1.125-1.125 1.125h-2.25A1.125 1.125 0 013 18.375v-5.25zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125v-9.75zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v14.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"/></svg>`,
    },
    {
        id: 'event',
        label: 'Events & Milestones',
        icon: `<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="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>`,
    },
];

// ── Templates ────────────────────────────────────────────────────────────────
const allTemplates = [
    // ── Welcome & Onboarding ──
    {
        id: 'welcome_new',
        name: 'Welcome New Subscribers',
        shortDesc: 'Greet new contacts with a warm welcome series',
        desc: 'Automatically send a series of welcome emails to new subscribers. Build trust, introduce your brand, and guide them through your product or service.',
        category: 'welcome',
        popular: true,
        trigger: 'Contact Subscribes to List',
        setupTime: '5 min',
        iconBg: '#E8F0FE',
        iconColor: '#4285F4',
        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>`,
        steps: [
            { type: 'trigger', label: 'Contact subscribes to list' },
            { type: 'action', label: 'Send welcome email' },
            { type: 'delay', label: 'Wait 2 days' },
            { type: 'action', label: 'Send getting started guide' },
            { type: 'delay', label: 'Wait 3 days' },
            { type: 'action', label: 'Send social proof / testimonials email' },
        ],
    },
    {
        id: 'onboarding',
        name: 'New User Onboarding',
        shortDesc: 'Guide new users through your product step by step',
        desc: 'A structured onboarding sequence that helps new users understand your product\'s value, activate key features, and complete their setup.',
        category: 'welcome',
        popular: true,
        trigger: 'New User Sign Up',
        setupTime: '10 min',
        iconBg: '#E6F4EA',
        iconColor: '#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="M4.26 10.147a60.436 60.436 0 00-.491 6.347A48.627 48.627 0 0112 20.904a48.627 48.627 0 018.232-4.41 60.46 60.46 0 00-.491-6.347m-15.482 0a50.57 50.57 0 00-2.658-.813A59.905 59.905 0 0112 3.493a59.902 59.902 0 0110.399 5.84c-.896.248-1.783.52-2.658.814m-15.482 0A50.697 50.697 0 0112 13.489a50.702 50.702 0 017.74-3.342M6.75 15a.75.75 0 100-1.5.75.75 0 000 1.5zm0 0v-3.675A55.378 55.378 0 0112 8.443m-7.007 11.55A5.981 5.981 0 006.75 15.75v-1.5"/></svg>`,
        steps: [
            { type: 'trigger', label: 'New user signs up' },
            { type: 'action', label: 'Send welcome & account setup email' },
            { type: 'delay', label: 'Wait 1 day' },
            { type: 'condition', label: 'Has completed profile?' },
            { type: 'action', label: 'Send feature highlight email' },
            { type: 'delay', label: 'Wait 3 days' },
            { type: 'action', label: 'Send tips & tricks email' },
        ],
    },

    // ── Engagement ──
    {
        id: 'reengagement',
        name: 'Re-engagement Campaign',
        shortDesc: 'Win back contacts who stopped opening emails',
        desc: 'Identify inactive subscribers and re-engage them with a targeted win-back campaign. Sunset contacts who remain unresponsive to keep your list healthy.',
        category: 'engagement',
        popular: true,
        trigger: 'Email Not Opened (30 days)',
        setupTime: '8 min',
        iconBg: '#FCE8E6',
        iconColor: '#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="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Contact inactive for 30 days' },
            { type: 'action', label: 'Send "We miss you" email' },
            { type: 'delay', label: 'Wait 5 days' },
            { type: 'condition', label: 'Opened re-engagement email?' },
            { type: 'action', label: 'Send special comeback offer' },
            { type: 'delay', label: 'Wait 7 days' },
            { type: 'action', label: 'Final unsubscribe or reactivate email' },
        ],
    },
    {
        id: 'inactive',
        name: 'Inactive Customer Recovery',
        shortDesc: 'Recover idle customers with a 3-step sequence',
        desc: 'Recover your idle customers with a targeted 3-step re-engagement sequence. Offer incentives, share new content, and restore the relationship.',
        category: 'engagement',
        popular: false,
        trigger: 'Tag Applied: Inactive',
        setupTime: '6 min',
        iconBg: '#FEF7E0',
        iconColor: '#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="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Tag "Inactive" is applied' },
            { type: 'action', label: 'Send check-in email' },
            { type: 'delay', label: 'Wait 3 days' },
            { type: 'action', label: 'Send exclusive offer email' },
            { type: 'delay', label: 'Wait 4 days' },
            { type: 'action', label: 'Send final notice or farewell' },
        ],
    },
    {
        id: 'email_click_followup',
        name: 'Email Click Follow-Up',
        shortDesc: 'Follow up with contacts who clicked a link',
        desc: 'When a contact clicks a link in your email, automatically follow up with targeted content relevant to their interest. Perfect for nurturing leads down the funnel.',
        category: 'engagement',
        popular: false,
        trigger: 'Email Link Clicked',
        setupTime: '5 min',
        iconBg: '#dbeafe',
        iconColor: '#2563eb',
        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.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zm-7.518-.267A8.25 8.25 0 1120.25 10.5M8.288 14.212A5.25 5.25 0 1117.25 10.5"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Contact clicks a link in email' },
            { type: 'action', label: 'Apply interest tag' },
            { type: 'delay', label: 'Wait 1 day' },
            { type: 'action', label: 'Send related follow-up content' },
            { type: 'delay', label: 'Wait 2 days' },
            { type: 'action', label: 'Send conversion-focused offer' },
        ],
    },

    // ── Sales & Revenue ──
    {
        id: 'upsell',
        name: 'Post-Purchase Upsell',
        shortDesc: 'Upsell or cross-sell right after a purchase',
        desc: 'Automatically send cross-sell and upsell emails right after a customer makes a purchase. Increase average order value and maximize revenue per customer.',
        category: 'sales',
        popular: true,
        trigger: 'Purchase Completed',
        setupTime: '7 min',
        iconBg: '#E6F4EA',
        iconColor: '#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="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 00-16.536-1.84M7.5 14.25L5.106 5.272M6 20.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm12.75 0a.75.75 0 11-1.5 0 .75.75 0 011.5 0z"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Purchase completed' },
            { type: 'action', label: 'Send order confirmation & thank you' },
            { type: 'delay', label: 'Wait 2 days' },
            { type: 'action', label: 'Send related product recommendations' },
            { type: 'delay', label: 'Wait 3 days' },
            { type: 'action', label: 'Send exclusive discount for next order' },
        ],
    },
    {
        id: 'recommend',
        name: 'Product Recommendation',
        shortDesc: 'Recommend products based on purchase history',
        desc: 'Boost revenue by recommending products right after a purchase. Leverage purchase behavior to suggest items that genuinely complement what they already bought.',
        category: 'sales',
        popular: false,
        trigger: 'Purchase Completed',
        setupTime: '6 min',
        iconBg: '#FCE8E6',
        iconColor: '#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="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Purchase completed' },
            { type: 'delay', label: 'Wait 3 days' },
            { type: 'action', label: 'Send "Customers also bought" email' },
            { type: 'delay', label: 'Wait 5 days' },
            { type: 'condition', label: 'Clicked recommendation?' },
            { type: 'action', label: 'Send limited-time offer for that product' },
        ],
    },
    {
        id: 'feedback',
        name: 'Post-Purchase Feedback',
        shortDesc: 'Collect reviews and feedback after purchase',
        desc: 'Automatically request reviews and feedback after a customer makes a purchase. Build social proof, improve your product, and show customers you care.',
        category: 'sales',
        popular: false,
        trigger: 'Purchase Completed',
        setupTime: '5 min',
        iconBg: '#FEF7E0',
        iconColor: '#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="M11.48 3.499a.562.562 0 011.04 0l2.125 5.111a.563.563 0 00.475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 00-.182.557l1.285 5.385a.562.562 0 01-.84.61l-4.725-2.885a.563.563 0 00-.586 0L6.982 20.54a.562.562 0 01-.84-.61l1.285-5.386a.562.562 0 00-.182-.557l-4.204-3.602a.563.563 0 01.321-.988l5.518-.442a.563.563 0 00.475-.345L11.48 3.5z"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Purchase completed' },
            { type: 'delay', label: 'Wait 7 days' },
            { type: 'action', label: 'Send feedback request email' },
            { type: 'delay', label: 'Wait 3 days' },
            { type: 'condition', label: 'Submitted review?' },
            { type: 'action', label: 'Send thank you coupon or reward' },
        ],
    },

    // ── Retention & Win-Back ──
    {
        id: 'winback',
        name: 'Customer Win-Back',
        shortDesc: 'Re-engage customers who haven\'t purchased in 90 days',
        desc: 'Automatically identify customers who haven\'t purchased in 90+ days and send a targeted win-back sequence with incentives to bring them back.',
        category: 'retention',
        popular: true,
        trigger: 'No Purchase in 90 Days',
        setupTime: '8 min',
        iconBg: '#E8F0FE',
        iconColor: '#4285F4',
        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="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Tag "At Risk" applied' },
            { type: 'action', label: 'Send "We miss you" email' },
            { type: 'delay', label: 'Wait 5 days' },
            { type: 'action', label: 'Send exclusive 20% off coupon' },
            { type: 'delay', label: 'Wait 7 days' },
            { type: 'condition', label: 'Made a purchase?' },
            { type: 'action', label: 'Send final win-back or sunset email' },
        ],
    },
    {
        id: 'cart_abandon',
        name: 'Cart Abandonment Recovery',
        shortDesc: 'Recover lost sales from abandoned carts',
        desc: 'Automatically follow up with customers who left items in their cart. Use urgency, social proof, and discounts to recover lost revenue.',
        category: 'retention',
        popular: true,
        trigger: 'Cart Abandoned',
        setupTime: '7 min',
        iconBg: '#FCE8E6',
        iconColor: '#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="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 00-16.536-1.84M7.5 14.25L5.106 5.272M6 20.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm12.75 0a.75.75 0 11-1.5 0 .75.75 0 011.5 0z"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Cart abandoned (1 hour)' },
            { type: 'action', label: 'Send cart reminder email' },
            { type: 'delay', label: 'Wait 12 hours' },
            { type: 'condition', label: 'Completed purchase?' },
            { type: 'action', label: 'Send urgency reminder with scarcity' },
            { type: 'delay', label: 'Wait 1 day' },
            { type: 'action', label: 'Send final offer with discount' },
        ],
    },

    // ── Lead Nurturing ──
    {
        id: 'lead_nurture',
        name: 'Lead Nurture Drip',
        shortDesc: 'Educate and convert leads over time',
        desc: 'A multi-step educational drip sequence designed to nurture leads from awareness to conversion. Deliver value, build trust, and guide them toward a purchase decision.',
        category: 'lead',
        popular: true,
        trigger: 'Contact Created / Lead Captured',
        setupTime: '12 min',
        iconBg: '#dbeafe',
        iconColor: '#2563eb',
        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="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v5.25c0 .621-.504 1.125-1.125 1.125h-2.25A1.125 1.125 0 013 18.375v-5.25zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125v-9.75zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v14.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"/></svg>`,
        steps: [
            { type: 'trigger', label: 'New lead captured' },
            { type: 'action', label: 'Send lead magnet / resource' },
            { type: 'delay', label: 'Wait 2 days' },
            { type: 'action', label: 'Send educational content email' },
            { type: 'delay', label: 'Wait 3 days' },
            { type: 'action', label: 'Send case study / social proof' },
            { type: 'delay', label: 'Wait 3 days' },
            { type: 'action', label: 'Send demo offer or CTA email' },
        ],
    },
    {
        id: 'tag_nurture',
        name: 'Tag-Based Lead Nurture',
        shortDesc: 'Trigger nurture sequences based on contact tags',
        desc: 'When a specific tag is applied to a contact, automatically start a personalized nurture sequence tailored to that interest or behavior.',
        category: 'lead',
        popular: false,
        trigger: 'Tag Applied',
        setupTime: '6 min',
        iconBg: '#E6F4EA',
        iconColor: '#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="M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 005.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 009.568 3z"/><path stroke-linecap="round" stroke-linejoin="round" d="M6 6h.008v.008H6V6z"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Tag applied to contact' },
            { type: 'action', label: 'Send relevant introductory email' },
            { type: 'delay', label: 'Wait 2 days' },
            { type: 'action', label: 'Send deep-dive content email' },
            { type: 'delay', label: 'Wait 4 days' },
            { type: 'action', label: 'Send personalized offer or CTA' },
        ],
    },

    // ── Events & Milestones ──
    {
        id: 'birthday',
        name: 'Birthday Discount',
        shortDesc: 'Send birthday greetings with a special discount',
        desc: 'Delight your contacts on their special day with personalized birthday greetings and an exclusive discount. Simple, effective, and builds lasting loyalty.',
        category: 'event',
        popular: false,
        trigger: 'Contact Birthday',
        setupTime: '4 min',
        iconBg: '#FCE8E6',
        iconColor: '#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="M12 8.25v-1.5m0 1.5c-1.355 0-2.697.056-4.024.166C6.845 8.51 6 9.473 6 10.608v2.513m6-4.87c1.355 0 2.697.055 4.024.165C17.155 8.51 18 9.473 18 10.608v2.513m-3-4.87v-1.5m-6 1.5v-1.5m12 9.75l-1.5.75a3.354 3.354 0 01-3 0 3.354 3.354 0 00-3 0 3.354 3.354 0 01-3 0 3.354 3.354 0 00-3 0 3.354 3.354 0 01-3 0L3 16.5m15-3.38a48.474 48.474 0 00-6-.37c-2.032 0-4.034.125-6 .37m12 0c.39.049.777.102 1.163.16 1.07.16 1.837 1.094 1.837 2.175v5.17c0 .62-.504 1.124-1.125 1.124H4.125A1.125 1.125 0 013 20.625v-5.17c0-1.08.768-2.014 1.837-2.174A47.78 47.78 0 016 13.12M12.265 3.11a.375.375 0 11-.53 0L12 2.845l.265.265zm-3 0a.375.375 0 11-.53 0L9 2.845l.265.265zm6 0a.375.375 0 11-.53 0L15 2.845l.265.265z"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Contact birthday (7 days before)' },
            { type: 'action', label: 'Send birthday greeting email with coupon' },
            { type: 'delay', label: 'Wait 3 days (if not redeemed)' },
            { type: 'action', label: 'Send reminder — offer expires soon' },
        ],
    },
    {
        id: 'anniversary',
        name: 'Customer Anniversary',
        shortDesc: 'Celebrate loyalty milestones with your customers',
        desc: 'Recognize and celebrate the anniversary of a contact\'s relationship with your brand. A powerful loyalty-building touch that customers truly appreciate.',
        category: 'event',
        popular: false,
        trigger: 'Contact Anniversary (1 year)',
        setupTime: '4 min',
        iconBg: '#FEF7E0',
        iconColor: '#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="M16.5 18.75h-9m9 0a3 3 0 013 3h-15a3 3 0 013-3m9 0v-3.375c0-.621-.503-1.125-1.125-1.125h-.871M7.5 18.75v-3.375c0-.621.504-1.125 1.125-1.125h.872m5.007 0H9.497m5.007 0a7.454 7.454 0 01-.982-3.172M9.497 14.25a7.454 7.454 0 00.981-3.172M5.25 4.236c-.982.143-1.954.317-2.916.52A6.003 6.003 0 007.73 9.728M5.25 4.236V4.5c0 2.108.966 3.99 2.48 5.228M5.25 4.236V2.721C7.456 2.41 9.71 2.25 12 2.25c2.291 0 4.545.16 6.75.47v1.516M7.73 9.728a6.726 6.726 0 002.748 1.35m8.272-6.842V4.5c0 2.108-.966 3.99-2.48 5.228m2.48-5.492a46.32 46.32 0 012.916.52 6.003 6.003 0 01-5.395 4.972m0 0a6.726 6.726 0 01-2.749 1.35m0 0a6.772 6.772 0 01-3.044 0"/></svg>`,
        steps: [
            { type: 'trigger', label: 'Contact anniversary date reached' },
            { type: 'action', label: 'Send heartfelt anniversary email' },
            { type: 'action', label: 'Apply "Loyal Customer" tag' },
            { type: 'delay', label: 'Wait 1 day' },
            { type: 'action', label: 'Send exclusive loyalty reward email' },
        ],
    },
];

// ── Computed ─────────────────────────────────────────────────────────────────
const filteredTemplates = computed(() => allTemplates);

const visibleTemplates = computed(() => {
    if (activeCategory.value === 'all') return allTemplates;
    return allTemplates.filter(t => t.category === activeCategory.value);
});

function categoryLabel(id) {
    const cat = templateCategories.find(c => c.id === id);
    return cat?.label ?? id;
}

function stepIcon(type) {
    const icons = {
        trigger: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="12" height="12"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z"/></svg>`,
        action: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="12" height="12"><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>`,
        condition: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="12" height="12"><path stroke-linecap="round" stroke-linejoin="round" d="M7.5 21L3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5"/></svg>`,
        delay: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="12" height="12"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>`,
    };
    return icons[type] ?? icons.action;
}

// ── Table helpers ─────────────────────────────────────────────────────────────
const allSelected = computed(() => {
    return props.automations.data.length > 0 && selected.value.length === props.automations.data.length;
});

function toggleAll() {
    if (allSelected.value) {
        selected.value = [];
    } else {
        selected.value = props.automations.data.map(a => a.id);
    }
}

const statusOptions = [
    { label: 'All statuses', value: '' },
    { label: 'Draft', value: 'draft' },
    { label: 'Active', value: 'active' },
    { label: 'Paused', value: 'paused' },
];

let searchTimer = null;
function onSearch() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        router.get('/automation', {
            search: search.value || undefined,
            status: statusFilter.value || undefined,
        }, { preserveState: true, replace: true });
    }, 300);
}

function triggerLabel(type) {
    if (!type) return 'Unknown';
    return type.split(', ').map(t => {
        const map = {
            new_user_signup: 'New User Sign Up',
            subscribes_to_list: 'Contact Subscribes to List',
            tag_applied: 'Tag Applied',
            contact_created: 'Contact Created',
            contact_updated: 'Contact Updated',
            unsubscribes_from_list: 'Unsubscribes from List',
            tag_removed: 'Tag Removed',
            email_opened: 'Email Opened',
            email_clicked: 'Email Clicked',
            unsubscribed: 'Unsubscribed',
            birthday: 'Contact Birthday',
        };
        return map[t] || t.toUpperCase().replace('_', ' ');
    }).join(' or ');
}

function toggleMenu(id) {
    openMenuId.value = openMenuId.value === id ? null : id;
}

function updateAutomationStatus(a, status) {
    axios.put(`/automation/${a.id}`, { status })
        .then(() => {
            a.status = status;
        })
        .catch(err => {
            console.error('Failed to update status', err);
        });
}

function closeTemplateModal() {
    showTemplateModal.value = false;
    previewTemplate.value = null;
    activeCategory.value = 'all';
}

function createAutomation(templateId) {
    const templateTitles = {
        // Legacy IDs (kept for backward compat)
        inactive: 'Inactive Customer Automation',
        reengagement: 'Re-engagement Email Automation',
        feedback: 'WooCommerce Feedback Automation',
        upsell: 'Post-Purchase Upsell Automation',
        recommend: 'Product Recommendation Automation',
        birthday: 'Birthday Discount Automation',
    };

    // New template IDs – use name from allTemplates
    const tpl = allTemplates.find(t => t.id === templateId);
    const title = tpl ? tpl.name : (templateId ? (templateTitles[templateId] ?? 'New Automation') : 'New Automation');

    router.post('/automation', { title, template: templateId });
    closeTemplateModal();
}

function confirmDelete(a) {
    deleteTarget.value = a;
    showDeleteConfirm.value = true;
    openMenuId.value = null;
}

function doDelete() {
    if (!deleteTarget.value) return;
    router.delete(`/automation/${deleteTarget.value.id}`, { preserveScroll: true });
    showDeleteConfirm.value = false;
    deleteTarget.value = null;
}

function doBulkDelete() {
    router.post('/automation/bulk-delete', { ids: selected.value }, {
        preserveScroll: true,
        onSuccess: () => { selected.value = []; },
    });
    showBulkDelete.value = false;
}

// Close dropdown on outside click
if (typeof document !== 'undefined') {
    document.addEventListener('click', () => { openMenuId.value = null; });
}
</script>

<style scoped>
.re-action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    border-radius: 6px;
    border: 1px solid transparent;
    background: transparent;
    cursor: pointer;
    text-decoration: none;
    transition: opacity 0.15s ease;
    color: var(--text-secondary);
    transition: background 0.1s, border-color 0.1s, color 0.1s;
    
}
.re-action-btn:hover {
    opacity: 0.9;
    background: var(--bg-hover);
    border-color: var(--border-color);
}
.automation-title-link {
    font-weight: 600;
    color: var(--text-primary);
    text-decoration: none;
    transition: color 0.15s ease;
}
.automation-title-link:hover {
    color: var(--active-text, #2563eb);
    text-decoration: underline;
}

/* ── Responsive table card layout ── */
@media (max-width: 1024px) {
    .data-table thead { display: none; }
    .data-table tbody tr {
        display: grid;
        grid-template-columns: 1fr auto;
        grid-template-rows: auto auto;
        gap: 4px 8px;
        padding: 12px 14px;
        border-bottom: 1px solid var(--border-color);
        background: var(--bg-surface);
        position: relative;
    }
    .data-table tbody tr:last-child { border-bottom: none; }
    .cell-check {
        position: absolute;
        top: 12px;
        left: 8px;
    }
    .cell-name {
        grid-column: 1;
        grid-row: 1;
        padding-left: 28px;
    }
    .cell-actions {
        grid-column: 2;
        grid-row: 1 / 3;
        display: flex;
        align-items: center;
    }
    .cell-enrolled,
    .cell-active,
    .cell-completed,
    .cell-status {
        grid-column: 1;
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
        color: var(--text-secondary);
        padding-left: 10px;
    }
    .cell-enrolled::before  { content: attr(data-label) ": "; font-weight: 600; color: var(--text-muted); }
    .cell-active::before    { content: attr(data-label) ": "; font-weight: 600; color: var(--text-muted); }
    .cell-completed::before { content: attr(data-label) ": "; font-weight: 600; color: var(--text-muted); }
    .cell-status::before    { content: attr(data-label) ": "; font-weight: 600; color: var(--text-muted); }
}

/* ── Automation Funnel Template Modal ── */
.aft-modal {
    background: var(--bg-surface);
    border-radius: 16px;
    box-shadow: 0 20px 60px rgba(0,0,0,.18), 0 8px 20px rgba(0,0,0,.10);
    width: 95%;
    max-width: 960px;
    height: 640px;
    max-height: calc(100vh - 48px);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    animation: aft-in 0.22s ease;
}
@keyframes aft-in {
    from { opacity: 0; transform: translateY(10px) scale(0.98); }
    to   { opacity: 1; transform: translateY(0) scale(1); }
}

.aft-modal__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px 16px;
    border-bottom: 1px solid var(--border-color);
    flex-shrink: 0;
}
.aft-modal__title {
    font-size: 17px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0;
}
.aft-modal__subtitle {
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 2px;
}

.aft-modal__body {
    display: flex;
    flex: 1;
    overflow: hidden;
    min-height: 0;
}

/* ── Sidebar (categories + list) ── */
.aft-sidebar {
    width: 340px;
    flex-shrink: 0;
    border-right: 1px solid var(--border-color);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.aft-categories {
    padding: 12px 12px 8px;
    display: flex;
    flex-direction: column;
    gap: 2px;
    border-bottom: 1px solid var(--border-color);
    flex-shrink: 0;
}

.aft-cat-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 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);
}

.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);
    box-shadow: 0 0 0 0px rgba(66,133,244,.2);
}
.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;
}

/* ── Preview panel ── */
.aft-preview {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    overflow: hidden;
}
/* scrollable inner content */
.aft-preview__scroll {
    flex: 1;
    overflow-y: auto;
    padding: 24px 24px 16px;
    display: flex;
    flex-direction: column;
}
.aft-preview__scroll::-webkit-scrollbar { width: 4px; }
.aft-preview__scroll::-webkit-scrollbar-track { background: transparent; }
.aft-preview__scroll::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 2px; }
/* sticky footer */
.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;
}

.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: 72px;
    height: 72px;
    border-radius: 18px;
    background: var(--bg-hover);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text-muted);
    margin-bottom: 4px;
}
.aft-preview__scratch-icon {
    background: var(--active-bg);
    color: var(--active-text);
}
.aft-preview__empty h4 {
    font-size: 15px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0;
}
.aft-preview__empty p {
    font-size: 13px;
    color: var(--text-secondary);
    margin: 0;
    max-width: 320px;
    line-height: 1.6;
}

.aft-preview__header {
    display: flex;
    align-items: center;
    gap: 14px;
    margin-bottom: 14px;
}
.aft-preview__tpl-icon {
    width: 52px;
    height: 52px;
    border-radius: 13px;
    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__desc {
    font-size: 13px;
    color: var(--text-secondary);
    line-height: 1.65;
    margin-bottom: 20px;
}

/* Workflow steps */
.aft-preview__steps {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
    flex: 1;
}
.aft-step {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}
.aft-step__connector {
    width: 2px;
    height: 14px;
    background: var(--border-color);
    margin-left: 16px;
    flex-shrink: 0;
}
.aft-step__node {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 8px 12px;
    border-radius: 9px;
    border: 1.5px solid var(--border-color);
    background: var(--bg-surface);
    width: 100%;
    transition: border-color 0.12s;
}
.aft-step__node:hover { border-color: var(--active-text, #c5d9fd); }
.aft-step__node--trigger {
    border-color: #C5D9FD;
    background: #F0F5FF;
}
.aft-step__node--action {
    border-color: #A8D5B5;
    background: #F0FAF4;
}
.aft-step__node--condition {
    border-color: #FDD663;
    background: #FEFAE8;
}
.aft-step__node--delay {
    border-color: var(--border-color);
    background: var(--bg-hover);
}
.aft-step__node-icon {
    width: 22px;
    height: 22px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    color: inherit;
    opacity: 0.7;
}
.aft-step__node--trigger  .aft-step__node-icon { color: #4285F4; opacity: 1; }
.aft-step__node--action   .aft-step__node-icon { color: #34A853; opacity: 1; }
.aft-step__node--condition .aft-step__node-icon { color: #F9AB00; opacity: 1; }
.aft-step__node--delay     .aft-step__node-icon { color: var(--text-muted); }
.aft-step__node-body { flex: 1; min-width: 0; }
.aft-step__node-type {
    font-size: 9.5px;
    font-weight: 700;
    letter-spacing: 0.06em;
    color: var(--text-muted);
    margin-bottom: 1px;
}
.aft-step__node--trigger  .aft-step__node-type { color: #4285F4; }
.aft-step__node--action   .aft-step__node-type { color: #34A853; }
.aft-step__node--condition .aft-step__node-type { color: #F9AB00; }
.aft-step__node-label {
    font-size: 12.5px;
    font-weight: 500;
    color: var(--text-secondary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.aft-preview__meta {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    padding: 10px 14px;
    background: var(--bg-hover);
    border-radius: 9px;
    flex-wrap: wrap;
}
.aft-preview__meta-item {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 11.5px;
    color: var(--text-secondary);
    font-weight: 500;
}

.aft-categories {
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 2px;
    border-bottom: 1px solid var(--border-color);
    flex-shrink: 0;
}
.aft-cat-mobile-toggle {
    display: none;
}
.aft-cat-list {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.aft-cat-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 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%;
}

/* ── Modal responsive: stack on small screens ── */
@media (max-width: 768px) {
    .aft-modal {
        height: 90vh;
        max-height: 90vh;
        border-radius: 12px;
        width: 95%;
        margin: auto;
        position: relative;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }
    .aft-modal__body {
        flex-direction: column;
        overflow-y: auto;
        flex: 1;
        min-height: 0;
        padding-bottom: 75px;
    }
    .aft-sidebar {
        width: 100%;
        border-right: none;
        border-bottom: 1px solid var(--border-color);
        max-height: none;
        flex-shrink: 0;
        overflow: visible;
    }
    .aft-categories {
        padding: 8px 12px;
        width: 100%;
        box-sizing: border-box;
    }
    .aft-cat-mobile-toggle {
        display: flex !important;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding: 8px 12px;
        background: var(--bg-hover);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        color: var(--text-primary);
        font-weight: 600;
        font-size: 13px;
        cursor: pointer;
        box-sizing: border-box;
    }
    .aft-cat-mobile-toggle-left {
        display: flex;
        align-items: center;
        gap: 8px;
        min-width: 0;
    }
    .aft-cat-mobile-label {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 13px;
    }
    .aft-cat-mobile-toggle-right {
        display: flex;
        align-items: center;
        gap: 6px;
        flex-shrink: 0;
    }
    .aft-cat-mobile-hint {
        font-size: 11px;
        color: var(--text-muted);
        font-weight: 600;
    }
    .aft-cat-chevron {
        width: 14px;
        height: 14px;
        transition: transform 0.2s ease;
        flex-shrink: 0;
    }
    .aft-cat-chevron.is-open {
        transform: rotate(180deg);
    }
    .aft-cat-list {
        display: none;
        flex-direction: column;
        gap: 4px;
        margin-top: 8px;
        padding-top: 8px;
        border-top: 1px solid var(--border-color);
        max-height: 220px;
        overflow-y: auto;
    }
    .aft-cat-list.is-open {
        display: flex !important;
    }
    .aft-cat-btn {
        width: 100% !important;
        white-space: normal;
        padding: 8px 10px;
    }
    .aft-list {
        display: flex;
        flex-direction: column;
        gap: 8px;
        max-height: 250px;
        overflow-y: auto;
        overflow-x: hidden;
        padding: 10px 12px;
        box-sizing: border-box;
        -webkit-overflow-scrolling: touch;
    }
    .aft-card {
        width: 100% !important;
        flex-shrink: 0;
        display: flex;
        flex-direction: row;
        align-items: center;
        gap: 12px;
        padding: 10px 12px;
        border-radius: 10px;
        box-sizing: border-box;
    }
    .aft-card__icon {
        flex-shrink: 0;
        width: 38px;
        height: 38px;
        border-radius: 9px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .aft-card__body {
        flex: 1;
        min-width: 0;
    }
    .aft-card__name {
        font-size: 13px;
        font-weight: 600;
        color: var(--text-primary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .aft-card__desc {
        font-size: 11.5px;
        color: var(--text-secondary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-top: 1px;
    }
    .aft-card__badge {
        flex-shrink: 0;
        font-size: 10px;
        padding: 2px 6px;
    }
    .aft-preview {
        flex: 1;
        min-height: 0;
    }
    .aft-preview__footer {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 50;
        background: var(--bg-surface);
        border-top: 1px solid var(--border-color);
        padding: 10px 14px;
        box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.35);
        display: flex !important;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
        width: 100%;
        box-sizing: border-box;
    }
    .aft-preview__footer-meta {
        display: none !important;
    }
    .aft-import-btn {
        width: 100% !important;
        justify-content: center;
        padding: 12px 16px;
        font-size: 14px;
        font-weight: 600;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(37, 99, 235, 0.35);
    }
}

@media (max-width: 480px) {
    .aft-modal {
        width: 100%;
        border-radius: 12px 12px 0 0;
        height: 95vh;
        max-height: 95vh;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
    }
    .aft-modal__header {
        padding: 16px 16px 12px;
    }
    .aft-preview__scroll {
        padding: 16px;
    }
    .aft-preview__footer {
        padding: 12px 16px;
    }
}
/* removed – actions now in sticky footer */
</style>
