/**
 * Секция «Почта» в настройках (FR-M-011, FR-M-006).
 */
(function () {
    const API = '/api/v1/admin/mail';

    function transportBanner(transport) {
        if (transport === 'file' || transport === 'local') {
            return (
                '<div class="alert alert-warning">' +
                '<i class="bi bi-exclamation-triangle"></i> ' +
                'Режим <strong>' + transport + '</strong> только для dev/staging. ' +
                'Не используйте для production-доставки клиентам.' +
                '</div>'
            );
        }
        if (transport === 'postfix') {
            return (
                '<div class="alert alert-info">' +
                '<i class="bi bi-info-circle"></i> ' +
                'Postfix: письма передаются локальному MTA по SMTP (обычно <code>127.0.0.1:25</code>).' +
                '</div>'
            );
        }
        if (transport === 'sendmail') {
            return (
                '<div class="alert alert-info">' +
                '<i class="bi bi-info-circle"></i> ' +
                'Sendmail: письма передаются через pipe в бинарник MTA (классический Unix-режим).' +
                '</div>'
            );
        }
        return '';
    }

    function toggleTransportBlocks() {
        const transport = document.getElementById('mailTransport').value;
        const blocks = ['mailSmtpBlock', 'mailPostfixBlock', 'mailSendmailBlock', 'mailLocalBlock', 'mailFileBlock'];
        blocks.forEach(function (id) {
            const el = document.getElementById(id);
            if (el) el.style.display = 'none';
        });
        if (transport === 'smtp') {
            document.getElementById('mailSmtpBlock').style.display = 'block';
        } else if (transport === 'postfix') {
            document.getElementById('mailPostfixBlock').style.display = 'block';
        } else if (transport === 'sendmail') {
            document.getElementById('mailSendmailBlock').style.display = 'block';
        } else if (transport === 'local') {
            document.getElementById('mailLocalBlock').style.display = 'block';
        } else if (transport === 'file') {
            document.getElementById('mailFileBlock').style.display = 'block';
        }
        const banner = document.getElementById('mailTransportBanner');
        if (banner) {
            banner.innerHTML = transportBanner(transport);
        }
    }

    async function loadHealthMetrics() {
        const el = document.getElementById('mailMetricsPanel');
        if (!el) return;
        try {
            const resp = await fetch(API + '/health');
            const data = await resp.json();
            if (!data.success) {
                el.textContent = 'Метрики недоступны';
                return;
            }
            const m = data.metrics || {};
            el.innerHTML =
                '<span class="badge bg-secondary me-1">в очереди: ' + (data.queue_depth || 0) + '</span>' +
                '<span class="badge bg-primary me-1">поставлено: ' + (m.enqueued_total || 0) + '</span>' +
                '<span class="badge bg-success me-1">отправлено: ' + (m.sent_total || 0) + '</span>' +
                '<span class="badge bg-warning text-dark me-1">ошибки: ' + (m.failed_total || 0) + '</span>' +
                '<span class="badge bg-danger">мертвые: ' + (m.dead_total || 0) + '</span>';
        } catch (e) {
            el.textContent = 'Ошибка загрузки метрик';
        }
    }

    function outboxStatusLabel(status) {
        const labels = {
            queued: 'В очереди',
            sent: 'Отправлено',
            failed: 'Ошибка',
            dead: 'Мёртвые',
        };
        return labels[status] || status;
    }

    async function loadOutbox(statusFilter) {
        const tbody = document.getElementById('mailOutboxBody');
        if (!tbody) return;
        tbody.innerHTML = '<tr><td colspan="6">Загрузка...</td></tr>';
        const qs = statusFilter ? '?status=' + encodeURIComponent(statusFilter) : '';
        const resp = await fetch(API + '/outbox' + qs);
        const data = await resp.json();
        if (!data.success || !data.items || !data.items.length) {
            tbody.innerHTML = '<tr><td colspan="7" class="text-muted">Нет записей</td></tr>';
            return;
        }
        tbody.innerHTML = data.items.map(function (item) {
            const canRetry = item.status === 'failed' || item.status === 'dead';
            const retryBtn = canRetry
                ? '<button class="btn btn-sm btn-outline-secondary mail-retry-btn" data-id="' + item.id + '">Повторить</button>'
                : '';
            return (
                '<tr>' +
                '<td>' + item.id + '</td>' +
                '<td><span class="badge bg-light text-dark">' + outboxStatusLabel(item.status) + '</span></td>' +
                '<td>' + (item.subject || '') + '</td>' +
                '<td>' + (item.attempts != null ? item.attempts : 0) + '</td>' +
                '<td class="small text-muted">' + (item.last_error || '—') + '</td>' +
                '<td>' + (item.created_at || '') + '</td>' +
                '<td>' + retryBtn + '</td>' +
                '</tr>'
            );
        }).join('');
        tbody.querySelectorAll('.mail-retry-btn').forEach(function (btn) {
            btn.addEventListener('click', async function () {
                const id = btn.getAttribute('data-id');
                const resp = await fetch(API + '/outbox/' + id + '/retry', { method: 'POST' });
                const result = await resp.json();
                document.getElementById('mailSaveStatus').textContent = result.success
                    ? 'Повтор поставлен в очередь'
                    : (result.error || 'Ошибка повтора');
                loadOutbox(document.getElementById('mailOutboxFilter').value);
                loadHealthMetrics();
            });
        });
    }

    async function loadSettings() {
        const resp = await fetch(API + '/settings');
        return resp.json();
    }

    window.MailSettingsPanel = {
        mount: function (container) {
            if (!container) return;
            container.innerHTML =
                '<ul class="nav nav-tabs mb-3" id="mailSettingsTabs">' +
                '<li class="nav-item"><button class="nav-link active" type="button" data-mail-tab="transport">Транспорт</button></li>' +
                '<li class="nav-item"><button class="nav-link" type="button" data-mail-tab="templates">Шаблоны</button></li>' +
                '</ul>' +
                '<div id="mailTabTransport">' +
                '<div id="mailTransportBanner"></div>' +
                '<div class="card mb-3">' +
                '<div class="card-header d-flex justify-content-between align-items-center">' +
                '<h5 class="mb-0">Почтовый сервис</h5>' +
                '<span id="mailMetricsPanel" class="small"></span>' +
                '</div>' +
                '<div class="card-body">' +
                '<div class="mb-3">' +
                '<label class="form-label">Транспорт</label>' +
                '<select id="mailTransport" class="form-select">' +
                '<option value="file">Файл (отладка)</option>' +
                '<option value="local">Локальный (dev relay)</option>' +
                '<option value="postfix">Postfix (локальный MTA)</option>' +
                '<option value="sendmail">Sendmail (pipe)</option>' +
                '<option value="smtp">SMTP (удалённый)</option>' +
                '</select></div>' +
                '<div class="mb-3"><label class="form-label">Email отправителя</label>' +
                '<input type="email" class="form-control" id="mailFromEmail"></div>' +
                '<div class="mb-3"><label class="form-label">Имя отправителя</label>' +
                '<input type="text" class="form-control" id="mailFromName"></div>' +
                '<div class="mb-3"><label class="form-label">Адрес для ответа</label>' +
                '<input type="email" class="form-control" id="mailReplyTo"></div>' +
                '<div id="mailSmtpBlock">' +
                '<div class="mb-3"><label class="form-label">Хост SMTP</label>' +
                '<input type="text" class="form-control" id="mailSmtpHost"></div>' +
                '<div class="mb-3"><label class="form-label">Порт SMTP</label>' +
                '<input type="number" class="form-control" id="mailSmtpPort" value="587"></div>' +
                '<div class="mb-3"><label class="form-label">Имя пользователя SMTP</label>' +
                '<input type="text" class="form-control" id="mailSmtpUsername"></div>' +
                '<div class="mb-3"><label class="form-label">Пароль SMTP</label>' +
                '<input type="password" class="form-control" id="mailSmtpPassword" placeholder="***"></div>' +
                '<div class="mb-3"><label class="form-label">Шифрование</label>' +
                '<select id="mailSmtpEncryption" class="form-select">' +
                '<option value="starttls">STARTTLS</option>' +
                '<option value="ssl">SSL</option>' +
                '<option value="none">Без шифрования</option>' +
                '</select></div></div>' +
                '<div id="mailPostfixBlock" style="display:none">' +
                '<div class="mb-3"><label class="form-label">Хост Postfix</label>' +
                '<input type="text" class="form-control" id="mailPostfixHost" value="127.0.0.1"></div>' +
                '<div class="mb-3"><label class="form-label">Порт Postfix</label>' +
                '<input type="number" class="form-control" id="mailPostfixPort" value="25"></div>' +
                '<div class="mb-3"><label class="form-label">Шифрование</label>' +
                '<select id="mailPostfixEncryption" class="form-select">' +
                '<option value="none">Без шифрования (localhost)</option>' +
                '<option value="starttls">STARTTLS</option>' +
                '<option value="ssl">SSL</option>' +
                '</select></div>' +
                '<div class="mb-3"><label class="form-label">Таймаут (сек)</label>' +
                '<input type="number" class="form-control" id="mailPostfixTimeout" value="30"></div></div>' +
                '<div id="mailSendmailBlock" style="display:none">' +
                '<div class="mb-3"><label class="form-label">Путь к sendmail</label>' +
                '<input type="text" class="form-control" id="mailSendmailPath" value="/usr/sbin/sendmail"></div>' +
                '<div class="mb-3"><label class="form-label">Аргументы</label>' +
                '<input type="text" class="form-control" id="mailSendmailArgs" value="-t -i">' +
                '<div class="form-text">Обычно <code>-t -i</code> для совместимости с Postfix/sendmail.</div></div>' +
                '<div class="mb-3"><label class="form-label">Таймаут (сек)</label>' +
                '<input type="number" class="form-control" id="mailSendmailTimeout" value="30"></div></div>' +
                '<div id="mailLocalBlock" style="display:none">' +
                '<div class="mb-3"><label class="form-label">Каталог local</label>' +
                '<input type="text" class="form-control" id="mailLocalOutputDir" value="var/mail/local"></div></div>' +
                '<div id="mailFileBlock" style="display:none">' +
                '<div class="mb-3"><label class="form-label">Каталог file</label>' +
                '<input type="text" class="form-control" id="mailFileOutputDir" value="var/mail"></div></div>' +
                '<div class="mb-3"><label class="form-label">Тестовый email</label>' +
                '<div class="input-group">' +
                '<input type="email" class="form-control" id="mailTestTo">' +
                '<button class="btn btn-outline-primary" type="button" id="mailTestBtn">Отправить</button>' +
                '</div></div>' +
                '<button class="btn btn-primary" type="button" id="mailSaveBtn">Сохранить</button>' +
                '<span id="mailSaveStatus" class="ms-2 text-muted"></span>' +
                '</div></div>' +
                '<div class="card">' +
                '<div class="card-header d-flex justify-content-between align-items-center">' +
                '<h6 class="mb-0">Журнал исходящих</h6>' +
                '<select id="mailOutboxFilter" class="form-select form-select-sm w-auto">' +
                '<option value="">Все</option>' +
                '<option value="queued">В очереди</option>' +
                '<option value="sent">Отправлено</option>' +
                '<option value="failed">Ошибка</option>' +
                '<option value="dead">Мёртвые</option>' +
                '</select></div>' +
                '<div class="card-body p-0">' +
                '<table class="table table-sm mb-0">' +
                '<thead><tr><th>ID</th><th>Статус</th><th>Тема</th><th>Попытки</th><th>Ошибка</th><th>Создано</th><th></th></tr></thead>' +
                '<tbody id="mailOutboxBody"></tbody></table></div></div></div>' +
                '<div id="mailTabTemplates" style="display:none"></div>';

            document.querySelectorAll('#mailSettingsTabs [data-mail-tab]').forEach(function (btn) {
                btn.addEventListener('click', function () {
                    const tab = btn.getAttribute('data-mail-tab');
                    document.querySelectorAll('#mailSettingsTabs .nav-link').forEach(function (b) {
                        b.classList.toggle('active', b === btn);
                    });
                    document.getElementById('mailTabTransport').style.display = tab === 'transport' ? 'block' : 'none';
                    document.getElementById('mailTabTemplates').style.display = tab === 'templates' ? 'block' : 'none';
                    if (tab === 'templates' && window.MailTemplatesPanel && !document.getElementById('mailTabTemplates').dataset.mounted) {
                        window.MailTemplatesPanel.mount(document.getElementById('mailTabTemplates'));
                        document.getElementById('mailTabTemplates').dataset.mounted = '1';
                    }
                });
            });

            document.getElementById('mailTransport').addEventListener('change', toggleTransportBlocks);

            loadSettings().then(function (data) {
                if (!data.success) return;
                const s = data.settings || {};
                document.getElementById('mailTransport').value = s.transport || 'file';
                document.getElementById('mailFromEmail').value = s.from_email || '';
                document.getElementById('mailFromName').value = s.from_name || '';
                document.getElementById('mailReplyTo').value = s.reply_to || '';
                const smtp = s.smtp || {};
                document.getElementById('mailSmtpHost').value = smtp.host || '';
                document.getElementById('mailSmtpPort').value = smtp.port || 587;
                document.getElementById('mailSmtpUsername').value = smtp.username || '';
                document.getElementById('mailSmtpEncryption').value = smtp.encryption || 'starttls';
                const pf = s.postfix || {};
                document.getElementById('mailPostfixHost').value = pf.host || '127.0.0.1';
                document.getElementById('mailPostfixPort').value = pf.port || 25;
                document.getElementById('mailPostfixEncryption').value = pf.encryption || 'none';
                document.getElementById('mailPostfixTimeout').value = pf.timeout || 30;
                const sm = s.sendmail || {};
                document.getElementById('mailSendmailPath').value = sm.binary_path || '/usr/sbin/sendmail';
                document.getElementById('mailSendmailArgs').value = sm.arguments || '-t -i';
                document.getElementById('mailSendmailTimeout').value = sm.timeout || 30;
                const local = s.local || {};
                document.getElementById('mailLocalOutputDir').value = local.output_dir || 'var/mail/local';
                const file = s.file || {};
                document.getElementById('mailFileOutputDir').value = file.output_dir || 'var/mail';
                toggleTransportBlocks();
            });

            loadHealthMetrics();
            loadOutbox('');
            document.getElementById('mailOutboxFilter').addEventListener('change', function (e) {
                loadOutbox(e.target.value);
            });

            document.getElementById('mailSaveBtn').addEventListener('click', async function () {
                const transport = document.getElementById('mailTransport').value;
                const settings = {
                    transport: transport,
                    from_email: document.getElementById('mailFromEmail').value,
                    from_name: document.getElementById('mailFromName').value,
                    reply_to: document.getElementById('mailReplyTo').value,
                    smtp: {
                        host: document.getElementById('mailSmtpHost').value,
                        port: parseInt(document.getElementById('mailSmtpPort').value, 10) || 587,
                        username: document.getElementById('mailSmtpUsername').value,
                        password: document.getElementById('mailSmtpPassword').value,
                        encryption: document.getElementById('mailSmtpEncryption').value,
                    },
                    postfix: {
                        host: document.getElementById('mailPostfixHost').value,
                        port: parseInt(document.getElementById('mailPostfixPort').value, 10) || 25,
                        encryption: document.getElementById('mailPostfixEncryption').value,
                        timeout: parseInt(document.getElementById('mailPostfixTimeout').value, 10) || 30,
                    },
                    sendmail: {
                        binary_path: document.getElementById('mailSendmailPath').value,
                        arguments: document.getElementById('mailSendmailArgs').value,
                        timeout: parseInt(document.getElementById('mailSendmailTimeout').value, 10) || 30,
                    },
                    local: {
                        output_dir: document.getElementById('mailLocalOutputDir').value,
                    },
                    file: {
                        output_dir: document.getElementById('mailFileOutputDir').value,
                    },
                };
                const resp = await fetch(API + '/settings', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ settings: settings }),
                });
                const result = await resp.json();
                document.getElementById('mailSaveStatus').textContent = result.success
                    ? 'Сохранено'
                    : (result.error || 'Ошибка');
                if (result.success) {
                    loadHealthMetrics();
                    loadOutbox(document.getElementById('mailOutboxFilter').value);
                }
            });

            document.getElementById('mailTestBtn').addEventListener('click', async function () {
                const to = document.getElementById('mailTestTo').value;
                const resp = await fetch(API + '/test', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ to: to }),
                });
                const result = await resp.json();
                document.getElementById('mailSaveStatus').textContent = result.success
                    ? 'Тест отправлен: ' + (result.job_id || '')
                    : (result.error || 'Ошибка');
                if (result.success) {
                    loadOutbox(document.getElementById('mailOutboxFilter').value);
                    loadHealthMetrics();
                }
            });
        },
    };
})();
