/**
 * Mail templates admin panel (F5 UI-104).
 */
(function () {
    'use strict';

    const API = '/api/v1/admin/mail/templates';
    const NAME_RE = /^[a-z][a-z0-9_.]{2,127}$/;
    let templates = [];
    let currentName = null;

    function canManageMailTemplates() {
        return window.__CAN_MANAGE_MAIL_TEMPLATES__ !== false;
    }

    function applyReadOnlyMode() {
        if (canManageMailTemplates()) {
            return;
        }
        const banner = document.getElementById('mailTplReadOnlyBanner');
        if (banner) {
            banner.classList.remove('d-none');
        }
        [
            'mailTplSubject', 'mailTplBodyText', 'mailTplBodyHtml', 'mailTplDescription',
        ].forEach(function (id) {
            const el = document.getElementById(id);
            if (el) {
                el.readOnly = true;
            }
        });
        const useLayout = document.getElementById('mailTplUseLayout');
        if (useLayout) {
            useLayout.disabled = true;
        }
        ['mailTplSaveBtn', 'mailTplCreateBtn', 'mailTplAddVarBtn'].forEach(function (id) {
            const btn = document.getElementById(id);
            if (btn) {
                btn.disabled = true;
            }
        });
        document.querySelectorAll('.mail-tpl-del').forEach(function (btn) {
            btn.disabled = true;
        });
        document.querySelectorAll('.mail-tpl-var-del').forEach(function (btn) {
            btn.disabled = true;
        });
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text == null ? '' : String(text);
        return div.innerHTML;
    }

    function setStatus(msg, isError) {
        const el = document.getElementById('mailTplStatus');
        if (el) {
            el.className = 'ms-2 text-' + (isError ? 'danger' : 'success');
            el.textContent = msg;
        }
    }

    function validateTemplateName(name) {
        if (!name || !NAME_RE.test(name)) {
            return 'Имя: строчные латиница/цифры/._ , от 3 до 128 символов (например custom.welcome)';
        }
        if (name.indexOf('system.') === 0) {
            return 'Имя не может начинаться с system.';
        }
        return null;
    }

    function collectVariablesSchema(containerId) {
        const tbody = document.querySelector('#' + containerId + ' tbody');
        if (!tbody) {
            return [];
        }
        const rows = [];
        tbody.querySelectorAll('tr').forEach(function (tr) {
            const nameEl = tr.querySelector('.mail-tpl-var-name');
            const reqEl = tr.querySelector('.mail-tpl-var-required');
            const descEl = tr.querySelector('.mail-tpl-var-desc');
            if (!nameEl) {
                return;
            }
            const varName = nameEl.value.trim();
            if (!varName) {
                return;
            }
            const item = { name: varName, required: !!(reqEl && reqEl.checked) };
            const desc = descEl ? descEl.value.trim() : '';
            if (desc) {
                item.description = desc;
            }
            rows.push(item);
        });
        return rows;
    }

    function renderVariablesSchemaRows(schema, containerId) {
        const tbody = document.querySelector('#' + containerId + ' tbody');
        if (!tbody) {
            return;
        }
        const items = Array.isArray(schema) ? schema : [];
        if (!items.length) {
            tbody.innerHTML = '';
            return;
        }
        tbody.innerHTML = items.map(function (v) {
            return (
                '<tr>' +
                '<td><input type="text" class="form-control form-control-sm mail-tpl-var-name" value="' +
                escapeHtml(v.name || '') + '" placeholder="confirm_url"></td>' +
                '<td class="text-center"><input type="checkbox" class="form-check-input mail-tpl-var-required"' +
                (v.required ? ' checked' : '') + '></td>' +
                '<td><input type="text" class="form-control form-control-sm mail-tpl-var-desc" value="' +
                escapeHtml(v.description || '') + '" placeholder="описание"></td>' +
                '<td><button type="button" class="btn btn-sm btn-outline-danger mail-tpl-var-del">&times;</button></td>' +
                '</tr>'
            );
        }).join('');
        bindVariableRowActions(containerId);
    }

    function bindVariableRowActions(containerId) {
        const root = document.getElementById(containerId);
        if (!root) {
            return;
        }
        root.querySelectorAll('.mail-tpl-var-del').forEach(function (btn) {
            btn.addEventListener('click', function () {
                const tr = btn.closest('tr');
                if (tr) {
                    tr.remove();
                }
            });
        });
    }

    function addVariableRow(containerId) {
        const tbody = document.querySelector('#' + containerId + ' tbody');
        if (!tbody) {
            return;
        }
        const tr = document.createElement('tr');
        tr.innerHTML =
            '<td><input type="text" class="form-control form-control-sm mail-tpl-var-name" placeholder="confirm_url"></td>' +
            '<td class="text-center"><input type="checkbox" class="form-check-input mail-tpl-var-required"></td>' +
            '<td><input type="text" class="form-control form-control-sm mail-tpl-var-desc" placeholder="описание"></td>' +
            '<td><button type="button" class="btn btn-sm btn-outline-danger mail-tpl-var-del">&times;</button></td>';
        tbody.appendChild(tr);
        bindVariableRowActions(containerId);
    }

    function buildSampleVariables(schema) {
        const vars = {};
        (schema || []).forEach(function (v) {
            if (!v || !v.name) {
                return;
            }
            if (v.name === 'confirm_url') {
                vars[v.name] = 'https://example.com/confirm?token=sample';
            } else if (v.name.indexOf('url') >= 0 || v.name.indexOf('_link') >= 0) {
                vars[v.name] = 'https://example.com/sample';
            } else if (v.name.indexOf('email') >= 0) {
                vars[v.name] = 'user@example.com';
            } else if (v.name.indexOf('hours') >= 0 || v.name.indexOf('count') >= 0) {
                vars[v.name] = '24';
            } else {
                vars[v.name] = '{{' + v.name + '}}';
            }
        });
        return vars;
    }

    function getEditorSampleVariables() {
        return buildSampleVariables(collectVariablesSchema('mailTplVarTable'));
    }

    async function loadTemplates(filter) {
        const tbody = document.getElementById('mailTplTableBody');
        if (!tbody) return;
        tbody.innerHTML = '<tr><td colspan="4">Загрузка...</td></tr>';
        const qs = filter && filter !== 'all' ? '?type=' + encodeURIComponent(filter) : '';
        const resp = await fetch(API + qs);
        const data = await resp.json();
        if (!data.success) {
            tbody.innerHTML = '<tr><td colspan="4" class="text-danger">' + escapeHtml(data.error) + '</td></tr>';
            return;
        }
        templates = data.templates || [];
        if (!templates.length) {
            tbody.innerHTML = '<tr><td colspan="4" class="text-muted">Нет шаблонов</td></tr>';
            return;
        }
        tbody.innerHTML = templates.map(function (t) {
            const badge = t.is_system
                ? '<span class="badge bg-secondary">системный</span>'
                : '<span class="badge bg-info">пользовательский</span>';
            return (
                '<tr>' +
                '<td><code>' + escapeHtml(t.name) + '</code></td>' +
                '<td>' + escapeHtml(t.subject_template || '') + '</td>' +
                '<td>' + badge + '</td>' +
                '<td>' +
                '<button class="btn btn-sm btn-outline-primary mail-tpl-edit" data-name="' + escapeHtml(t.name) + '">Редактировать</button> ' +
                (!t.is_system && canManageMailTemplates()
                    ? '<button class="btn btn-sm btn-outline-danger mail-tpl-del" data-name="' + escapeHtml(t.name) + '">Удалить</button>'
                    : '') +
                '</td></tr>'
            );
        }).join('');
        tbody.querySelectorAll('.mail-tpl-edit').forEach(function (btn) {
            btn.addEventListener('click', function () { openEditor(btn.getAttribute('data-name')); });
        });
        tbody.querySelectorAll('.mail-tpl-del').forEach(function (btn) {
            btn.addEventListener('click', function () { deleteTemplate(btn.getAttribute('data-name')); });
        });
        applyReadOnlyMode();
    }

    function fillEditorFields(t) {
        document.getElementById('mailTplEditorName').textContent = t.name;
        document.getElementById('mailTplSubject').value = t.subject_template || '';
        document.getElementById('mailTplBodyText').value = t.body_text || '';
        document.getElementById('mailTplBodyHtml').value = t.body_html || '';
        document.getElementById('mailTplDescription').value = t.description || '';
        document.getElementById('mailTplUseLayout').checked = t.use_layout !== false;
        document.getElementById('mailTplIsSystem').textContent = t.is_system ? '(системный)' : '(пользовательский)';
        renderVariablesSchemaRows(t.variables_schema || [], 'mailTplVarTable');
    }

    async function openEditor(name) {
        currentName = name;
        const resp = await fetch(API + '/' + encodeURIComponent(name));
        const data = await resp.json();
        if (!data.success) {
            setStatus(data.error || 'Ошибка загрузки', true);
            return;
        }
        document.getElementById('mailTplEditor').style.display = 'block';
        fillEditorFields(data.template);
        applyReadOnlyMode();
    }

    function openCreateModal() {
        if (!canManageMailTemplates()) {
            setStatus('Недостаточно прав на управление шаблонами', true);
            return;
        }
        document.getElementById('mailTplCreateName').value = '';
        document.getElementById('mailTplCreateDescription').value = '';
        document.getElementById('mailTplCreateSubject').value = '';
        document.getElementById('mailTplCreateBodyText').value = '';
        document.getElementById('mailTplCreateBodyHtml').value = '';
        document.getElementById('mailTplCreateUseLayout').checked = true;
        renderVariablesSchemaRows([], 'mailTplCreateVarTable');
        new bootstrap.Modal(document.getElementById('mailTplCreateModal')).show();
    }

    async function createTemplate() {
        if (!canManageMailTemplates()) {
            setStatus('Недостаточно прав на управление шаблонами', true);
            return;
        }
        const name = document.getElementById('mailTplCreateName').value.trim();
        const nameErr = validateTemplateName(name);
        if (nameErr) {
            setStatus(nameErr, true);
            return;
        }
        const subject = document.getElementById('mailTplCreateSubject').value.trim();
        if (!subject) {
            setStatus('Укажите тему письма', true);
            return;
        }
        const body = {
            name: name,
            description: document.getElementById('mailTplCreateDescription').value.trim() || null,
            subject_template: subject,
            body_text: document.getElementById('mailTplCreateBodyText').value,
            body_html: document.getElementById('mailTplCreateBodyHtml').value,
            use_layout: document.getElementById('mailTplCreateUseLayout').checked,
            variables_schema: collectVariablesSchema('mailTplCreateVarTable'),
        };
        const resp = await cascad360Fetch(API, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        });
        const data = await resp.json();
        if (!data.success) {
            setStatus(data.error || 'Ошибка создания', true);
            return;
        }
        bootstrap.Modal.getInstance(document.getElementById('mailTplCreateModal')).hide();
        setStatus('Шаблон создан: ' + name, false);
        await loadTemplates(document.getElementById('mailTplFilter').value);
        await openEditor(name);
    }

    async function saveTemplate() {
        if (!canManageMailTemplates()) {
            setStatus('Недостаточно прав на управление шаблонами', true);
            return;
        }
        if (!currentName) return;
        const body = {
            subject_template: document.getElementById('mailTplSubject').value,
            body_text: document.getElementById('mailTplBodyText').value,
            body_html: document.getElementById('mailTplBodyHtml').value,
            description: document.getElementById('mailTplDescription').value.trim() || null,
            use_layout: document.getElementById('mailTplUseLayout').checked,
            variables_schema: collectVariablesSchema('mailTplVarTable'),
        };
        const resp = await cascad360Fetch(API + '/' + encodeURIComponent(currentName), {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        });
        const data = await resp.json();
        if (!data.success) {
            setStatus(data.error || 'Ошибка сохранения', true);
            return;
        }
        setStatus('Шаблон сохранён', false);
        loadTemplates(document.getElementById('mailTplFilter').value);
    }

    async function previewTemplate() {
        if (!currentName) return;
        const variables = getEditorSampleVariables();
        const resp = await cascad360Fetch(API + '/' + encodeURIComponent(currentName) + '/preview', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ variables: variables }),
        });
        const data = await resp.json();
        if (!data.success) {
            setStatus(data.error || data.message || 'Ошибка предпросмотра', true);
            return;
        }
        const iframe = document.getElementById('mailTplPreviewFrame');
        iframe.srcdoc = data.body_html || ('<pre>' + escapeHtml(data.body_text || '') + '</pre>');
        new bootstrap.Modal(document.getElementById('mailTplPreviewModal')).show();
    }

    async function testSendTemplate() {
        if (!currentName) return;
        const to = document.getElementById('mailTplTestEmail').value.trim();
        if (!to) {
            setStatus('Укажите email', true);
            return;
        }
        const variables = getEditorSampleVariables();
        const resp = await cascad360Fetch(API + '/' + encodeURIComponent(currentName) + '/test-send', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ to: to, variables: variables }),
        });
        const data = await resp.json();
        setStatus(data.success ? ('Отправлено: ' + (data.job_id || '')) : (data.error || 'Ошибка отправки'), !data.success);
        bootstrap.Modal.getInstance(document.getElementById('mailTplTestModal')).hide();
    }

    async function deleteTemplate(name) {
        if (!canManageMailTemplates()) {
            setStatus('Недостаточно прав на управление шаблонами', true);
            return;
        }
        if (!confirm('Удалить шаблон ' + name + '?')) return;
        const resp = await cascad360Fetch(API + '/' + encodeURIComponent(name), { method: 'DELETE' });
        const data = await resp.json();
        if (!data.success) {
            setStatus(data.error || 'Удаление запрещено', true);
            return;
        }
        if (currentName === name) {
            document.getElementById('mailTplEditor').style.display = 'none';
            currentName = null;
        }
        loadTemplates(document.getElementById('mailTplFilter').value);
    }

    function variablesTableHtml(tableId, addBtnId) {
        return (
            '<div class="mb-2">' +
            '<label class="form-label d-flex justify-content-between align-items-center">' +
            '<span>Переменные шаблона</span>' +
            '<button type="button" class="btn btn-sm btn-outline-secondary" id="' + addBtnId + '">+ переменная</button>' +
            '</label>' +
            '<div id="' + tableId + '" class="table-responsive">' +
            '<table class="table table-sm table-bordered mb-0">' +
            '<thead><tr><th>Имя</th><th style="width:70px">Обяз.</th><th>Описание</th><th style="width:40px"></th></tr></thead>' +
            '<tbody></tbody></table></div></div>'
        );
    }

    window.MailTemplatesPanel = {
        mount: function (container) {
            if (!container) return;
            container.innerHTML =
                '<div id="mailTplReadOnlyBanner" class="alert alert-secondary d-none mb-3">' +
                'Только просмотр: нет права на управление шаблонами.</div>' +
                '<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">' +
                '<div class="d-flex align-items-center gap-2">' +
                '<select id="mailTplFilter" class="form-select form-select-sm w-auto">' +
                '<option value="all">Все</option><option value="system">Системные</option><option value="custom">Пользовательские</option>' +
                '</select>' +
                (canManageMailTemplates()
                    ? '<button type="button" class="btn btn-sm btn-success" id="mailTplCreateBtn">Создать шаблон</button>'
                    : '') +
                '</div>' +
                '<span id="mailTplStatus" class="text-muted"></span></div>' +
                '<table class="table table-sm table-hover"><thead><tr><th>Имя</th><th>Тема</th><th>Тип</th><th></th></tr></thead>' +
                '<tbody id="mailTplTableBody"></tbody></table>' +
                '<div id="mailTplEditor" style="display:none" class="card mt-3">' +
                '<div class="card-header">Редактор: <code id="mailTplEditorName"></code> <span id="mailTplIsSystem" class="text-muted"></span></div>' +
                '<div class="card-body">' +
                '<div class="row">' +
                '<div class="col-lg-8">' +
                '<div class="mb-2"><label class="form-label">Описание</label>' +
                '<textarea class="form-control" id="mailTplDescription" rows="2"></textarea></div>' +
                '<div class="mb-2"><label class="form-label">Тема письма</label>' +
                '<input type="text" class="form-control" id="mailTplSubject"></div>' +
                '<div class="mb-2"><label class="form-label">Текст (plain)</label>' +
                '<textarea class="form-control font-monospace" id="mailTplBodyText" rows="4"></textarea></div>' +
                '<div class="mb-2"><label class="form-label">HTML-фрагмент</label>' +
                '<textarea class="form-control font-monospace" id="mailTplBodyHtml" rows="8"></textarea></div>' +
                '<div class="form-check mb-3">' +
                '<input class="form-check-input" type="checkbox" id="mailTplUseLayout" checked>' +
                '<label class="form-check-label" for="mailTplUseLayout">Оборачивать в общий layout</label></div>' +
                '</div>' +
                '<div class="col-lg-4">' +
                variablesTableHtml('mailTplVarTable', 'mailTplAddVarBtn') +
                '</div></div>' +
                '<button type="button" class="btn btn-primary btn-sm" id="mailTplSaveBtn">Сохранить</button> ' +
                '<button type="button" class="btn btn-outline-secondary btn-sm" id="mailTplPreviewBtn">Предпросмотр</button> ' +
                '<button type="button" class="btn btn-outline-info btn-sm" id="mailTplTestBtn">Тестовая отправка</button>' +
                '</div></div>' +
                '<div class="modal fade" id="mailTplCreateModal" tabindex="-1">' +
                '<div class="modal-dialog modal-lg"><div class="modal-content">' +
                '<div class="modal-header"><h5 class="modal-title">Создать шаблон</h5>' +
                '<button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>' +
                '<div class="modal-body">' +
                '<div class="mb-2"><label class="form-label">Имя <span class="text-muted">(например custom.welcome)</span></label>' +
                '<input type="text" class="form-control font-monospace" id="mailTplCreateName" placeholder="custom.welcome"></div>' +
                '<div class="mb-2"><label class="form-label">Описание</label>' +
                '<textarea class="form-control" id="mailTplCreateDescription" rows="2"></textarea></div>' +
                '<div class="mb-2"><label class="form-label">Тема письма</label>' +
                '<input type="text" class="form-control" id="mailTplCreateSubject"></div>' +
                '<div class="mb-2"><label class="form-label">Текст (plain)</label>' +
                '<textarea class="form-control font-monospace" id="mailTplCreateBodyText" rows="3"></textarea></div>' +
                '<div class="mb-2"><label class="form-label">HTML-фрагмент</label>' +
                '<textarea class="form-control font-monospace" id="mailTplCreateBodyHtml" rows="5"></textarea></div>' +
                '<div class="form-check mb-3">' +
                '<input class="form-check-input" type="checkbox" id="mailTplCreateUseLayout" checked>' +
                '<label class="form-check-label" for="mailTplCreateUseLayout">Оборачивать в общий layout</label></div>' +
                variablesTableHtml('mailTplCreateVarTable', 'mailTplCreateAddVarBtn') +
                '</div>' +
                '<div class="modal-footer">' +
                '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>' +
                '<button type="button" class="btn btn-primary" id="mailTplCreateConfirmBtn">Создать</button>' +
                '</div></div></div></div>' +
                '<div class="modal fade" id="mailTplPreviewModal" tabindex="-1">' +
                '<div class="modal-dialog modal-lg"><div class="modal-content">' +
                '<div class="modal-header"><h5 class="modal-title">Предпросмотр</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>' +
                '<div class="modal-body"><iframe id="mailTplPreviewFrame" sandbox="" style="width:100%;min-height:320px;border:1px solid #dee2e6"></iframe></div>' +
                '</div></div></div>' +
                '<div class="modal fade" id="mailTplTestModal" tabindex="-1">' +
                '<div class="modal-dialog"><div class="modal-content">' +
                '<div class="modal-header"><h5 class="modal-title">Тестовая отправка</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>' +
                '<div class="modal-body"><input type="email" class="form-control" id="mailTplTestEmail" placeholder="email@example.com"></div>' +
                '<div class="modal-footer"><button type="button" class="btn btn-primary" id="mailTplTestConfirmBtn">Отправить</button></div>' +
                '</div></div></div>';

            document.getElementById('mailTplFilter').addEventListener('change', function (e) {
                loadTemplates(e.target.value);
            });
            const createBtn = document.getElementById('mailTplCreateBtn');
            if (createBtn) {
                createBtn.addEventListener('click', openCreateModal);
            }
            document.getElementById('mailTplCreateConfirmBtn').addEventListener('click', createTemplate);
            document.getElementById('mailTplAddVarBtn').addEventListener('click', function () {
                addVariableRow('mailTplVarTable');
            });
            document.getElementById('mailTplCreateAddVarBtn').addEventListener('click', function () {
                addVariableRow('mailTplCreateVarTable');
            });
            document.getElementById('mailTplSaveBtn').addEventListener('click', saveTemplate);
            document.getElementById('mailTplPreviewBtn').addEventListener('click', previewTemplate);
            document.getElementById('mailTplTestBtn').addEventListener('click', function () {
                new bootstrap.Modal(document.getElementById('mailTplTestModal')).show();
            });
            document.getElementById('mailTplTestConfirmBtn').addEventListener('click', testSendTemplate);
            if (!canManageMailTemplates()) {
                document.getElementById('mailTplReadOnlyBanner').classList.remove('d-none');
            }
            loadTemplates('all');
        },
    };
})();
