// ── Group Management ─────────────────────────────────────────────────
async function renderGroups() {
    if (!window.securitySettings?.db_auth_enabled) {
        const container = document.getElementById('securityPageContainer');
        container.innerHTML = '<div class="alert alert-warning">Database authentication is not enabled. Please enable it in the Settings tab first.</div>';
        return;
    }
    const container = document.getElementById('securityPageContainer');
    container.innerHTML = '<div class="text-center py-5"><div class="spinner-border"></div></div>';
    let groups = [];
    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/security/groups`);
        const data = await res.json();
        if (!data.success) throw new Error(data.message);
        groups = Array.isArray(data.groups) ? data.groups : [];
    } catch (e) {
        console.error(e);
        container.innerHTML = '<div class="alert alert-danger">Failed to load groups: ' + escapeHtml(e.message) + '</div>';
        return;
    }
    window.securityData.groups = groups;

    let html = '<div class="d-flex justify-content-between mb-2">' +
        '<h6>Groups</h6>' +
        '<button class="btn btn-sm btn-primary" id="btnAddGroup"><i class="bi bi-plus"></i> Add Group</button>' +
        '</div>' +
        '<div class="table-responsive">' +
        '<table class="table table-sm table-bordered small">' +
        '<thead><tr><th>ID</th><th>Name</th><th>Description</th><th>Admin Group</th><th>Actions</th></tr></thead>' +
        '<tbody>';

    for (let i = 0; i < groups.length; i++) {
        const g = groups[i];
        const adminFlag = g.is_admin_group ? 'Yes' : 'No';
        const deleteDisabled = g.is_admin_group ? 'disabled' : '';
        html += '<tr>' +
            '<td>' + g.id + '</td>' +
            '<td>' + escapeHtml(g.name) + '</td>' +
            '<td>' + escapeHtml(g.description || '') + '</td>' +
            '<td>' + adminFlag + '</td>' +
            '<td>' +
            '<button class="btn btn-sm btn-outline-primary edit-group-btn" data-id="' + g.id + '"><i class="bi bi-pencil"></i></button> ' +
            '<button class="btn btn-sm btn-outline-danger delete-group-btn" data-id="' + g.id + '" ' + deleteDisabled + '><i class="bi bi-trash"></i></button>' +
            '</td>' +
            '</tr>';
    }
    html += '</tbody></table></div>';
    container.innerHTML = html;

    document.getElementById('btnAddGroup')?.addEventListener('click', () => openGroupModal());
    document.querySelectorAll('.edit-group-btn').forEach(btn => {
        btn.addEventListener('click', () => openGroupModal(btn.dataset.id));
    });
    document.querySelectorAll('.delete-group-btn').forEach(btn => {
        btn.addEventListener('click', async () => {
            if (btn.disabled) return;
            const confirmed = await pp.dialog.confirm('Delete group?', 'Are you sure?');
            if (!confirmed) return;
            const res = await fetch(`${baseUrl}/project/${projectSlug}/security/groups/${btn.dataset.id}`, { method: 'DELETE' });
            const data = await res.json();
            if (data.success) {
                pp.dialog.toast('success', data.message);
                renderGroups();
            } else {
                pp.dialog.alert('Error', data.message, 'error');
            }
        });
    });
}



async function openGroupModal(groupId = null) {
    let group = null;
    if (groupId) group = window.securityData.groups.find(g => g.id == groupId);

    const { value: submit } = await Swal.fire({
        title: groupId ? 'Edit group' : 'Add group',
        width: 500,
        customClass: { popup: 'secusr-modal' },
        html: `
            <div class="secusr-form">
                <div class="secusr-grid">
                    <label class="secusr-field secusr-wide">
                        <span>Group name <em>*</em></span>
                        <input id="sgName" type="text" autocomplete="off" value="${group ? escapeHtml(group.name) : ''}">
                    </label>
                    <label class="secusr-field secusr-wide">
                        <span>Description</span>
                        <input id="sgDesc" type="text" autocomplete="off"
                               placeholder="What this group is for" value="${group ? escapeHtml(group.description || '') : ''}">
                    </label>
                </div>
                <label class="secusr-check">
                    <input id="sgAdmin" type="checkbox" ${group && group.is_admin_group ? 'checked' : ''}>
                    <span><strong>Administrator group</strong><small>Members get full access — permissions are not restricted.</small></span>
                </label>
            </div>`,
        didOpen: () => document.getElementById('sgName').focus(),
        focusConfirm: false,
        showCancelButton: true,
        confirmButtonText: groupId ? 'Save changes' : 'Create group',
        preConfirm: () => {
            const name = document.getElementById('sgName').value.trim();
            if (!name) return Swal.showValidationMessage('Group name is required.');
            return {
                id: groupId,
                name,
                description: document.getElementById('sgDesc').value.trim(),
                is_admin_group: document.getElementById('sgAdmin').checked ? 1 : 0
            };
        }
    });
    if (!submit) return;

    try {
        const res = await fetch(`${baseUrl}/project/${projectSlug}/security/groups`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(submit)
        });
        const data = await res.json();
        if (data.success) {
            pp.dialog.toast('success', data.message);
            renderGroups();
        } else {
            pp.dialog.alert('Could not save group', data.message, 'error');
        }
    } catch (e) { pp.dialog.toast('error', 'Network error'); }
}
