(() => {
    document.addEventListener('DOMContentLoaded', () => {
        ['studentModal', 'activityModal', 'courseModal', 'departmentModal', 'userModal']
            .forEach(setupRecordModal);
        setupSidebarToggle();
        setupQrModal('qrModal');
        ['deleteStudentModal', 'deleteActivityModal', 'deleteCourseModal', 'deleteDepartmentModal', 'toggleUserModal', 'resetPasswordModal']
            .forEach(setupDeleteModal);
    });

    function setupRecordModal(id) {
        const modalEl = document.getElementById(id);
        if (!modalEl) return;

        const createTitle = modalEl.dataset.createTitle || 'Add Record';
        const editTitle = modalEl.dataset.editTitle || 'Edit Record';
        const createSubmit = modalEl.dataset.createSubmit || 'Add Record';
        const editSubmit = modalEl.dataset.editSubmit || 'Save Changes';

        modalEl.addEventListener('show.bs.modal', (event) => {
            const button = event.relatedTarget;
            const mode = button && button.dataset ? button.dataset.mode || 'create' : 'create';
            const form = modalEl.querySelector('form');
            if (!form) return;
            const hasRecordPayload = Boolean(button && button.dataset && button.dataset.record);
            const isEdit = mode === 'edit' || hasRecordPayload;

            form.reset();
            form.querySelector('[name="action"]').value = isEdit ? 'update' : 'create';
            form.querySelector('[name="id"]').value = '';

            const title = modalEl.querySelector('[data-modal-title]');
            const submit = modalEl.querySelector('[type="submit"]');

            if (hasRecordPayload) {
                try {
                    const data = JSON.parse(atob(button.dataset.record));
                    Object.entries(data).forEach(([key, value]) => {
                        const field = form.querySelector(`[name="${key}"]`);
                        if (!field) return;
                        field.value = value ?? '';
                    });
                    form.querySelector('[name="id"]').value = data.id ?? '';
                } catch (error) {
                    console.error('Failed to parse record payload', error);
                }
            }

            if (title) {
                title.textContent = isEdit ? editTitle : createTitle;
            }
            if (submit) {
                submit.textContent = isEdit ? editSubmit : createSubmit;
            }
        });
    }

    function setupSidebarToggle() {
        const toggleButtons = document.querySelectorAll('[data-sidebar-toggle]');
        if (!toggleButtons.length) return;

        const storageKey = 'sidebarCollapsed';
        if (localStorage.getItem(storageKey) === '1') {
            document.body.classList.add('sidebar-collapsed');
        }

        toggleButtons.forEach((button) => {
            button.addEventListener('click', () => {
                document.body.classList.toggle('sidebar-collapsed');
                const collapsed = document.body.classList.contains('sidebar-collapsed');
                localStorage.setItem(storageKey, collapsed ? '1' : '0');
            });
        });
    }

    function setupQrModal(id) {
        const modalEl = document.getElementById(id);
        if (!modalEl) return;

        const generator = modalEl.getAttribute('data-generator') || '';
        const nameEl = modalEl.querySelector('[data-qr-name]');
        const idEl = modalEl.querySelector('[data-qr-id]');
        const tokenEl = modalEl.querySelector('[data-qr-token]');
        const imageEl = modalEl.querySelector('[data-qr-image]');
        const downloadEl = modalEl.querySelector('[data-qr-download]');

        modalEl.addEventListener('show.bs.modal', (event) => {
            const trigger = event.relatedTarget;
            if (!trigger || !trigger.dataset) return;

            const token = trigger.dataset.qrToken || '';
            const studentId = trigger.dataset.studentId || '';
            const studentName = trigger.dataset.studentName || 'Student';

            if (nameEl) nameEl.textContent = studentName;
            if (idEl) idEl.textContent = `ID: ${studentId || '—'}`;
            if (tokenEl) tokenEl.textContent = token;

            if (imageEl) {
                if (generator && token) {
                    imageEl.src = `${generator}?token=${encodeURIComponent(token)}&v=${Date.now()}`;
                    imageEl.alt = `QR code for ${studentName}`;
                } else {
                    imageEl.removeAttribute('src');
                    imageEl.alt = 'QR code unavailable';
                }
            }

            if (downloadEl) {
                const canDownload = Boolean(generator && token);
                if (canDownload) {
                    downloadEl.href = `${generator}?token=${encodeURIComponent(token)}&download=1`;
                    downloadEl.setAttribute('download', `qr-${studentId || token}.png`);
                    downloadEl.classList.remove('disabled');
                    downloadEl.removeAttribute('aria-disabled');
                } else {
                    downloadEl.href = '#';
                    downloadEl.setAttribute('aria-disabled', 'true');
                    downloadEl.classList.add('disabled');
                }
            }
        });
    }

    function setupDeleteModal(id) {
        const modalEl = document.getElementById(id);
        if (!modalEl) return;

        const nameEl = modalEl.querySelector('[data-delete-name]');
        const idEl = modalEl.querySelector('[data-delete-id]');
        const messageEl = modalEl.querySelector('[data-delete-message]');
        const confirmButton = modalEl.querySelector('[data-delete-confirm]');
        const hiddenId = modalEl.querySelector('input[name="id"]');
        const defaultNameText = nameEl ? nameEl.textContent : 'Record Name';
        const defaultIdText = idEl ? idEl.textContent : '';
        const defaultMessageText = messageEl ? messageEl.textContent : '';
        const defaultConfirmText = confirmButton ? confirmButton.textContent : '';

        modalEl.addEventListener('show.bs.modal', (event) => {
            const trigger = event.relatedTarget;
            if (!trigger || !trigger.dataset) return;

            const recordId = trigger.dataset.id || '';
            const recordName = trigger.dataset.recordName || trigger.dataset.studentName || 'Record';
            const recordRef = trigger.dataset.recordRef || trigger.dataset.studentId || '';

            if (hiddenId) hiddenId.value = recordId;
            if (nameEl) nameEl.textContent = recordName || defaultNameText;
            if (idEl) {
                if (recordRef) {
                    const label = idEl.dataset.label || '';
                    idEl.textContent = label ? `${label}: ${recordRef}` : recordRef;
                } else {
                    idEl.textContent = defaultIdText;
                }
            }
            if (messageEl) {
                const confirmText = trigger.dataset.confirmText || '';
                messageEl.textContent = confirmText || defaultMessageText;
            }
            if (confirmButton) {
                const confirmLabel = trigger.dataset.confirmLabel || '';
                confirmButton.textContent = confirmLabel || defaultConfirmText;
            }
        });

        modalEl.addEventListener('hidden.bs.modal', () => {
            if (hiddenId) hiddenId.value = '';
            if (nameEl) nameEl.textContent = defaultNameText;
            if (idEl) idEl.textContent = defaultIdText;
            if (messageEl) messageEl.textContent = defaultMessageText;
            if (confirmButton) confirmButton.textContent = defaultConfirmText;
        });
    }
})();
