/**
 * Public Auth settings panel (F5 UI-101).
 */
(function () {
    'use strict';

    const PUBLIC_API = '/api/v1/admin/auth/settings/public';
    const LOCKOUT_API = '/api/v1/admin/auth/settings/lockout';
    const ROLES_API = '/api/v1/admin/roles';

    function canManageAuthSettings() {
        return window.__CAN_MANAGE_AUTH_SETTINGS__ !== false;
    }

    function applyReadOnlyMode() {
        if (canManageAuthSettings()) {
            return;
        }
        const banner = document.createElement('div');
        banner.className = 'alert alert-secondary mb-3';
        banner.textContent = 'Только просмотр: нет права auth_settings_manage.';
        const container = document.getElementById('publicAuthSettingsContainer');
        if (container && container.firstChild) {
            container.insertBefore(banner, container.firstChild);
        }
        ['paAllowRegistration', 'paRequireEmailVerification', 'paConfirmationBaseUrl',
            'paDefaultRoleId', 'paMaxAttempts', 'paWindowSeconds', 'paDurationSeconds'].forEach(function (id) {
            const el = document.getElementById(id);
            if (el) {
                el.disabled = true;
            }
        });
        ['paSavePublicBtn', 'paSaveLockoutBtn'].forEach(function (id) {
            const btn = document.getElementById(id);
            if (btn) {
                btn.disabled = true;
            }
        });
    }

    function toast(msg, type) {
        const el = document.getElementById('publicAuthStatus');
        if (el) {
            el.className = 'ms-2 text-' + (type === 'error' ? 'danger' : 'success');
            el.textContent = msg;
        }
    }

    async function loadRoles(selectEl) {
        const resp = await cascad360Fetch(ROLES_API);
        const data = await resp.json();
        if (!data.success || !selectEl) return;
        selectEl.innerHTML = '<option value="">— не выбрано —</option>';
        (data.roles || []).forEach(function (r) {
            selectEl.innerHTML += '<option value="' + r.id + '">' + r.name + '</option>';
        });
    }

    async function loadPublicSettings() {
        const resp = await cascad360Fetch(PUBLIC_API);
        const data = await resp.json();
        if (!data.success) throw new Error(data.error || 'load failed');
        const s = data.data || {};
        document.getElementById('paAllowRegistration').checked = !!s.allow_public_registration;
        document.getElementById('paRequireEmailVerification').checked = !!s.require_email_verification;
        document.getElementById('paConfirmationBaseUrl').value = s.confirmation_base_url || '';
        const roleSelect = document.getElementById('paDefaultRoleId');
        if (roleSelect && s.default_role_id != null) {
            roleSelect.value = String(s.default_role_id);
        }
    }

    async function loadLockoutSettings() {
        const resp = await cascad360Fetch(LOCKOUT_API);
        const data = await resp.json();
        if (!data.success) throw new Error(data.error || 'load failed');
        const s = data.data || {};
        document.getElementById('paMaxAttempts').value = s.max_attempts != null ? s.max_attempts : 5;
        document.getElementById('paWindowSeconds').value = s.window_seconds != null ? s.window_seconds : 900;
        document.getElementById('paDurationSeconds').value = s.duration_seconds != null ? s.duration_seconds : 1800;
    }

    async function savePublicSettings() {
        if (!canManageAuthSettings()) {
            toast('Недостаточно прав для сохранения', 'error');
            return;
        }
        const body = {
            allow_public_registration: document.getElementById('paAllowRegistration').checked,
            require_email_verification: document.getElementById('paRequireEmailVerification').checked,
            confirmation_base_url: document.getElementById('paConfirmationBaseUrl').value.trim(),
            default_role_id: parseInt(document.getElementById('paDefaultRoleId').value, 10) || null,
        };
        const resp = await cascad360Fetch(PUBLIC_API, {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        });
        const data = await resp.json();
        if (!data.success) throw new Error(data.error || 'save failed');
        toast('Public Auth сохранено', 'ok');
    }

    async function saveLockoutSettings() {
        if (!canManageAuthSettings()) {
            toast('Недостаточно прав для сохранения', 'error');
            return;
        }
        const body = {
            max_attempts: parseInt(document.getElementById('paMaxAttempts').value, 10),
            window_seconds: parseInt(document.getElementById('paWindowSeconds').value, 10),
            duration_seconds: parseInt(document.getElementById('paDurationSeconds').value, 10),
        };
        const resp = await cascad360Fetch(LOCKOUT_API, {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        });
        const data = await resp.json();
        if (!data.success) throw new Error(data.error || 'save failed');
        toast('Lockout сохранён', 'ok');
    }

    window.PublicAuthSettingsPanel = {
        mount: function (container) {
            if (!container) return;
            container.innerHTML =
                '<div class="row">' +
                '<div class="col-lg-6">' +
                '<div class="card mb-3"><div class="card-header"><h6 class="mb-0">Public Auth</h6></div>' +
                '<div class="card-body">' +
                '<div class="form-check form-switch mb-3">' +
                '<input class="form-check-input" type="checkbox" id="paAllowRegistration">' +
                '<label class="form-check-label" for="paAllowRegistration">Разрешить публичную регистрацию</label></div>' +
                '<div class="form-check form-switch mb-3">' +
                '<input class="form-check-input" type="checkbox" id="paRequireEmailVerification">' +
                '<label class="form-check-label" for="paRequireEmailVerification">Требовать верификацию email</label></div>' +
                '<div class="mb-3"><label class="form-label">Confirmation base URL</label>' +
                '<input type="url" class="form-control" id="paConfirmationBaseUrl" placeholder="https://app.example/verify"></div>' +
                '<div class="mb-3"><label class="form-label">Роль по умолчанию</label>' +
                '<select class="form-select" id="paDefaultRoleId"><option value="">Загрузка...</option></select></div>' +
                '<button type="button" class="btn btn-primary" id="paSavePublicBtn">Сохранить Public Auth</button>' +
                '</div></div></div>' +
                '<div class="col-lg-6">' +
                '<div class="card mb-3"><div class="card-header"><h6 class="mb-0">Lockout</h6></div>' +
                '<div class="card-body">' +
                '<div class="mb-3"><label class="form-label">Max attempts</label>' +
                '<input type="number" class="form-control" id="paMaxAttempts" min="1"></div>' +
                '<div class="mb-3"><label class="form-label">Window (seconds)</label>' +
                '<input type="number" class="form-control" id="paWindowSeconds" min="60"></div>' +
                '<div class="mb-3"><label class="form-label">Duration (seconds)</label>' +
                '<input type="number" class="form-control" id="paDurationSeconds" min="60"></div>' +
                '<button type="button" class="btn btn-primary" id="paSaveLockoutBtn">Сохранить Lockout</button>' +
                '</div></div></div></div>' +
                '<span id="publicAuthStatus" class="ms-2 text-muted"></span>';

            const roleSelect = document.getElementById('paDefaultRoleId');
            loadRoles(roleSelect).then(function () {
                return Promise.all([loadPublicSettings(), loadLockoutSettings()]);
            }).catch(function (e) {
                toast(e.message || 'Ошибка загрузки', 'error');
            });

            document.getElementById('paSavePublicBtn').addEventListener('click', function () {
                savePublicSettings().catch(function (e) {
                    toast(e.message || 'Ошибка', 'error');
                });
            });
            document.getElementById('paSaveLockoutBtn').addEventListener('click', function () {
                saveLockoutSettings().catch(function (e) {
                    toast(e.message || 'Ошибка', 'error');
                });
            });
            applyReadOnlyMode();
        },
    };
})();
