{% extends 'base.html' %}

{% block title %}Form Templates — AgentForms{% endblock %}

{% block head_extra %}
<style nonce="{{ csp_nonce }}">
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: system-ui, -apple-system, sans-serif; background: #f5f5f5; color: #333; }
        a { color: inherit; text-decoration: none; }

        .container { max-width: 1100px; margin: 0 auto; padding: 24px 16px; }

        /* Page header */
        .page-header { margin-bottom: 24px; }
        .page-header h1 { font-size: 28px; font-weight: 700; margin-bottom: 6px; color: #1a1a2e; }
        .page-header p { color: #666; font-size: 15px; line-height: 1.5; }
        .page-header .count { font-size: 13px; color: #888; margin-top: 4px; }

        /* Filters */
        .filters-bar {
            background: white;
            border-radius: 8px;
            padding: 14px 16px;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.08);
        }
        .filters { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
        .filter-btn {
            padding: 6px 14px;
            border: 1px solid #e0e0e0;
            background: white;
            border-radius: 20px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.15s;
            color: #555;
            font-weight: 500;
        }
        .filter-btn:hover { border-color: #1a1a2e; color: #1a1a2e; }
        .filter-btn.active { background: #1a1a2e; color: white; border-color: #1a1a2e; }
        .search-box {
            padding: 6px 12px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            font-size: 13px;
            width: 220px;
            margin-left: auto;
        }
        .search-box:focus { outline: none; border-color: #1a1a2e; }

        /* Template grid */
        .template-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(310px, 1fr));
            gap: 16px;
        }

        .template-card {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 18px;
            transition: all 0.15s;
            position: relative;
            display: flex;
            flex-direction: column;
        }
        .template-card:hover {
            border-color: #1a1a2e;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transform: translateY(-1px);
        }
        .template-card.featured {
            border-left: 3px solid #27ae60;
        }

        .template-card .card-header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .template-card h3 {
            font-size: 16px;
            font-weight: 600;
            color: #1a1a2e;
            line-height: 1.3;
        }
        .template-card .icon { font-size: 20px; margin-right: 10px; flex-shrink: 0; }

        .template-card .category-badge {
            display: inline-block;
            padding: 2px 10px;
            background: #f0f4ff;
            color: #1a5276;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 10px;
        }

        .template-card .description {
            font-size: 13px;
            color: #666;
            margin-bottom: 14px;
            line-height: 1.5;
            flex: 1;
        }

        .template-card .meta {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
            margin-bottom: 14px;
        }
        .template-card .meta .badge {
            padding: 2px 8px;
            background: #f5f5f5;
            border-radius: 12px;
            font-size: 11px;
            color: #777;
        }
        .template-card .meta .badge.conditional { background: #fef3e2; color: #e67e22; }
        .template-card .meta .badge.multi-step { background: #e8f5e9; color: #27ae60; }
        .template-card .meta .badge.featured-badge { background: #fff3cd; color: #856404; }

        .template-card .actions { display: flex; gap: 8px; margin-top: auto; }
        .template-card .actions .btn {
            padding: 7px 14px;
            border-radius: 4px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            text-align: center;
            transition: all 0.15s;
            border: 1px solid transparent;
            flex: 1;
        }
        .template-card .actions .btn-outline {
            background: white;
            border-color: #e0e0e0;
            color: #555;
        }
        .template-card .actions .btn-outline:hover {
            border-color: #1a1a2e;
            color: #1a1a2e;
        }
        .template-card .actions .btn-primary {
            background: #1a1a2e;
            color: white;
        }
        .template-card .actions .btn-primary:hover {
            background: #2d2d4a;
        }

        /* Preview modal */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 100;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .modal-overlay.active { display: flex; }
        .modal {
            background: white;
            border-radius: 8px;
            max-width: 600px;
            width: 100%;
            max-height: 85vh;
            overflow-y: auto;
            padding: 24px;
            position: relative;
        }
        .modal .close-btn {
            position: absolute;
            top: 16px; right: 16px;
            background: none; border: none;
            font-size: 22px; cursor: pointer;
            color: #888; line-height: 1;
        }
        .modal .close-btn:hover { color: #333; }
        .modal h2 { font-size: 20px; margin-bottom: 6px; color: #1a1a2e; }
        .modal .description { color: #666; margin-bottom: 16px; line-height: 1.5; }

        .modal .field-list { margin-bottom: 16px; }
        .modal .field-item {
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .modal .field-item:last-child { border-bottom: none; }
        .modal .field-label { font-weight: 500; font-size: 14px; }
        .modal .field-meta { font-size: 12px; color: #888; }
        .modal .field-badge {
            display: inline-block;
            padding: 1px 6px;
            background: #f0f0f0;
            border-radius: 3px;
            font-size: 11px;
            margin-left: 4px;
        }
        .modal .field-badge.required { background: #fde8e8; color: #c0392b; }
        .modal .field-badge.conditional { background: #fef3e2; color: #e67e22; }
        .modal .actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; }

        /* Steps section in modal */
        .modal .steps-section { margin-bottom: 16px; }
        .modal .steps-section h4 { font-size: 14px; color: #1a1a2e; margin-bottom: 8px; }
        .modal .step-group { padding: 8px 12px; background: #f8f9fa; border-radius: 4px; margin-bottom: 4px; }
        .modal .step-group .step-title { font-weight: 600; font-size: 13px; }
        .modal .step-group .step-fields { font-size: 12px; color: #666; margin-top: 2px; }

        /* Toast */
        .toast {
            position: fixed;
            bottom: 20px; right: 20px;
            background: #27ae60;
            color: white;
            padding: 12px 20px;
            border-radius: 4px;
            font-size: 14px;
            z-index: 200;
            transform: translateY(100px);
            transition: transform 0.3s;
        }
        .toast.show { transform: translateY(0); }
        .toast.error { background: #e74c3c; }

        /* Loading */
        .loading { text-align: center; padding: 40px; color: #888; }
        .loading .spinner {
            display: inline-block;
            width: 24px; height: 24px;
            border: 2px solid #e9ecef;
            border-top-color: #1a1a2e;
            border-radius: 50%;
            animation: spin 0.6s linear infinite;
        }
        @keyframes spin { to { transform: rotate(360deg); } }

        /* Empty state */
        .empty-state { text-align: center; padding: 40px; color: #888; }
        .empty-state p { font-size: 15px; margin-top: 8px; }

        @media (max-width: 640px) {
            .container { padding: 16px; }
            .template-grid { grid-template-columns: 1fr; }
            .filters { flex-direction: column; }
            .search-box { width: 100%; margin-left: 0; }
            .page-header h1 { font-size: 24px; }
        }
    </style>
{% endblock %}

{% block content %}

    <div class="container">
        <div class="page-header">
            <h1>Form Templates</h1>
            <p>Start with a pre-built form — customize fields, add your branding, and go live in minutes.</p>
            <div class="count" id="templateCount"></div>
        </div>

        <!-- Filters -->
        <div class="filters-bar">
            <div class="filters" id="filterBar">
                <button class="filter-btn active" data-category="all">All Templates</button>
                <div id="categoryFilters" class="filters" style="display:contents;"></div>
                <input type="text" class="search-box" id="searchBox" placeholder="Search templates..." />
            </div>
        </div>

        <!-- Template grid -->
        <div class="template-grid" id="templateGrid">
            <div class="loading">
                <div class="spinner"></div>
                <p style="margin-top:8px;">Loading templates...</p>
            </div>
        </div>
    </div>

    <!-- Preview Modal -->
    <div class="modal-overlay" id="previewModal">
        <div class="modal" id="modalContent">
            <button class="close-btn" style="position:absolute;top:16px;right:16px;background:none;border:none;font-size:22px;cursor:pointer;color:#888;">&times;</button>
            <div class="loading"><div class="spinner"></div></div>
        </div>
    </div>

    <!-- Toast -->
    <div class="toast" id="toast"></div>
{% endblock %}

{% block scripts %}
<script nonce="{{ csp_nonce }}">
    let templates = [];
    let allCategories = [];
    let currentCategory = 'all';
    let searchQuery = '';

    async function fetchTemplates() {
            const params = new URLSearchParams();
            if (currentCategory !== 'all') params.set('category', currentCategory);
            if (searchQuery) params.set('q', searchQuery);

            try {
                const resp = await fetch(`/api/v2/templates/?${params}`);
                const data = await resp.json();
                templates = data.templates;
                allCategories = data.categories || [];
                renderCategoryFilters();
                renderGrid();
                document.getElementById('templateCount').textContent =
                    `${data.total} template${data.total !== 1 ? 's' : ''} available`;
            } catch (err) {
                document.getElementById('templateGrid').innerHTML =
                    '<div class="empty-state"><p>Failed to load templates. Please try again.</p></div>';
            }
        }

        function renderCategoryFilters() {
            const container = document.getElementById('categoryFilters');
            if (!allCategories.length) return;

            container.innerHTML = allCategories.map(cat => {
                const isActive = currentCategory === cat ? ' active' : '';
                return `<button class="filter-btn${isActive}" data-category="${cat}">${cat}</button>`;
            }).join('');

            container.querySelectorAll('.filter-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    currentCategory = btn.dataset.category;
                    document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    document.querySelector('[data-category="all"]').classList.remove('active');
                    fetchTemplates();
                });
            });
        }

        function renderGrid() {
            const grid = document.getElementById('templateGrid');

            if (!templates.length) {
                grid.innerHTML = '<div class="empty-state"><p>No templates found matching your search.</p></div>';
                return;
            }

            // Sort: featured first, then alphabetical
            const sorted = [...templates].sort((a, b) => {
                if (a.is_featured && !b.is_featured) return -1;
                if (!a.is_featured && b.is_featured) return 1;
                return a.name.localeCompare(b.name);
            });

            grid.innerHTML = sorted.map(t => {
                const featuredClass = t.is_featured ? ' featured' : '';
                let metaBadges = `<span class="badge">${t.field_count} fields</span>`;
                if (t.steps > 1) metaBadges += `<span class="badge multi-step">${t.steps} steps</span>`;
                if (t.has_conditionals) metaBadges += `<span class="badge conditional">Conditionals</span>`;
                if (t.is_featured) metaBadges += `<span class="badge featured-badge">★ Featured</span>`;

                const icon = t.icon || '📋';

                return `
                <div class="template-card${featuredClass}" data-slug="${t.slug}">
                    <div class="card-header">
                        <h3><span class="icon">${icon}</span>${t.name}</h3>
                    </div>
                    <div class="category-badge">${t.category}</div>
                    <div class="description">${t.description}</div>
                    <div class="meta">${metaBadges}</div>
                    <div class="actions">
                        <button class="btn btn-outline preview-btn">Preview</button>
                        <button class="btn btn-primary use-btn">Use Template</button>
                    </div>
                </div>`;
            }).join('');

            // Wire up buttons via event delegation on the grid
            grid.querySelectorAll('.preview-btn').forEach(btn => {
                const slug = btn.closest('.template-card').dataset.slug;
                btn.addEventListener('click', () => previewTemplate(slug));
            });
            grid.querySelectorAll('.use-btn').forEach(btn => {
                const slug = btn.closest('.template-card').dataset.slug;
                btn.addEventListener('click', () => cloneTemplate(slug));
            });

            // Wire up close button (in case modal is still open from previous state)
            const initialCloseBtn = document.querySelector('#modalContent .close-btn');
            if (initialCloseBtn) {
                initialCloseBtn.addEventListener('click', closeModal);
            }
        }

        async function previewTemplate(slug) {
            const modal = document.getElementById('previewModal');
            const content = document.getElementById('modalContent');

            content.innerHTML = '<button class="close-btn" data-onclick="closeModal()" style="position:absolute;top:16px;right:16px;background:none;border:none;font-size:22px;cursor:pointer;color:#888;">&times;</button><div class="loading"><div class="spinner"></div></div>';
            modal.classList.add('active');

            try {
                const resp = await fetch(`/api/v2/templates/${slug}`);
                const data = await resp.json();

                // Group by steps
                const steps = {};
                data.field_config.forEach(f => {
                    const step = f.step || 1;
                    if (!steps[step]) steps[step] = [];
                    steps[step].push(f);
                });

                let stepsHtml = '';
                if (Object.keys(steps).length > 1) {
                    let groupsHtml = '';
                    Object.keys(steps).sort((a,b) => a-b).forEach(stepNum => {
                        const stepTitle = steps[stepNum][0].step_label || `Step ${stepNum}`;
                        const fieldNames = steps[stepNum].map(f => f.label).join(', ');
                        groupsHtml += `<div class="step-group"><div class="step-title">${stepTitle}</div><div class="step-fields">${fieldNames}</div></div>`;
                    });
                    stepsHtml = `<div class="steps-section"><h4>Multi-Step Form</h4>${groupsHtml}</div>`;
                }

                let fieldsHtml = data.field_config.map(f => {
                    let badges = '';
                    if (f.required) badges += '<span class="field-badge required">Required</span>';
                    if (f.condition) badges += '<span class="field-badge conditional">Conditional</span>';
                    return `
                        <div class="field-item">
                            <span class="field-label">${f.label}</span>
                            <span class="field-meta">
                                ${f.type}${badges}
                                ${f.options ? `<span class="field-badge">${f.options.length} options</span>` : ''}
                            </span>
                        </div>`;
                }).join('');

                content.innerHTML = `
                    <button class="close-btn" data-onclick="closeModal()" style="position:absolute;top:16px;right:16px;background:none;border:none;font-size:22px;cursor:pointer;color:#888;">&times;</button>
                    <h2>${data.icon || '📋'} ${data.name}</h2>
                    <div class="description">${data.description}</div>
                    <div class="meta" style="margin-bottom:16px;">
                        <span class="badge" style="padding:2px 10px;background:#f0f4ff;color:#1a5276;border-radius:12px;font-size:11px;font-weight:600;">${data.category}</span>
                        <span class="badge" style="padding:2px 8px;background:#f5f5f5;border-radius:12px;font-size:11px;">${data.field_config.length} fields</span>
                    </div>
                    ${stepsHtml}
                    <h4 style="font-size:14px;margin-bottom:8px;">Fields</h4>
                    <div class="field-list">${fieldsHtml}</div>
                    ${data.success_message ? `<p style="font-size:13px;color:#888;font-style:italic;margin-bottom:16px;">Confirmation: "${data.success_message}"</p>` : ''}
                    <div class="actions">
                        <button class="btn btn-outline modal-close-btn">Close</button>
                        <button class="btn btn-primary modal-use-btn">Use Template</button>
                    </div>
                `;

                // Wire up modal buttons
                content.querySelector('.modal-close-btn').addEventListener('click', closeModal);
                content.querySelector('.close-btn').addEventListener('click', closeModal);
                content.querySelector('.modal-use-btn').addEventListener('click', () => {
                    cloneTemplate(data.slug);
                    closeModal();
                });
            } catch (err) {
                content.innerHTML = '<p>Failed to load template details.</p>';
            }
        }

        function closeModal() {
            document.getElementById('previewModal').classList.remove('active');
        }

        async function cloneTemplate(slug) {
            try {
                const resp = await fetch(`/api/v2/templates/${slug}/clone`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({}),
                });

                if (resp.status === 403) {
                    showToast('Site limit reached. Upgrade to create more forms.', true);
                    return;
                }

                const data = await resp.json();
                if (data.status === 'created') {
                    showToast(`Form "${data.site.name}" created! Redirecting...`);
                    setTimeout(() => {
                        window.location.href = '/sites';
                    }, 1200);
                }
            } catch (err) {
                showToast('Failed to create form. Please try again.', true);
            }
        }

        function showToast(message, isError = false) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = 'toast' + (isError ? ' error' : '');
            toast.classList.add('show');
            setTimeout(() => toast.classList.remove('show'), 3000);
        }

        // "All Templates" button
        document.querySelector('[data-category="all"]').addEventListener('click', () => {
            currentCategory = 'all';
            document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
            document.querySelector('[data-category="all"]').classList.add('active');
            fetchTemplates();
        });

        // Search
        let searchTimeout;
        document.getElementById('searchBox').addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchQuery = e.target.value.trim();
            searchTimeout = setTimeout(fetchTemplates, 300);
        });

        // Modal close on overlay click
        document.getElementById('previewModal').addEventListener('click', (e) => {
            if (e.target === e.currentTarget) closeModal();
        });

        // Initial load
        fetchTemplates();
    </script>
{% endblock %}
