class MabangaExpress {
    constructor() {
        this.currentUser = null;
        this.currentPage = 'home';
        this.isInitialized = false;
        this.slideshowInstance = null;
        this.settings = {}; // To store system settings
        this.clickOutsideHandler = this.handleClickOutside.bind(this);
        this.appContainer = document.getElementById('app');

        this.accountActions = {
            'login': this.showLoginForm.bind(this),
            'register': this.showRegisterForm.bind(this),
            'logout': this.logout.bind(this),
            'admin_dashboard': this.loadAdminDashboard.bind(this),
            'rider_dashboard': this.loadRiderDashboard.bind(this),
            'my_shops': this.loadMyShops.bind(this),
            'profile': this.showProfileEdit.bind(this),
            'addresses': this.showAddresses.bind(this),
            'payment': this.showPaymentMethods.bind(this),
            'settings': this.showSettings.bind(this),
            'help': this.showHelp.bind(this),
            'about': this.showAbout.bind(this)
        };

        this.init();
    }

    async init() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.initializeApp();
            });
        } else {
            this.initializeApp();
        }
    }

    getAppContainer() {
        return this.appContainer;
    }

    async initializeApp() {
        console.log('Initializing Mabanga Express...');
        try {
            await this.checkAuth();
            await this.loadSettings();
            this.renderTemplates();
            this.setupEventListeners();
            this.setupHeaderScroll();
            this.initializeManagers();
            // Load initial page based on auth status
            const initialPage = this.currentUser ? 'home' : 'login';
            await this.loadPage(initialPage);
            this.notificationManager.startPolling();

            // Global polling for riders to receive delivery alerts anywhere in the app
            if (this.currentUser && this.currentUser.role === 'rider') {
                this.riderManager.startPolling();
            }
            
            // Register Service Worker for background notifications
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('sw.js')
                    .then(reg => {
                        console.log('Service Worker registered successfully with scope:', reg.scope);
                    })
                    .catch(err => {
                        console.error('Service Worker registration failed:', err);
                    });
            }

            this.isInitialized = true;
            console.log('App initialized successfully');
        } catch (error) {
            console.error('App initialization failed:', error);
            this.showError('Failed to initialize app');
        }
    }

    async loadSettings() {
        try {
            const response = await fetch('api/admin/settings.php');
            const data = await response.json();
            if (data.success) {
                this.settings = data.settings;
                console.log('System settings loaded.');
            }
        } catch (error) {
            console.error('Failed to load system settings:', error);
        }
    }

    initializeManagers() {
        console.log('Initializing role-based managers...');
        this.shopManager = null;
        this.notifier = new NotificationManager(); // For toast notifications
        this.authManager = new AuthManager(this);
        this.customerManager = new CustomerManager(this);
        this.shopManager = new ShopManager(this);
        this.riderManager = new RiderManager(this);
        this.adminManager = new AdminManager(this);
        this.cartManager = new CartManager(this);
        this.notificationManager = new AppNotificationManager(this); // For bell icon notifications
    }

    setupHeaderScroll() {
        let lastScroll = 0;
        const header = document.querySelector('header');
        const scrollThreshold = 50;

        window.addEventListener('scroll', () => {
            const currentScroll = window.pageYOffset;

            // Determine scroll direction
            if (currentScroll > lastScroll && currentScroll > scrollThreshold) {
                // Scrolling down & past threshold
                header.classList.add('header-hidden');
            } else {
                // Scrolling up or at top
                header.classList.remove('header-hidden');
            }

            lastScroll = currentScroll;
        });
    }

    async checkAuth() {
        try {
            const response = await fetch('api/auth/check.php');
            if (!response.ok) throw new Error('Auth check failed');
            const data = await response.json();

            if (data.success) {
                this.currentUser = data.user;
                console.log('User authenticated:', this.currentUser);
            } else {
                console.log('User not authenticated');
                this.currentUser = null;
            }
        } catch (error) {
            console.log('Auth check error:', error);
            this.currentUser = null;
        }
    }

    renderTemplates() {
        console.log('Rendering templates...');

        // Render header
        const headerElement = document.getElementById('header');
        if (headerElement) {
            const headerTemplate = document.getElementById('header-template');
            if (headerTemplate) {
                headerElement.innerHTML = headerTemplate.innerHTML;
                console.log('Header rendered');
            }
        }

        // Render footer
        const footerElement = document.getElementById('footer-nav');
        if (footerElement) {
            const footerTemplate = document.getElementById('footer-template');
            if (footerTemplate) {
                footerElement.innerHTML = footerTemplate.innerHTML;
                console.log('Footer rendered');
            }
        }

        // Render account menu
        const accountMenuElement = document.getElementById('account-menu');
        if (accountMenuElement) {
            const accountMenuTemplate = document.getElementById('account-menu-template');
            if (accountMenuTemplate) {
                accountMenuElement.innerHTML = accountMenuTemplate.innerHTML;
                console.log('Account menu rendered');
            }
        }

        this.updateUI();
    }

    setupEventListeners() {
        console.log('Setting up event listeners...');

        // Use event delegation for dynamic elements
        document.addEventListener('click', (e) => {
            // Navigation items
            const navItem = e.target.closest('.nav-item');
            if (navItem && navItem.dataset.page) {
                e.preventDefault();
                const page = navItem.dataset.page;
                console.log('Navigation clicked:', page);
                this.loadPage(page);
                this.setActiveNav(page);
                this.hideAccountMenu();
            }

            // Header auth buttons (for logged-out state)
            const loginBtn = e.target.closest('#login-btn');
            if (loginBtn) {
                e.preventDefault();
                this.showLoginForm();
            }

            const registerBtn = e.target.closest('#register-btn');
            if (registerBtn) {
                e.preventDefault();
                this.showRegisterForm();
            }

            // Notification bell
            const notificationsBtn = e.target.closest('#notifications-btn');
            if (notificationsBtn) {
                e.preventDefault();
                this.notificationManager.toggleNotificationList();
            }

            // Account menu trigger - multiple selectors for safety
            const accountTrigger = e.target.closest('#account-menu-trigger') ||
                e.target.closest('.account-trigger') ||
                (e.target.closest('.nav-item') && !e.target.closest('.nav-item').dataset.page);

            if (accountTrigger) {
                e.preventDefault();
                e.stopPropagation();
                console.log('Account menu trigger clicked');
                this.toggleAccountMenu();
            }

            // Account menu actions
            const menuItem = e.target.closest('.menu-item[data-action]');
            if (menuItem) {
                const action = menuItem.dataset.action;
                console.log('Menu action:', action);
                this.handleAccountAction(action);
            }

            // Quick actions
            if (e.target.closest('.action-card')) {
                const actionCard = e.target.closest('.action-card');
                this.handleQuickAction(actionCard);
            }
        });

        // Handle escape key to close account menu
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.hideAccountMenu();
            }
        });

        console.log('Event listeners setup complete');
    }

    _getLoggedInMenuHTML() {
        let menuHTML = '';

        // Role-specific menu items
        const role = this.currentUser.role;
        if (role === 'admin') {
            menuHTML += `
                <div class="menu-item" data-action="admin_dashboard"><i class="fas fa-tachometer-alt"></i><span>Admin Dashboard</span></div>
                <div class="menu-divider"></div>`;
        } else if (role === 'rider') {
            menuHTML += `
                <div class="menu-item" data-action="rider_dashboard"><i class="fas fa-motorcycle"></i><span>Rider Dashboard</span></div>
                <div class="menu-divider"></div>`;
        } else if (role === 'shop_owner') {
            menuHTML += `
                <div class="menu-item" data-action="my_shops"><i class="fas fa-store"></i><span>My Shops</span></div>
                <div class="menu-divider"></div>`;
        }

        // Common menu items
        menuHTML += `
            <div class="menu-item" data-action="profile"><i class="fas fa-user-edit"></i><span>Edit Profile</span></div>
            <div class="menu-item" data-action="addresses"><i class="fas fa-map-marker-alt"></i><span>My Addresses</span></div>
            <div class="menu-item" data-action="payment"><i class="fas fa-credit-card"></i><span>Payment Methods</span></div>
            <div class="menu-item" data-action="settings"><i class="fas fa-cog"></i><span>Settings</span></div>
            <div class="menu-item" data-action="help"><i class="fas fa-question-circle"></i><span>Help & Support</span></div>
            <div class="menu-divider"></div>
            <div class="menu-item logout" data-action="logout"><i class="fas fa-sign-out-alt"></i><span>Logout</span></div>
        `;

        return menuHTML;
    }

    _getLoggedOutMenuHTML() {
        return `
            <div class="menu-item" data-action="login"><i class="fas fa-sign-in-alt"></i><span>Login to Account</span></div>
            <div class="menu-item" data-action="register"><i class="fas fa-user-plus"></i><span>Create Account</span></div>
            <div class="menu-divider"></div>
            <div class="menu-item" data-action="help"><i class="fas fa-question-circle"></i><span>Help & Support</span></div>
            <div class="menu-item" data-action="about"><i class="fas fa-info-circle"></i><span>About Mabanga Express</span></div>
        `;
    }

    updateUI() {
        console.log('Updating UI for user:', this.currentUser);
        const headerIcons = document.getElementById('header-icons');
        const menuItems = document.getElementById('menu-items');
        const userName = document.getElementById('user-name');
        const userEmail = document.getElementById('user-email');

        if (this.currentUser) {
            // --- LOGGED-IN STATE ---

            // Update header icons
            if (headerIcons) {
                const loggedInTemplate = document.getElementById('header-icons-loggedin');
                if (loggedInTemplate) headerIcons.innerHTML = loggedInTemplate.innerHTML;
            }

            // Update account menu header
            if (userName) userName.textContent = this.currentUser.name;
            if (userEmail) userEmail.textContent = this.currentUser.email;

            // Update account menu items
            if (menuItems) {
                menuItems.innerHTML = this._getLoggedInMenuHTML();
            }

        } else {
            // --- LOGGED-OUT STATE ---

            // Update header icons
            if (headerIcons) {
                const loggedOutTemplate = document.getElementById('header-icons-loggedout');
                if (loggedOutTemplate) {
                    headerIcons.innerHTML = loggedOutTemplate.innerHTML;
                    // Note: Event listeners for login/register are now handled by the main delegated listener in setupEventListeners
                }
            }

            // Update account menu header
            if (userName) userName.textContent = 'Welcome Guest';
            if (userEmail) userEmail.textContent = 'Sign in to access all features';

            // Update account menu items
            if (menuItems) {
                menuItems.innerHTML = this._getLoggedOutMenuHTML();
            }
        }
    }

    async loadPage(page) {
        console.log('Loading page:', page);
        this.currentPage = page;
        const mainContent = document.getElementById('main-content');

        if (!mainContent) {
            console.error('Main content element not found');
            return;
        }

        // Clean up any page-specific instances before loading new content
        if (this.slideshowInstance) {
            this.slideshowInstance.destroy();
            this.slideshowInstance = null;
        }

        try {
            mainContent.innerHTML = '<div class="loading">Loading...</div>';

            let content = '';

            switch (page) {
                case 'home':
                    content = await this.loadHomePage();
                    break;
                case 'orders':
                    content = await this.loadOrdersPage();
                    break;
                case 'shops':
                    content = await this.loadShopsPage();
                    break;
                default:
                    content = await this.loadHomePage();
            }

            mainContent.innerHTML = content;
            this.initializePageSpecificFeatures();
        } catch (error) {
            console.error('Error loading page:', error);
            mainContent.innerHTML = '<div class="error">Error loading page. Please try refreshing.</div>';
        }
    }

    async _fetchHomePageData() {
        const [slidesResponse, deliveriesResponse] = await Promise.all([
            fetch('api/admin/slides.php'),
            fetch('api/deliveries/list.php?limit=5')
        ]);
        const slidesData = await slidesResponse.json();
        const deliveriesData = await deliveriesResponse.json();
        return { slides: slidesData.slides || [], deliveries: deliveriesData.deliveries || [] };
    }

    _renderSlideshow(slides) {
        if (!slides || slides.length === 0) return '';

        const slidesHTML = slides.map((slide, index) => {
            const activeClass = index === 0 ? 'active' : '';
            return `
                <div class="slide ${activeClass}" style="background-image: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.3)), url('${slide.image_path}')">
                    <div class="slide-content">
                        <h3>${slide.title}</h3>
                        <p>${slide.description}</p>
                    </div>
                </div>
            `;
        }).join('');

        const dotsHTML = slides.map((_, index) => {
            const activeClass = index === 0 ? 'active' : '';
            return `<div class="dot ${activeClass}" data-slide="${index}"></div>`;
        }).join('');

        return `
            <div class="slideshow-container">
                ${slidesHTML}
                <div class="slideshow-dots">
                    ${dotsHTML}
                </div>
            </div>
        `;
    }

    _renderRecentDeliveries(deliveries) {
        let deliveriesHTML;
        if (deliveries && deliveries.length > 0) {
            deliveriesHTML = deliveries.map(delivery => {
                const statusClass = `status-${delivery.status.replace('_', '-')}`;
                return `
                    <div class="delivery-item">
                        <div class="delivery-info">
                            <h4>${delivery.package_description}</h4>
                            <p>From: ${delivery.pickup_location} • To: ${delivery.delivery_location}</p>
                        </div>
                        <div class="delivery-status ${statusClass}">${delivery.status}</div>
                    </div>
                `;
            }).join('');
        } else {
            deliveriesHTML = '<p>No recent deliveries found. Create your first delivery!</p>';
        }

        return `
            <div class="recent-deliveries">
                <div class="section-title">
                    <h2>Recent Deliveries</h2>
                    <a href="#" style="color: var(--primary-blue); font-size: 0.9rem;">View All</a>
                </div>
                ${deliveriesHTML}
            </div>
        `;
    }

    async loadHomePage() {
        console.log('Loading home page');

        try {
            const { slides, deliveries } = await this._fetchHomePageData();
            const slideshowHTML = this._renderSlideshow(slides);
            const recentDeliveriesHTML = this._renderRecentDeliveries(deliveries);

            return `
                ${slideshowHTML}
                <div class="main-content">
                    <div class="quick-actions">
                        <div class="action-card send" data-action="send-package">
                            <i class="fas fa-shipping-fast"></i>
                            <h3>Send Package</h3>
                            <p>Request delivery</p>
                        </div>
                        <div class="action-card shop" data-action="shop-now">
                            <i class="fas fa-store"></i>
                            <h3>Shop Now</h3>
                            <p>Browse stores</p>
                        </div>
                        <div class="action-card track" data-action="track-order">
                            <i class="fas fa-map-marker-alt"></i>
                            <h3>Track Order</h3>
                            <p>Monitor delivery</p>
                        </div>
                        <div class="action-card history" data-action="history">
                            <i class="fas fa-history"></i>
                            <h3>History</h3>
                            <p>Past deliveries</p>
                        </div>
                    </div>

                    ${recentDeliveriesHTML}
                </div>
            `;
        } catch (error) {
            console.error('Error loading home page:', error);
            return this.getErrorHTML('Failed to load home page');
        }
    }

    async loadOrdersPage() {
        if (!this.currentUser) {
            return '<div class="auth-required">Please log in to view your orders</div>';
        }

        try {
            const response = await fetch('api/deliveries/list.php');
            const data = await response.json();

            let ordersHTML = '';
            if (data.success && data.deliveries) {
                ordersHTML = data.deliveries.map(order => `
                    <div class="delivery-item">
                        <div class="delivery-info">
                            <h4>${order.package_description}</h4>
                            <p>From: ${order.pickup_location} • To: ${order.delivery_location}</p>
                            <small>Created: ${new Date(order.created_at).toLocaleDateString()}</small>
                        </div>
                        <div class="delivery-status status-${order.status.replace('_', '-')}">
                            ${order.status}
                        </div>
                    </div>
                `).join('');
            } else {
                ordersHTML = '<p>No orders found</p>';
            }

            return `
                <div class="main-content">
                    <div class="section-title">
                        <h2>My Orders</h2>
                    </div>
                    <div class="recent-deliveries">
                        ${ordersHTML}
                    </div>
                </div>
            `;
        } catch (error) {
            console.error('Error loading orders:', error);
            return this.getErrorHTML('Failed to load orders');
        }
    }

    async loadShopsPage() {
        try {
            const response = await fetch('api/shops/list.php');
            const data = await response.json();

            let shopsHTML = '';
            if (data.success && data.shops) {
                const approvedShops = data.shops.filter(shop => shop.is_approved);
                shopsHTML = approvedShops.map(shop => `
                    <div class="shop-card action-card" data-shop-id="${shop.id}">
                        <div class="shop-image" style="background-image: url('${shop.image || 'assets/images/default-shop.jpg'}')"></div>
                        <h3>${shop.name}</h3>
                        <p>${shop.description}</p>
                        <p><strong>Location:</strong> ${shop.location}</p>
                        <button class="btn-primary view-shop-btn" data-shop-id="${shop.id}">View Shop</button>
                    </div>
                `).join('');
            } else {
                shopsHTML = '<p>No shops available at the moment</p>';
            }

            let createShopBtn = '';
            if (this.currentUser && this.currentUser.role === 'shop_owner') {
                createShopBtn = '<button class="btn-primary create-shop-action" style="margin-left: auto;"><i class="fas fa-plus"></i> Create Shop</button>';
            }

            return `
                <div class="main-content">
                    <div class="section-title">
                        <h2>Available Shops</h2>
                        ${createShopBtn}
                    </div>
                    <div class="shops-grid">
                        ${shopsHTML}
                    </div>
                </div>
            `;
        } catch (error) {
            console.error('Error loading shops:', error);
            return this.getErrorHTML('Failed to load shops');
        }
    }

    initializePageSpecificFeatures() {
        // If a slideshow container exists on the current page, initialize it.
        if (document.querySelector('.slideshow-container')) {
            this.slideshowInstance = new Slideshow('.slideshow-container');
        }
    }

    setActiveNav(page) {
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });

        const activeNav = document.querySelector(`[data-page="${page}"]`);
        if (activeNav) {
            activeNav.classList.add('active');
        }
    }

    toggleAccountMenu() {
        console.log('Toggling account menu');
        const accountMenu = document.getElementById('account-menu');
        if (!accountMenu) {
            console.error('Account menu element not found');
            return;
        }
        accountMenu.classList.contains('active') ? this.hideAccountMenu() : this.showAccountMenu();
    }

    showAccountMenu() {
        console.log('Showing account menu');
        const accountMenu = document.getElementById('account-menu');
        if (accountMenu) {
            console.log('Account menu element found, adding active class');
            accountMenu.classList.add('active');

            // Add click outside listener
            document.addEventListener('click', this.clickOutsideHandler, { capture: true });
        } else {
            console.error('Account menu element not found when trying to show');
        }
    }

    hideAccountMenu() {
        console.log('Hiding account menu');
        const accountMenu = document.getElementById('account-menu');
        if (accountMenu) {
            accountMenu.classList.remove('active');

            // Remove click outside listener
            document.removeEventListener('click', this.clickOutsideHandler, { capture: true });
        }
    }

    handleClickOutside(event) {
        const accountMenu = document.getElementById('account-menu');
        // If the menu is active and the click is outside of it, hide it.
        if (accountMenu.classList.contains('active') && !accountMenu.contains(event.target)) {
            console.log('Click outside detected, hiding account menu');
            event.stopPropagation(); // Prevent the click from triggering other listeners, like the toggle.
            this.hideAccountMenu();
        }
    }

    handleAccountAction(action) {
        console.log('Handling account action:', action);

        const handler = this.accountActions[action];

        if (handler) {
            handler();
        } else {
            console.log('Unknown action:', action);
        }

        this.hideAccountMenu();
    }

    showLoginForm() {
        const mainContent = document.getElementById('main-content');
        if (mainContent) {
            mainContent.innerHTML = `
                <div class="auth-container">
                    <div class="auth-card">
                        <h2>Welcome to Mabanga Express</h2>
                        <form id="login-form">
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" id="email" name="email" placeholder="Enter your email" required>
                            </div>
                            <div class="form-group">
                                <label for="password">Password</label>
                                <div class="password-input-group">
                                    <input type="password" id="password" name="password" placeholder="Enter your password" required>
                                    <button type="button" class="password-toggle" tabindex="-1">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="form-group checkbox-group">
                                <label class="checkbox-label">
                                    <input type="checkbox" id="remember-me" name="remember_me">
                                    <span>Remember me</span>
                                </label>
                                <a href="#" class="forgot-password" id="forgot-password">Forgot Password?</a>
                            </div>
                            <button type="submit" class="btn-primary">Login</button>
                        </form>
                        <div class="auth-links">
                            <p>Don't have an account? <a href="#" id="show-register">Register here</a></p>
                        </div>
                    </div>
                </div>
            `;

        }
    }

    showRegisterForm() {
        const mainContent = document.getElementById('main-content');
        if (mainContent) {
            mainContent.innerHTML = `
                <div class="auth-container">
                    <div class="auth-card">
                        <h2>Create Account</h2>
                        <form id="register-form">
                            <div class="form-group">
                                <label for="name">Full Name</label>
                                <input type="text" id="name" name="name" placeholder="Enter your full name" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" id="email" name="email" placeholder="Enter your email" required>
                            </div>
                            <div class="form-group">
                                <label for="password">Password</label>
                                <div class="password-input-group">
                                    <input type="password" id="password" name="password" 
                                           placeholder="Enter your password" required
                                           pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$"
                                           title="Must contain at least 8 characters, one uppercase, one lowercase, one number and one special character">
                                    <button type="button" class="password-toggle" tabindex="-1">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                <div class="password-strength">
                                    <div class="strength-meter"></div>
                                    <div class="strength-text"></div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="phone">Phone Number</label>
                                <input type="tel" id="phone" name="phone" 
                                       placeholder="Enter your phone number"
                                       pattern="^\\+?[\\d\\s-]{10,}$"
                                       title="Please enter a valid phone number">
                            </div>
                            <div class="form-group">
                                <label for="role">Account Type</label>
                                <select id="role" name="role" required>
                                    <option value="">Select your role</option>
                                    <option value="customer">Customer - Send and receive packages</option>
                                    <option value="shop_owner">Shop Owner - List products and manage store</option>
                                    <option value="rider">Delivery Rider - Accept and deliver orders</option>
                                </select>
                            </div>
                            <button type="submit" class="btn-primary">Create Account</button>
                        </form>
                        <div class="auth-links">
                            <p>Already have an account? <a href="#" id="show-login">Login here</a></p>
                        </div>
                    </div>
                </div>
            `;
        }
    }

    async logout() {
        try {
            await fetch('api/auth/logout.php');
            if (this.notificationManager) {
                this.notificationManager.stopPolling();
                this.notificationManager.clearNotifications();
            }
            if (this.riderManager) {
                this.riderManager.stopPolling();
            }
            this.currentUser = null;
            this.updateUI();
            this.loadPage('home');
        } catch (error) {
            console.error('Logout failed:', error);
        }
    }

    handleQuickAction(card) {
        if (!card) return;

        const action = card.dataset.action;
        if (!action) return;

        switch (action) {
            case 'send-package':
                if (this.customerManager) {
                    this.customerManager.showDeliveryModal();
                } else if (!this.currentUser) {
                    this.showLoginForm();
                }
                break;
            case 'shop-now':
                this.loadPage('shops');
                this.setActiveNav('shops');
                break;
            case 'track-order':
                this.customerManager?.promptTrack();
                break;
            case 'history':
                this.customerManager?.loadDeliveries(true);
                break;
        }
    }

    loadAdminDashboard() {
        if (this.currentUser?.role !== 'admin') return;

        const mainContent = document.getElementById('main-content');
        mainContent.innerHTML = `
            <div class="admin-dashboard">
                <div class="section-title">
                    <h2>Admin Dashboard</h2>
                </div>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="stat-info">
                            <h3 id="total-users">0</h3>
                            <p>Total Users</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-shipping-fast"></i>
                        </div>
                        <div class="stat-info">
                            <h3 id="total-deliveries">0</h3>
                            <p>Total Deliveries</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-store"></i>
                        </div>
                        <div class="stat-info">
                            <h3 id="total-shops">0</h3>
                            <p>Total Shops</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-money-bill-wave"></i>
                        </div>
                        <div class="stat-info">
                            <h3 id="total-revenue">$0</h3>
                            <p>Total Revenue</p>
                        </div>
                    </div>
                </div>
                <div class="admin-actions" id="admin-actions-container">
                    <button class="btn-primary" data-admin-action="manageUsers">Manage Users</button>
                    <button class="btn-primary" data-admin-action="manageDeliveries">Manage Deliveries</button>
                    <button class="btn-primary" data-admin-action="createDelivery">Create Delivery</button>
                    <button class="btn-primary" data-admin-action="manageShops">Manage Shops</button>
                    <button class="btn-primary" data-admin-action="manageSlides">Manage Slides</button>
                    <button class="btn-secondary" data-admin-action="manageSettings">
                        <i class="fas fa-cogs"></i> System Settings
                    </button>
                </div>
            </div>
        `;

        if (this.adminManager) {
            this.adminManager.loadStats();
            document.getElementById('admin-actions-container').addEventListener('click', (e) => {
                const action = e.target.dataset.adminAction;
                if (action && this.adminManager[action]) {
                    this.adminManager[action]();
                }
            });
            // Make the revenue card clickable
            document.getElementById('total-revenue').closest('.stat-card').style.cursor = 'pointer';
            document.getElementById('total-revenue').closest('.stat-card').addEventListener('click', () => {
                this.adminManager.showRevenueDetails();
            });
        }
    }

    loadRiderDashboard() {
        if (this.currentUser?.role !== 'rider') return;

        const mainContent = document.getElementById('main-content');
        mainContent.innerHTML = `
            <div class="rider-dashboard">
                <div class="section-title">
                    <h2>Rider Dashboard</h2>
                </div>
                <div class="rider-stats">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="stat-info">
                            <h3 id="pending-deliveries">0</h3>
                            <p>Pending</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-motorcycle"></i>
                        </div>
                        <div class="stat-info">
                            <h3 id="active-deliveries">0</h3>
                            <p>Active</p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="stat-info">
                            <h3 id="completed-deliveries">0</h3>
                            <p>Completed</p>
                        </div>
                    </div>
                </div>
                <div class="deliveries-section">
                    <h3>Available Deliveries</h3>
                    <div id="available-deliveries">
                        Loading available deliveries...
                    </div>
                </div>
                <div class="deliveries-section">
                    <h3>My Deliveries</h3>
                    <div id="my-deliveries">
                        Loading your deliveries...
                    </div>
                </div>
            </div>
        `;

        if (this.riderManager) {
            // Start polling for stats and new deliveries
            this.riderManager.loadDashboardData(); // Initial load
        }
    }

    loadMyShops() {
        if (this.currentUser?.role !== 'shop_owner') return;

        const mainContent = document.getElementById('main-content');
        mainContent.innerHTML = `
            <div class="my-shops">
                <div class="section-title">
                    <h2>My Shops</h2>
                    <button class="btn-primary create-shop-action">
                        <i class="fas fa-plus"></i> Create New Shop
                    </button>
                </div>
                <div id="shops-list">
                    Loading your shops...
                </div>
            </div>
        `;

        if (this.shopManager) {
            // This method doesn't exist on ShopManager, but if it did, it would be called here.
            // For now, we can just load the shops page.
            this.loadPage('shops');
        }
    }

    _renderAccountPage(title, content) {
        const mainContent = document.getElementById('main-content');
        mainContent.innerHTML = `
            <div class="account-page-container">
                <div class="section-title">
                    <h2>${title}</h2>
                </div>
                <div class="account-page-content">
                    ${content}
                </div>
            </div>
        `;
    }

    showProfileEdit() {
        if (!this.currentUser) return;
        const user = this.currentUser;

        const content = `
            <form id="profile-edit-form">
                <div class="profile-avatar-section">
                    <img src="${user.avatar || 'assets/images/default-avatar.png'}" alt="User Avatar" id="profile-avatar-preview">
                    <input type="file" name="avatar" id="avatar-upload" accept="image/*" style="display: none;">
                    <button type="button" class="btn-secondary" onclick="document.getElementById('avatar-upload').click();">Change Picture</button>
                </div>
                <div class="form-group">
                    <label for="profile-name">Full Name</label>
                    <input type="text" id="profile-name" name="name" value="${user.name}" required>
                </div>
                <div class="form-group">
                    <label for="profile-email">Email (cannot be changed)</label>
                    <input type="email" id="profile-email" name="email" value="${user.email}" disabled>
                </div>
                <div class="form-group">
                    <label for="profile-phone">Phone Number</label>
                    <input type="tel" id="profile-phone" name="phone" value="${user.phone || ''}">
                </div>
                <hr>
                <h4>Change Password</h4>
                <div class="form-group">
                    <label for="profile-new-password">New Password (leave blank to keep current)</label>
                    <input type="password" id="profile-new-password" name="new_password">
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn-primary">Save Changes</button>
                </div>
            </form>
        `;
        this._renderAccountPage('Edit Profile', content);
        this.setupProfileEditListeners();
    }

    setupProfileEditListeners() {
        const form = document.getElementById('profile-edit-form');
        const avatarUpload = document.getElementById('avatar-upload');
        const avatarPreview = document.getElementById('profile-avatar-preview');

        avatarUpload.addEventListener('change', () => {
            if (avatarUpload.files && avatarUpload.files[0]) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    avatarPreview.src = e.target.result;
                };
                reader.readAsDataURL(avatarUpload.files[0]);
            }
        });

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';

            try {
                const imageFile = avatarUpload.files[0];
                let avatarUrl = null;

                if (imageFile) {
                    const uploadFormData = new FormData();
                    uploadFormData.append('image', imageFile);
                    uploadFormData.append('type', 'profiles');
                    const uploadResponse = await fetch('api/upload.php', { method: 'POST', body: uploadFormData });
                    const uploadResult = await uploadResponse.json();
                    if (!uploadResult.success) throw new Error(uploadResult.message);
                    avatarUrl = uploadResult.url;
                }

                const data = {
                    name: form.elements['name'].value,
                    phone: form.elements['phone'].value,
                    avatar: avatarUrl,
                    new_password: form.elements['new_password'].value
                };

                const response = await fetch('api/users/update_profile.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
                const result = await response.json();
                if (!result.success) throw new Error(result.message);

                this.notifier.show('Profile updated successfully!', 'success');
                await this.checkAuth(); // Refresh user data
                this.updateUI();

            } catch (error) {
                this.notifier.show(error.message, 'error');
            } finally {
                submitBtn.disabled = false;
                submitBtn.innerHTML = 'Save Changes';
            }
        });
    }

    showAddresses() {
        this._renderAccountPage('My Addresses', '<div class="empty-state">Address management feature coming soon!</div>');
    }

    showPaymentMethods() {
        this._renderAccountPage('Payment Methods', '<div class="empty-state">Payment methods feature coming soon!</div>');
    }

    showSettings() {
        this._renderAccountPage('App Settings', '<div class="empty-state">User settings feature coming soon!</div>');
    }

    showHelp() {
        const content = `
            <div class="help-content p-3 text-center">
                <i class="fas fa-headset fa-3x mb-3" style="color: var(--primary-blue);"></i>
                <p class="mb-2"><strong>Need assistance?</strong></p>
                <p>Contact our support team at <a href="mailto:support@mabanga.com" style="color: var(--primary-blue);">support@mabanga.com</a></p>
                <p>Or call us at: +1 234 567 890</p>
                <p class="mt-2"><small>Operating Hours: 08:00 - 22:00</small></p>
            </div>
        `;
        new Modal({ title: 'Help & Support', content: content }).show();
    }

    showAbout() {
        const content = `
            <div class="about-content text-center p-3">
                <div class="logo mb-3" style="justify-content: center; font-size: 2rem;">Mabanga<span>Express</span></div>
                <p class="mb-2"><strong>Version 1.0.0</strong></p>
                <p>Your reliable delivery partner for everything from gadgets to groceries.</p>
                <p class="mt-3 text-muted" style="color: #999;"><small>&copy; ${new Date().getFullYear()} Mabanga Express. All rights reserved.</small></p>
            </div>
        `;
        new Modal({ title: 'About Us', content: content }).show();
    }

    trackOrder() {
        if (this.customerManager) {
            this.customerManager.promptTrack();
        }
    }

    showConfirm(message, title = 'Confirmation') {
        return new Promise((resolve) => {
            const content = `
                <div class="confirm-modal-content">
                    <p class="mb-3">${message}</p>
                    <div class="form-actions" style="justify-content: flex-end;">
                        <button class="btn-secondary" data-action="cancel" style="flex: 0 0 auto; width: auto; padding: 10px 20px;">Cancel</button>
                        <button class="btn-primary" data-action="confirm" style="flex: 0 0 auto; width: auto; padding: 10px 20px;">Confirm</button>
                    </div>
                </div>
            `;
            const modalInstance = new Modal({ title: title, content: content });
            const modal = modalInstance.show();

            const closeBtn = modal.querySelector('.close-btn');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => resolve(false));
            }

            modal.addEventListener('click', (e) => {
                if (e.target.closest('[data-action="confirm"]')) {
                    modalInstance.close();
                    resolve(true);
                } else if (e.target.closest('[data-action="cancel"]')) {
                    modalInstance.close();
                    resolve(false);
                }
            });
        });
    }

    showPrompt(message, placeholder = '', title = 'Input Required') {
        return new Promise((resolve) => {
            const content = `
                <div class="prompt-modal-content">
                    <p class="mb-2">${message}</p>
                    <div class="form-group">
                        <input type="text" id="prompt-input" placeholder="${placeholder}">
                    </div>
                    <div class="form-actions" style="justify-content: flex-end;">
                        <button class="btn-secondary" data-action="cancel" style="flex: 0 0 auto; width: auto; padding: 10px 20px;">Cancel</button>
                        <button class="btn-primary" data-action="confirm" style="flex: 0 0 auto; width: auto; padding: 10px 20px;">Submit</button>
                    </div>
                </div>
            `;
            const modalInstance = new Modal({ title: title, content: content });
            const modal = modalInstance.show();
            const input = modal.querySelector('#prompt-input');
            if (input) {
                input.focus();
                input.addEventListener('keydown', (e) => {
                    if (e.key === 'Enter') {
                        modalInstance.close();
                        resolve(input.value);
                    }
                });
            }

            const closeBtn = modal.querySelector('.close-btn');
            if (closeBtn) closeBtn.addEventListener('click', () => resolve(null));

            modal.addEventListener('click', (e) => {
                if (e.target.closest('[data-action="confirm"]')) {
                    modalInstance.close();
                    resolve(input ? input.value : '');
                } else if (e.target.closest('[data-action="cancel"]')) {
                    modalInstance.close();
                    resolve(null);
                }
            });
        });
    }

    getErrorHTML(message) {
        return `
            <div class="error-container">
                <div class="error-message">
                    <i class="fas fa-exclamation-triangle"></i>
                    <h3>Something went wrong</h3>
                    <p>${message}</p>
                    <button class="btn-primary" onclick="window.location.reload()">Reload Page</button>
                </div>
            </div>
        `;
    }

    showError(message) {
        console.error('App Error:', message);
    }
}

