/** * Centralized Logout Logic * Handles modal injection, display, and API interactions for logging out. */ (function () { // Inject Logout Modal HTML and Styles if they don't exist function injectLogoutModal() { if (document.getElementById('common-logout-modal')) return; const modalHtml = `
`; const styleHtml = ` `; document.head.insertAdjacentHTML('beforeend', styleHtml); document.body.insertAdjacentHTML('beforeend', modalHtml); // Bind Events document.getElementById('common-logout-cancel').addEventListener('click', closeLogoutModal); document.getElementById('common-logout-confirm').addEventListener('click', executeLogout); // Close on overlay click document.getElementById('common-logout-modal').addEventListener('click', function (e) { if (e.target === this) closeLogoutModal(); }); } // Expose global functions window.showLogoutModal = function () { injectLogoutModal(); // Ensure it exists const modal = document.getElementById('common-logout-modal'); // Small timeout to allow display:flex to apply before opacity transition modal.style.display = 'flex'; requestAnimationFrame(() => { modal.classList.add('active'); }); }; window.closeLogoutModal = function () { const modal = document.getElementById('common-logout-modal'); if (modal) { modal.classList.remove('active'); setTimeout(() => { modal.style.display = 'none'; }, 300); // Wait for transition } }; // Alias for backward compatibility with existing buttons window.logout = function (event) { if (event) { event.preventDefault(); event.stopPropagation(); } window.showLogoutModal(); }; window.executeLogout = async function () { try { // Close SSE connection if exists if (window.eventSource) { window.eventSource.close(); } // Call API await fetch('/api/auth/logout', { method: 'POST' }); } catch (error) { console.error('Logout error:', error); } finally { // Clear all possible Storage items const keysToRemove = [ 'access_token', 'refresh_token', 'selected_store_id', 'selected_store_name', 'selected_store_code', 'username', 'user_role', 'superadmin_franchise_context', 'store_management_context' ]; keysToRemove.forEach(key => localStorage.removeItem(key)); // Redirect window.location.replace('/login'); } }; // Initialize on load if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', injectLogoutModal); } else { injectLogoutModal(); } })();