<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Template Management — Admin</title>
    <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; padding: 20px; }
        h1 { font-size: 20px; margin-bottom: 16px; }
        .card { background: white; border-radius: 8px; padding: 24px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        .btn { display: inline-block; padding: 6px 14px; background: #1a1a2e; color: white; text-decoration: none; border-radius: 4px; border: none; cursor: pointer; font-size: 13px; }
        .btn-sm { padding: 4px 10px; font-size: 12px; }
        .btn-danger { background: #c0392b; }
        .btn-outline { background: transparent; border: 1px solid #1a1a2e; color: #1a1a2e; }
        .btn:hover { opacity: 0.9; }
        table { width: 100%; border-collapse: collapse; font-size: 13px; }
        th { text-align: left; padding: 8px; border-bottom: 2px solid #ddd; font-weight: 600; }
        td { padding: 8px; border-bottom: 1px solid #eee; vertical-align: top; }
        .badge { display: inline-block; padding: 2px 8px; border-radius: 12px; font-size: 11px; font-weight: 600; }
        .badge-featured { background: #fff3cd; color: #856404; }
        .badge-cat { background: #e8f5e9; color: #2e7d32; }
        .actions { display: flex; gap: 4px; }
        .flash { padding: 10px 14px; border-radius: 4px; margin-bottom: 16px; font-size: 13px; }
        .flash-success { background: #d4edda; color: #155724; }
        .flash-error { background: #f8d7da; color: #721c24; }
        .modal { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: none; align-items: center; justify-content: center; z-index: 100; }
        .modal.active { display: flex; }
        .modal-content { background: white; border-radius: 8px; padding: 24px; width: 500px; max-width: 90vw; max-height: 80vh; overflow-y: auto; }
        .modal-content h2 { font-size: 16px; margin-bottom: 16px; }
        .form-group { margin-bottom: 12px; }
        .form-group label { display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px; }
        .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 13px; }
        .form-group textarea { font-family: monospace; font-size: 12px; min-height: 120px; }
        .modal-actions { display: flex; gap: 8px; margin-top: 16px; }
    </style>
</head>
<body>
    <h1>Template Management <span style="font-weight:400; color:#888;">({{ templates|length }} templates)</span></h1>
    {% with messages = get_flashed_messages(with_categories=true) %}
        {% for cat, msg in messages %}
            <div class="flash flash-{{ cat }}">{{ msg }}</div>
        {% endfor %}
    {% endwith %}

    <div class="card">
        <div style="margin-bottom:12px;">
            <button class="btn" data-onclick="showCreateModal()">+ New Template</button>
        </div>
        <table>
            <thead>
                <tr>
                    <th>Slug</th>
                    <th>Name</th>
                    <th>Category</th>
                    <th>Fields</th>
                    <th>Featured</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                {% for t in templates %}
                <tr>
                    <td><code style="font-size:12px;">{{ t.slug }}</code></td>
                    <td>{{ t.name }}</td>
                    <td><span class="badge badge-cat">{{ t.category }}</span></td>
                    <td>{{ t.field_count }}</td>
                    <td>{% if t.is_featured %}<span class="badge badge-featured">★ Featured</span>{% else %}—{% endif %}</td>
                    <td class="actions">
                        <button class="btn btn-sm btn-outline" onclick='showEditModal({{ t|tojson }})'>Edit</button>
                        <button class="btn btn-sm btn-danger" data-onclick="deleteTemplate('{{ t.slug }}')">Delete</button>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- Create/Edit Modal -->
    <div class="modal" id="templateModal">
        <div class="modal-content">
            <h2 id="modalTitle">New Template</h2>
            <div class="form-group">
                <label>Slug</label>
                <input type="text" id="tmplSlug" placeholder="e.g. contact-us">
            </div>
            <div class="form-group">
                <label>Name</label>
                <input type="text" id="tmplName" placeholder="e.g. Contact Us">
            </div>
            <div class="form-group">
                <label>Description</label>
                <input type="text" id="tmplDesc" placeholder="Brief description">
            </div>
            <div class="form-group">
                <label>Category</label>
                <select id="tmplCategory">
                    <option>Business</option>
                    <option>Events</option>
                    <option>Hiring</option>
                    <option>Support</option>
                    <option>E-commerce</option>
                    <option>Onboarding</option>
                </select>
            </div>
            <div class="form-group">
                <label>Success Message</label>
                <input type="text" id="tmplSuccessMsg" placeholder="Thank you for your submission!">
            </div>
            <div class="form-group">
                <label>Featured</label>
                <select id="tmplFeatured">
                    <option value="0">No</option>
                    <option value="1">Yes</option>
                </select>
            </div>
            <div class="form-group">
                <label>Field Config (JSON)</label>
                <textarea id="tmplFieldConfig" placeholder='[{"name":"email","label":"Email","type":"email","required":true}]'></textarea>
            </div>
            <div class="modal-actions">
                <button class="btn" data-onclick="saveTemplate()">Save</button>
                <button class="btn btn-outline" data-onclick="closeModal()">Cancel</button>
            </div>
        </div>
    </div>

    <script nonce="{{ csp_nonce }}">
        var editSlug = null;

        function showCreateModal() {
            editSlug = null;
            document.getElementById('modalTitle').textContent = 'New Template';
            document.getElementById('tmplSlug').value = '';
            document.getElementById('tmplSlug').disabled = false;
            document.getElementById('tmplName').value = '';
            document.getElementById('tmplDesc').value = '';
            document.getElementById('tmplCategory').value = 'Business';
            document.getElementById('tmplSuccessMsg').value = '';
            document.getElementById('tmplFeatured').value = '0';
            document.getElementById('tmplFieldConfig').value = '[]';
            document.getElementById('templateModal').classList.add('active');
        }

        function showEditModal(tpl) {
            editSlug = tpl.slug;
            document.getElementById('modalTitle').textContent = 'Edit Template';
            document.getElementById('tmplSlug').value = tpl.slug;
            document.getElementById('tmplSlug').disabled = true;
            document.getElementById('tmplName').value = tpl.name;
            document.getElementById('tmplDesc').value = tpl.description;
            document.getElementById('tmplCategory').value = tpl.category;
            document.getElementById('tmplSuccessMsg').value = tpl.success_message || '';
            document.getElementById('tmplFeatured').value = tpl.is_featured ? '1' : '0';
            try {
                var fc = JSON.parse(tpl.field_config);
                document.getElementById('tmplFieldConfig').value = JSON.stringify(fc, null, 2);
            } catch(e) {
                document.getElementById('tmplFieldConfig').value = tpl.field_config || '[]';
            }
            document.getElementById('templateModal').classList.add('active');
        }

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

        async function saveTemplate() {
            var slug = document.getElementById('tmplSlug').value.trim();
            var name = document.getElementById('tmplName').value.trim();
            if (!slug || !name) { alert('Slug and Name are required'); return; }

            var fieldConfig;
            try {
                fieldConfig = JSON.parse(document.getElementById('tmplFieldConfig').value);
            } catch(e) {
                alert('Invalid JSON in Field Config: ' + e.message);
                return;
            }

            var data = {
                slug: slug,
                name: name,
                description: document.getElementById('tmplDesc').value.trim(),
                category: document.getElementById('tmplCategory').value,
                success_message: document.getElementById('tmplSuccessMsg').value.trim() || null,
                is_featured: parseInt(document.getElementById('tmplFeatured').value),
                field_config: fieldConfig,
                created_by: 'admin'
            };

            var method = 'POST';
            var url = '/api/admin/templates';
            if (editSlug) {
                method = 'PUT';
                url = '/api/admin/templates/' + editSlug;
                delete data.slug;
            }

            try {
                var resp = await fetch(url, {
                    method: method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
                if (resp.ok) {
                    location.reload();
                } else {
                    var err = await resp.json();
                    alert('Error: ' + (err.error || 'Unknown error'));
                }
            } catch(e) {
                alert('Request failed: ' + e.message);
            }
        }

        async function deleteTemplate(slug) {
            if (!confirm('Delete template "' + slug + '"? This cannot be undone.')) return;
            try {
                var resp = await fetch('/api/admin/templates/' + slug, { method: 'DELETE' });
                if (resp.ok) {
                    location.reload();
                } else {
                    var err = await resp.json();
                    alert('Error: ' + (err.error || 'Unknown error'));
                }
            } catch(e) {
                alert('Request failed: ' + e.message);
            }
        }

        // Close modal on backdrop click
        document.getElementById('templateModal').addEventListener('click', function(e) {
            if (e.target === this) closeModal();
        });
    });
    // CSP-safe event delegation
    (function(){
        var H={'data-onclick':'click','data-onsubmit':'submit','data-onchange':'change','data-oninput':'input','data-onkeyup':'keyup','data-onkeydown':'keydown','data-onkeypress':'keypress','data-onfocus':'focusin','data-onblur':'focusout'};
        function _resolveFn(n,c){var p=n.split('.'),o=c||window;for(var i=0;i<p.length;i++){if(typeof o[p[i]]!=='function')return null;o=o[p[i]];}return o;}
        function _parseCall(c){var s=c.trim();if(s.startsWith('return '))s=s.slice(7).trim();var m=s.match(/^([\w.$]+)\((.*)\)$/);if(m)return{fn:m[1],argsStr:m[2]};if(/^[\w.$]+$/.test(s))return{fn:s,argsStr:''};return null;}
        function _splitArgs(s){if(!s.trim())return[];var a=[],c='',d=0,ins=false,ch='';for(var i=0;i<s.length;i++){var x=s[i];if(ins){if(x===ch)ins=false;c+=x;continue;}if(x==='"'||x==="'"){ins=true;ch=x;c+=x;continue;}if(x==='('||x==='['||x==='{')d++;if(x===')'||x===']'||x==='}')d--;if(x===','&&d===0){a.push(c.trim());c='';continue;}c+=x;}if(c.trim())a.push(c.trim());return a;}
        function _invoke(c,e,evt){var p=_parseCall(c);if(!p)return;var fn=_resolveFn(p.fn,e);if(!fn){console.warn('CSP delegate: unknown',p.fn);return;}var args=_splitArgs(p.argsStr).map(function(a){if(a==='this')return e;if(a==='event'||a==='e')return evt;if(a==='this.value')return e.value;if(a==='this.form')return e.form;if(a==='this.checked')return e.checked;return a;});return fn.apply(window,args);}
        for(var attr in H)(function(a,ev){document.addEventListener(ev,function(e){var el=e.target.closest('['+a+']');if(!el)return;var code=el.getAttribute(a);if(!code)return;var r=_invoke(code,el,e);if(r===false){e.preventDefault();e.stopPropagation();}},ev==='focusin'||ev==='focusout');})(attr,H[attr]);
        ['error','load'].forEach(function(ev){document.addEventListener(ev,function(e){var c=e.target.getAttribute('data-'+ev);if(!c)return;_invoke(c,e.target,e);},true);});
    })();
    </script>
</body>
</html>