class AppNotificationManager {
    constructor(app) {
        this.app = app;
        this.pollingInterval = 30000; // 30 seconds
        this.pollTimer = null;
        this.notifications = [];
    }

    startPolling() {
        if (!this.app.currentUser) return;
        this.stopPolling();
        this.fetchNotifications();
        this.pollTimer = setInterval(() => this.fetchNotifications(), this.pollingInterval);
        console.log('Notification polling started.');
    }

    stopPolling() {
        clearInterval(this.pollTimer);
        this.pollTimer = null;
        console.log('Notification polling stopped.');
    }

    clearNotifications() {
        this.notifications = [];
        this.updateBadge();
    }

    async fetchNotifications() {
        if (!this.app.currentUser) {
            this.stopPolling();
            return;
        }
        try {
            const response = await fetch('api/notifications/list.php');
            const result = await response.json();
            if (result.success) {
                this.notifications = result.notifications;
                this.updateBadge();
            }
        } catch (error) {
            console.error('Error fetching notifications:', error);
        }
    }

    updateBadge() {
        const badge = document.querySelector('#notifications-btn .notification-badge');
        if (!badge) return;

        const count = this.notifications.length;
        badge.textContent = count;
        badge.style.display = count > 0 ? 'flex' : 'none';
    }

    toggleNotificationList() {
        let list = document.querySelector('.notification-list');
        if (list) {
            list.remove();
            return;
        }

        list = document.createElement('div');
        list.className = 'notification-list';

        if (this.notifications.length > 0) {
            list.innerHTML = this.notifications.map(n => `
                <div class="notification-item" data-id="${n.id}">
                    <p>${n.message}</p>
                    <small>${new Date(n.created_at).toLocaleString()}</small>
                </div>
            `).join('');
        } else {
            list.innerHTML = '<div class="notification-item empty">No new notifications</div>';
        }

        document.body.appendChild(list);
        this.markAsRead();
    }

    async markAsRead() {
        const unreadIds = this.notifications.map(n => n.id);
        if (unreadIds.length === 0) return;

        // Optimistically update UI
        this.notifications = [];
        this.updateBadge();

        try {
            await fetch('api/notifications/mark_read.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ids: unreadIds })
            });
        } catch (error) {
            console.error('Failed to mark notifications as read:', error);
        }
    }
}

// Initialize the app when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    // The app is now initialized by the script tag in index.php
});