(function() {
    // Determine path prefix for admin pages
    const isAdminPage = window.location.pathname.includes('/admin/');
    const pathPrefix = isAdminPage ? '../' : '';

    // Create a style element for any dynamic styling
    const style = document.createElement('style');
    style.innerHTML = `
        body { padding-top: 76px; }
        .btn-xs { padding: 0.25rem 0.4rem; font-size: 0.75rem; border-radius: 0.2rem; }
    `;
    document.head.appendChild(style);

    // Run session check
    fetch(pathPrefix + 'api/session_check.php')
        .then(res => res.json())
        .then(data => {
            if (!data.is_logged_in) {
                // Redirect to login if not logged in
                window.location.href = pathPrefix + 'login.html?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                return;
            }

            // Expose session globally
            window.AuthSession = data;
            
            // Dispatch event when session is ready
            const event = new CustomEvent('auth-ready', { detail: data });
            window.dispatchEvent(event);

            // Render shared layouts
            renderHeader(data, pathPrefix);
            renderFooter(data);
        })
        .catch(err => {
            console.error('Auth verification failed', err);
        });

    function renderHeader(data, prefix) {
        const header = document.querySelector('header');
        if (!header) return;

        const siteName = data.site_name;
        const logoUrl = data.logo_url;
        const logoHtml = logoUrl 
            ? `<img src="${logoUrl}" alt="Logo" class="d-inline-block align-top me-2" style="height: 32px; max-width: 150px; object-fit: contain;">` 
            : `<i class="bi bi-calendar-event-fill me-2 text-primary"></i>`;
        
        const siteNameSpan = (!logoUrl || !data.hide_site_name) ? `<span class="fw-bold text-dark">${siteName}</span>` : '';
        
        const unreadBadge = data.unread_notifications > 0 
            ? `<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger border border-white" style="font-size: 0.65rem;">${data.unread_notifications}</span>` 
            : '';

        const role = data.user.role;
        const username = data.user.username;
        const userAvatarUrl = data.user.profile_picture_url 
            ? prefix + data.user.profile_picture_url 
            : 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=random';

        // Construct Admin Navigation items
        let adminNavHtml = '';
        if (role === 'admin') {
            adminNavHtml = `
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle text-dark" href="#" id="adminDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-sliders me-1"></i> Administration
                    </a>
                    <ul class="dropdown-menu shadow border-0 mt-2" aria-labelledby="adminDropdown">
                        <li><a class="dropdown-item py-2 px-3 rounded" href="${prefix}admin/users.html"><i class="bi bi-people-fill text-primary me-2"></i>User Management</a></li>
                        <li><a class="dropdown-item py-2 px-3 rounded" href="${prefix}admin/designations.html"><i class="bi bi-award-fill text-warning me-2"></i>Designations</a></li>
                        <li><a class="dropdown-item py-2 px-3 rounded" href="${prefix}admin/payouts.html"><i class="bi bi-cash-coin text-success me-2"></i>Payout Approvals</a></li>
                        <li><a class="dropdown-item py-2 px-3 rounded" href="${prefix}reports.html"><i class="bi bi-bar-chart-line-fill text-info me-2"></i>System Reports</a></li>
                        <li><a class="dropdown-item py-2 px-3 rounded" href="${prefix}admin/notifications.html"><i class="bi bi-bell-fill text-danger me-2"></i>Notifications Admin</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item py-2 px-3 rounded" href="${prefix}admin/settings.html"><i class="bi bi-gear-fill text-secondary me-2"></i>System Settings</a></li>
                    </ul>
                </li>
            `;
        } else if (role === 'organizer') {
            adminNavHtml = `
                <li class="nav-item">
                    <a class="nav-link text-dark" href="${prefix}reports.html">
                        <i class="bi bi-bar-chart-line me-1"></i> Event Analytics
                    </a>
                </li>
            `;
        } else if (role === 'user') {
            adminNavHtml = `
                <li class="nav-item">
                    <a class="nav-link text-dark" href="${prefix}team.html">
                        <i class="bi bi-people-fill me-1"></i> My Team
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-dark" href="${prefix}reports.html">
                        <i class="bi bi-bar-chart-line me-1"></i> My Earnings
                    </a>
                </li>
            `;
        } else if (role === 'speaker' || role === 'sponsor') {
            adminNavHtml = `
                <li class="nav-item">
                    <a class="nav-link text-dark" href="${prefix}profile.html">
                        <i class="bi bi-person-badge me-1"></i> My Profile
                    </a>
                </li>
            `;
        }

        header.innerHTML = `
            <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom shadow-sm py-3 fixed-top">
                <div class="container-fluid px-md-5">
                    <a class="navbar-brand d-flex align-items-center" href="${prefix}dashboard.html">
                        ${logoHtml}
                        ${siteNameSpan}
                    </a>
                    
                    <div class="d-flex align-items-center gap-2 gap-sm-3 order-lg-last ms-auto me-2 me-lg-0">
                        <!-- Notification Bell -->
                        <div class="dropdown">
                            <button class="btn btn-light position-relative p-2 rounded-circle border-0 d-flex align-items-center justify-content-center" type="button" id="bellDropdown" data-bs-toggle="dropdown" aria-expanded="false" style="width: 40px; height: 40px;">
                                <i class="bi bi-bell-fill fs-5 text-secondary"></i>
                                ${unreadBadge}
                            </button>
                            <div class="dropdown-menu dropdown-menu-end shadow-lg border-0 mt-2 p-0" aria-labelledby="bellDropdown" style="width: 320px; z-index: 1050;" id="bell-dropdown-container">
                                <div class="p-3 bg-light border-bottom d-flex justify-content-between align-items-center rounded-top">
                                    <span class="fw-bold text-dark small">Inbox Notifications</span>
                                    <a href="${prefix}notifications.html" class="text-primary text-decoration-none small fw-semibold" style="font-size: 0.75rem;">View All</a>
                                </div>
                                <div class="list-group list-group-flush" id="bell-notifications-list" style="max-height: 280px; overflow-y: auto;">
                                    <div class="text-center py-4 text-muted">
                                        <div class="spinner-border spinner-border-sm text-secondary" role="status"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- User Profile Dropdown -->
                        <div class="dropdown">
                            <button class="btn btn-light d-flex align-items-center gap-2 px-3 py-1.5 border rounded-pill shadow-sm" type="button" id="userMenuDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                <img src="${userAvatarUrl}" class="rounded-circle border" style="width: 24px; height: 24px; object-fit: cover;">
                                <span class="d-none d-sm-inline fw-semibold text-secondary small">${username}</span>
                                <i class="bi bi-chevron-down small text-muted" style="font-size: 0.75rem;"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2 p-2" aria-labelledby="userMenuDropdown">
                                <li>
                                    <a class="dropdown-item d-flex align-items-center gap-2 rounded" href="${prefix}profile.html">
                                        <i class="bi bi-person-badge text-primary"></i> My Profile
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item d-flex align-items-center gap-2 rounded" href="${prefix}kyc.html">
                                        <i class="bi bi-shield-check text-primary"></i> KYC Verification
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item d-flex align-items-center gap-2 rounded" href="${prefix}payouts.html">
                                        <i class="bi bi-cash-stack text-success"></i> Withdraw Payout
                                    </a>
                                </li>
                                <li><hr class="dropdown-divider"></li>
                                <li>
                                    <a class="dropdown-item text-danger d-flex align-items-center gap-2 rounded" href="${prefix}logout.php">
                                        <i class="bi bi-box-arrow-right"></i> Log Out
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>

                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    
                    <div class="collapse navbar-collapse" id="navbarContent">
                        <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
                            <li class="nav-item">
                                <a class="nav-link text-dark" href="${prefix}dashboard.html">
                                    <i class="bi bi-speedometer2 me-1"></i> Dashboard
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-dark" href="${prefix}public_events.html">
                                    <i class="bi bi-calendar-check me-1"></i> Start Here
                                </a>
                            </li>
                            ${adminNavHtml}
                        </ul>
                    </div>
                </div>
            </nav>
        `;

        // Fetch bell notifications on dropdown toggle
        const bellBtn = document.getElementById('bellDropdown');
        bellBtn.addEventListener('show.bs.dropdown', function () {
            fetch(prefix + 'api/notifications_data.php?limit=5')
                .then(res => res.json())
                .then(notifData => {
                    const list = document.getElementById('bell-notifications-list');
                    list.innerHTML = '';
                    if (!notifData.notifications || notifData.notifications.length === 0) {
                        list.innerHTML = '<div class="text-center py-4 text-muted small">No notifications yet</div>';
                        return;
                    }
                    notifData.notifications.forEach(n => {
                        list.innerHTML += `
                            <a href="${prefix}notifications.html" class="list-group-item list-group-item-action p-3 border-bottom border-light">
                                <div class="d-flex justify-content-between align-items-start">
                                    <h6 class="mb-1 fw-bold text-dark small text-truncate" style="max-width: 200px;">${n.title}</h6>
                                    <small class="text-muted" style="font-size: 0.65rem;">${new Date(n.created_at).toLocaleDateString()}</small>
                                </div>
                                <p class="mb-0 text-secondary small text-truncate" style="font-size: 0.75rem;">${n.message}</p>
                            </a>
                        `;
                    });
                });
        });
    }

    function renderFooter(data) {
        const footer = document.querySelector('footer');
        if (!footer) return;

        footer.innerHTML = `
            <div class="container-fluid px-md-5 py-4 bg-white border-top mt-auto">
                <div class="row align-items-center justify-content-between g-3">
                    <div class="col-12 col-md-auto text-center text-md-start">
                        <span class="text-secondary small">&copy; 2026 <strong>${data.site_name}</strong>. All rights reserved.</span>
                    </div>
                    <div class="col-12 col-md-auto text-center text-md-end">
                        <a href="terms.php" class="text-secondary text-decoration-none small me-3">Terms of Service</a>
                        <a href="privacy.php" class="text-secondary text-decoration-none small">Privacy Policy</a>
                    </div>
                </div>
            </div>
        `;
    }
})();
