/* ============================================================
   DroidTester — Modals JS
   ============================================================ */

(function () {
    'use strict';

    function showModal(id) {
        if (typeof bootstrap !== 'undefined') {
            const el = document.getElementById(id);
            if (el) new bootstrap.Modal(el).show();
        }
    }

    document.querySelectorAll('[data-modal]').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            const target = this.dataset.modal;
            if (target === 'logout') showModal('logoutModal');
            else if (target === 'deleteAccount') showModal('deleteAccountModal');
            else if (target === 'insufficientCredits') showModal('insufficientCreditsModal');
        });
    });

    const confirmLogoutBtn = document.getElementById('confirmLogout');
    if (confirmLogoutBtn) {
        confirmLogoutBtn.addEventListener('click', async function () {
            this.disabled = true;
            this.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Logging out...';
            try {
                const data = await window.api('/api/auth/logout', { method: 'POST' });
                window.location.href = (data.data && data.data.redirect) || '/login';
            } catch {
                window.location.href = '/login';
            }
        });
    }

    const confirmDeleteBtn = document.getElementById('confirmDeleteAccount');
    if (confirmDeleteBtn) {
        confirmDeleteBtn.addEventListener('click', async function () {
            const pwd = document.getElementById('deletePasswordConfirm');
            if (!pwd || !pwd.value) {
                window.Toast && window.Toast.fire({ icon: 'warning', title: 'Please enter your password' });
                return;
            }
            this.disabled = true;
            const orig = this.innerHTML;
            this.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Deleting...';
            try {
                const fd = new FormData();
                fd.append('password', pwd.value);
                const data = await window.api('/api/profile/delete', { method: 'POST', body: fd });
                if (data.status === 'success') {
                    window.Toast && window.Toast.fire({ icon: 'success', title: data.message });
                    setTimeout(() => { window.location.href = '/login'; }, 800);
                } else {
                    window.Toast && window.Toast.fire({ icon: 'error', title: data.message });
                    this.disabled = false;
                    this.innerHTML = orig;
                }
            } catch {
                window.Toast && window.Toast.fire({ icon: 'error', title: 'Network error.' });
                this.disabled = false;
                this.innerHTML = orig;
            }
        });
    }

    window.showInsufficientCredits = function () { showModal('insufficientCreditsModal'); };

    document.querySelectorAll('.credit-row-header').forEach(function (header) {
        header.addEventListener('click', function () {
            const content = this.nextElementSibling;
            const toggleIcon = this.querySelector('.credit-toggle-btn i');
            if (!content) return;

            if (content.classList.contains('open')) {
                content.classList.remove('open');
                if (toggleIcon) toggleIcon.className = 'bi bi-arrow-down';
            } else {
                document.querySelectorAll('.credit-expanded-content.open').forEach(function (c) {
                    c.classList.remove('open');
                    const btn = c.previousElementSibling.querySelector('.credit-toggle-btn i');
                    if (btn) btn.className = 'bi bi-arrow-down';
                });
                content.classList.add('open');
                if (toggleIcon) toggleIcon.className = 'bi bi-arrow-up';
            }
        });
    });

    const firstRow = document.querySelector('.credit-row-header');
    if (firstRow) firstRow.click();

})();
