// Template management modal logic for admin_templates.html
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);});
})();
