// Standard CNPERP Bootstrap Navbar System - Clean & Crisp
// SINGLE SOURCE OF TRUTH - This file should be copied to static/js/navbar.js when modified
// To sync: Copy-Item "app\static\js\navbar.js" "static\js\navbar.js" -Force
console.log('📋 navbar.js loaded - version 20260601');

// Ensure shared UI assets are loaded everywhere navbar.js is used
(function ensureSharedAssets() {
	const head = document.head || document.getElementsByTagName('head')[0];
	if (!head) return;

	function addLink(id, href) {
		if (document.getElementById(id)) return;
		const link = document.createElement('link');
		link.id = id;
		link.rel = 'stylesheet';
		link.href = href;
		head.appendChild(link);
	}

	function addScript(id, src) {
		if (document.getElementById(id)) return;
		const script = document.createElement('script');
		script.id = id;
		script.src = src;
		head.appendChild(script);
	}

	addLink('css-spacing-utils', '/static/css/spacing.css');
	addLink('css-breadcrumbs', '/static/css/components/breadcrumbs.css');
	addScript('js-theme-manager', '/static/js/theme-manager.js');
	addScript('js-loading-spinner', '/static/js/loading.js');
	addScript('js-breadcrumbs', '/static/js/breadcrumb.js');
	addScript('js-global-search', '/static/js/global-search.js');
})();

// Global logout handler - explicitly attach to window object
window.handleLogoutClick = function () {
	console.log('🔴 Logout button clicked');
	// Redirect to logout page
	window.location.href = '/static/logout.html';
};

function createNavbar(currentPage = 'dashboard') {
	// Check user role from localStorage
	const user = JSON.parse(localStorage.getItem('user') || '{}');
	const role = (user.role || '').toLowerCase();

	// POS users should NOT see the navbar - return empty string
	if (role === 'pos_user' || role === 'cashier') {
		console.log('🔒 POS user detected - navbar hidden');
		return '';
	}

	const navbarHtml = `
	<style>
		/* Clean Bootstrap Navbar Styling */
		.cnperp-navbar {
			/* Use the purchases.html gradient globally for consistency */
			background: linear-gradient(135deg, #0d6efd, #0056b3) !important;
			box-shadow: 0 2px 4px rgba(0,0,0,0.1);
			position: fixed !important;
			top: 0 !important;
			left: 0 !important;
			right: 0 !important;
			z-index: 1030 !important;
			width: 100% !important;
		}
		.cnperp-navbar .navbar-brand {
			display: flex;
			align-items: center;
			font-weight: 600;
			font-size: 0.85rem; /* reduced brand size */
			color: white !important;
			margin-right: 0.3rem;
			padding: 0.4rem 0.3rem !important;
		}
		.cnperp-navbar .navbar-brand img.navbar-brand-logo {
			height: 36px;
			width: auto;
			max-width: 160px;
			display: inline-block;
			object-fit: contain;
		}
		.cnperp-navbar .nav-link {
			color: rgba(255, 255, 255, 0.95) !important;
			font-weight: 500;
			padding: 0.4rem 0.4rem !important; /* reduced padding */
			white-space: nowrap;
			font-size: 0.8rem; /* reduced link size */
		}
		.cnperp-navbar .nav-link:hover {
			color: white !important;
			background-color: rgba(255, 255, 255, 0.1);
			border-radius: 4px;
		}
		.cnperp-navbar .navbar-nav {
			gap: 0.25rem; /* small consistent spacing between items */
		}
		.cnperp-navbar .navbar-nav.me-auto {
			/* Move navbar items 4cm to the right (neutralize previous -4cm) */
			margin-left: 0cm !important;
		}
		.cnperp-navbar .navbar-nav.ms-auto {
			margin-left: auto !important;
		}
		.cnperp-navbar .navbar-nav.me-auto .nav-item:first-child {
			display: none;
		}
		/* User Info Display Styles */
		.user-info-display {
			color: rgba(255, 255, 255, 0.95) !important;
			font-size: 0.75rem;
			padding: 0.3rem 0.6rem;
			margin-right: 0.5rem;
			border-right: 1px solid rgba(255, 255, 255, 0.2);
		}
		.user-info-display .info-label {
			font-weight: 600;
			margin-right: 0.25rem;
		}
		.user-info-display .info-value {
			font-weight: 400;
		}
		.user-info-display i {
			margin-right: 0.25rem;
			font-size: 0.85rem;
		}
		.cnperp-navbar .nav-link i {
			font-size: 0.75rem; /* reduced icon size */
			margin-right: 0.25rem;
		}
		.cnperp-navbar .dropdown-menu {
			border: none;
			box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.15);
			border-radius: 0.375rem;
			font-size: 0.85rem; /* reduced dropdown text */
		}
		.cnperp-navbar .dropdown-item {
			padding: 0.4rem 0.8rem; /* reduced dropdown padding */
		}
		.cnperp-navbar .dropdown-item:hover {
			background-color: #f8f9fa;
			color: #0d6efd;
		}
		.cnperp-navbar .dropdown-item i {
			width: 20px;
			margin-right: 0.5rem;
		}
		/* Ensure navbar doesn't wrap */
		.cnperp-navbar .navbar-collapse {
			flex-wrap: nowrap;
		}
		.cnperp-navbar .container-fluid {
			padding-left: 0.5rem;
			padding-right: 0.5rem;
		}
	</style>

	<nav class="navbar navbar-expand-lg navbar-dark cnperp-navbar">
		<div class="container-fluid">
			<a class="navbar-brand" href="/static/index.html">
				<img src="/static/images/cnp-solutions-logo.jpg" alt="CNP Solutions" class="navbar-brand-logo" />
			</a>

			<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarMain">
				<span class="navbar-toggler-icon"></span>
			</button>

			<div class="collapse navbar-collapse" id="navbarMain">
				<ul class="navbar-nav me-auto">
					<li class="nav-item">
						<a class="nav-link" href="/static/index.html">
							<i class="bi bi-speedometer2 me-1"></i>Dashboard
						</a>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-cart-check me-1"></i>POS
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/pos.html"><i class="bi bi-cart-plus"></i>Point of Sale</a></li>
							<li><a class="dropdown-item" href="/static/pos-reconciliation.html?v=20260602"><i class="bi bi-cash-stack"></i>POS Reconciliation</a></li>
						</ul>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-cart me-1"></i>Sales
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/sales.html"><i class="bi bi-cash-coin"></i>Sales</a></li>
							<li><a class="dropdown-item" href="/static/customers.html"><i class="bi bi-people"></i>Customers</a></li>
							<li><a class="dropdown-item" href="/static/invoices.html"><i class="bi bi-receipt"></i>Invoices</a></li>
							<li><a class="dropdown-item" href="/static/quotations.html"><i class="bi bi-file-text"></i>Quotations</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><h6 class="dropdown-header">Jobs &amp; invoicing</h6></li>
							<li><a class="dropdown-item" href="/static/job-sales-queue.html?tab=pending"><i class="bi bi-hourglass-split"></i>Pending Jobs</a></li>
							<li><a class="dropdown-item" href="/static/job-sales-queue.html?tab=ready"><i class="bi bi-receipt-cutoff"></i>Jobs Ready to Invoice</a></li>
							<li><a class="dropdown-item" href="/static/job-cards.html"><i class="bi bi-card-checklist"></i>All Job Cards</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/credit-notes.html?v=20260602"><i class="bi bi-file-minus"></i>Credit Notes</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/billing.html"><i class="bi bi-calendar-check"></i>Billing & Recurring</a></li>
							<li><a class="dropdown-item" href="/static/branch-sales.html"><i class="bi bi-graph-up-arrow"></i>Branch Sales</a></li>
							<li><a class="dropdown-item" href="/static/sales-reports.html"><i class="bi bi-graph-up"></i>Sales Reports</a></li>
						</ul>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-box me-1"></i>Inventory
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/products.html"><i class="bi bi-box-seam"></i>Products</a></li>
							<li><a class="dropdown-item" href="/static/recipes.html?v=20260602"><i class="bi bi-journal-text"></i>Recipes/BOM</a></li>
							<li><a class="dropdown-item" href="/static/serial-numbers.html?v=20260602"><i class="bi bi-upc-scan"></i>Serial Numbers</a></li>
							<li><a class="dropdown-item" href="/static/traceability.html?v=20260602"><i class="bi bi-diagram-3"></i>Product Traceability</a></li>
							<li><a class="dropdown-item" href="/static/inventory-allocation.html"><i class="bi bi-distribution-vertical"></i>Inventory Allocation</a></li>
							<li><a class="dropdown-item" href="/static/uom-management.html?v=20260602"><i class="bi bi-rulers"></i>Units of Measure</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/cogs.html?v=20260602"><i class="bi bi-calculator"></i>COGS Management</a></li>
							<li><a class="dropdown-item" href="/static/inventory-reports.html"><i class="bi bi-graph-up"></i>Inventory Reports</a></li>
							<li><a class="dropdown-item" href="/static/cogs-reports.html"><i class="bi bi-file-bar-graph"></i>COGS Reports</a></li>
						</ul>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-truck me-1"></i>Purchases
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/purchases.html"><i class="bi bi-truck"></i>Purchases</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/purchase-orders.html"><i class="bi bi-cart-check"></i>Purchase Orders</a></li>
							<li><a class="dropdown-item" href="/static/suppliers.html"><i class="bi bi-building"></i>Suppliers</a></li>
							<li><a class="dropdown-item" href="/static/receipts.html"><i class="bi bi-inbox"></i>Receipts</a></li>
							<li><a class="dropdown-item" href="/static/purchase-payments.html"><i class="bi bi-credit-card"></i>Payments</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/procurement.html"><i class="bi bi-clipboard-check"></i>Procurement</a></li>
							<li><a class="dropdown-item" href="/static/landed-costs.html"><i class="bi bi-ship"></i>Landed Costs</a></li>
							<li><a class="dropdown-item" href="/static/purchase-reports.html"><i class="bi bi-graph-up"></i>Purchase Reports</a></li>
						</ul>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-building me-1"></i>Assets
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/asset-management.html"><i class="bi bi-buildings"></i>Asset Management</a></li>
							<li><a class="dropdown-item" href="/static/asset.html"><i class="bi bi-building-check"></i>Fixed Assets</a></li>
						</ul>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-bank me-1"></i>Banking
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/bank-accounts.html"><i class="bi bi-bank"></i>Bank Accounts</a></li>
							<li><a class="dropdown-item" href="/static/bank-transactions.html"><i class="bi bi-receipt-cutoff"></i>Transactions</a></li>
							<li><a class="dropdown-item" href="/static/bank-transfers.html"><i class="bi bi-arrow-left-right"></i>Transfers</a></li>
							<li><a class="dropdown-item" href="/static/bank-reconciliations.html"><i class="bi bi-check2-square"></i>Reconciliations</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/cash-submissions.html"><i class="bi bi-cash-stack"></i>Cash Submissions</a></li>
							<li><a class="dropdown-item" href="/static/float-allocations.html"><i class="bi bi-wallet2"></i>Float Allocations</a></li>
							<li><a class="dropdown-item" href="/static/banking-reports.html"><i class="bi bi-graph-up"></i>Banking Reports</a></li>
							<li><a class="dropdown-item" href="/static/cash-reports.html"><i class="bi bi-file-earmark-text"></i>Cash Reports</a></li>
						</ul>
					</li>

					<!-- VAT quick access (pulled out of Accounting so it appears everywhere) -->
					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-receipt-cutoff me-1"></i>VAT
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/vat-reports.html"><i class="bi bi-percent"></i>VAT Reports</a></li>
							<li><a class="dropdown-item" href="/static/vat-reconciliations.html"><i class="bi bi-check2-circle"></i>VAT Reconciliations</a></li>
						</ul>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-calculator me-1"></i>Accounting
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/accounting-codes.html"><i class="bi bi-diagram-3"></i>Chart of Accounts</a></li>
							<li><a class="dropdown-item" href="/static/accounting-codes-dimensional.html"><i class="bi bi-diagram-3"></i>Dimensional Accounting Codes</a></li>
							<li><a class="dropdown-item" href="/static/journal-entries.html"><i class="bi bi-journal-text"></i>Journal Entries</a></li>						<li><a class="dropdown-item" href="/static/payments.html"><i class="bi bi-credit-card-2-front"></i>Payments</a></li>							<li><a class="dropdown-item" href="/static/ledgers.html"><i class="bi bi-book"></i>General Ledger</a></li>
							<li><a class="dropdown-item" href="/static/accounting-dimensions.html"><i class="bi bi-grid-3x3"></i>Accounting Dimensions</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/fiscal-periods.html"><i class="bi bi-calendar-range"></i>Fiscal Period Management</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/vat-reports.html"><i class="bi bi-percent"></i>VAT Reports</a></li>
							<li><a class="dropdown-item" href="/static/vat-reconciliations.html"><i class="bi bi-check2-circle"></i>VAT Reconciliations</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/budgeting.html"><i class="bi bi-graph-up-arrow"></i>Budgeting</a></li>
							<li><a class="dropdown-item" href="/static/financial-reports.html"><i class="bi bi-file-earmark-bar-graph"></i>Financial Reports</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/notifications.html?v=20260602"><i class="bi bi-bell"></i>Notifications & Approvals</a></li>
						</ul>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-tools me-1"></i>Manufacturing
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/manufacturing.html?v=20260602"><i class="bi bi-gear"></i>Production Orders</a></li>
							<li><a class="dropdown-item" href="/static/job-cards.html"><i class="bi bi-card-checklist"></i>Job Cards</a></li>
							<li><a class="dropdown-item" href="/static/recipes.html?v=20260602"><i class="bi bi-journal-text"></i>Recipes/BOM</a></li>
						</ul>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-graph-up me-1"></i>Reports
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/reports.html?v=20260602"><i class="bi bi-file-earmark-bar-graph"></i>All Reports</a></li>
							<li><a class="dropdown-item" href="/static/dimensional-reports.html"><i class="bi bi-grid-3x3"></i>Dimensional Reports <span class="badge bg-success badge-sm ms-1">New</span></a></li>
							<li><a class="dropdown-item" href="/static/financial-reports.html"><i class="bi bi-cash-coin"></i>Financial Reports</a></li>
							<li><a class="dropdown-item" href="/static/management-reports.html"><i class="bi bi-briefcase"></i>Management Reports</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/sales-reports.html"><i class="bi bi-cart"></i>Sales Reports</a></li>
							<li><a class="dropdown-item" href="/static/purchase-reports.html"><i class="bi bi-truck"></i>Purchase Reports</a></li>
							<li><a class="dropdown-item" href="/static/inventory-reports.html"><i class="bi bi-box"></i>Inventory Reports</a></li>
							<li><a class="dropdown-item" href="/static/customer-reports.html"><i class="bi bi-people"></i>Customer Reports</a></li>
							<li><a class="dropdown-item" href="/static/invoice-reports.html"><i class="bi bi-receipt"></i>Invoice Reports</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/business-intelligence.html"><i class="bi bi-bar-chart"></i>Business Intelligence</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/period-reports.html"><i class="bi bi-clock-history me-1"></i>Historical Reports &amp; Year-End Close <span class="badge bg-primary badge-sm ms-1">New</span></a></li>
						</ul>
					</li>

					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-gear-fill me-1"></i>Settings
						</a>
						<ul class="dropdown-menu">
							<li><a class="dropdown-item" href="/static/settings.html"><i class="bi bi-sliders"></i>System Settings</a></li>
							<li><a class="dropdown-item" href="/static/settings.html#app-updates-settings"><i class="bi bi-download"></i>Software Updates</a></li>
							<li><a class="dropdown-item" href="/static/admin-panel.html"><i class="bi bi-shield-lock"></i>Admin Panel</a></li>
							<li><a class="dropdown-item" href="/static/logs-viewer.html"><i class="bi bi-file-text"></i>System Logs <span class="badge bg-success badge-sm ms-1">New</span></a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/users.html"><i class="bi bi-person"></i>Users</a></li>
							<li><a class="dropdown-item" href="/static/branches.html"><i class="bi bi-building"></i>Branches</a></li>
							<li><a class="dropdown-item" href="/static/user-permissions.html"><i class="bi bi-key"></i>User Permissions</a></li>
							<li><a class="dropdown-item" href="/static/role-management.html"><i class="bi bi-person-badge"></i>Role Management</a></li>
							<li><a class="dropdown-item" href="/static/permission-matrix.html"><i class="bi bi-grid"></i>Permission Matrix</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/invoice-customization.html?v=20260602"><i class="bi bi-brush"></i>Invoice Customization</a></li>
							<li><a class="dropdown-item" href="/static/invoice-designer.html?v=20260603"><i class="bi bi-palette"></i>Invoice Designer</a></li>
							<li><a class="dropdown-item" href="/static/invoice-printer-settings.html"><i class="bi bi-printer"></i>Print Settings</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/backup-management.html"><i class="bi bi-cloud-upload"></i>Backup Management</a></li>
							<li><a class="dropdown-item" href="/static/excel-templates.html?v=20260602"><i class="bi bi-file-excel"></i>Excel Templates</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/help-center.html"><i class="bi bi-question-circle"></i>Help Center</a></li>
						</ul>
					</li>
				</ul>

				<ul class="navbar-nav ms-auto">
					<!-- Notification Bell -->
					<li class="nav-item dropdown me-2" id="notification-dropdown">
						<a class="nav-link position-relative" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false" id="notificationBell" title="Notifications">
							<i class="bi bi-bell fs-5"></i>
							<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" id="notification-badge" style="display: none; font-size: 0.65rem;">0</span>
						</a>
						<div class="dropdown-menu dropdown-menu-end shadow" style="min-width: 350px; max-height: 400px; overflow-y: auto;" id="notification-menu">
							<div class="d-flex justify-content-between align-items-center px-3 py-2 border-bottom">
								<h6 class="mb-0"><i class="bi bi-bell me-1"></i>Notifications</h6>
								<button class="btn btn-link btn-sm p-0 text-decoration-none" id="mark-all-read-btn" title="Mark all as read">
									<i class="bi bi-check-all"></i> Mark all read
								</button>
							</div>
							<div id="notification-list">
								<div class="text-center py-4 text-muted">
									<i class="bi bi-inbox fs-3 d-block mb-2"></i>
									<small>Loading notifications...</small>
								</div>
							</div>
							<div class="border-top px-3 py-2 text-center">
								<a href="/static/notifications.html" class="text-decoration-none small">View all notifications</a>
							</div>
						</div>
					</li>

					<!-- Pending Approvals -->
					<li class="nav-item dropdown me-2" id="approvals-dropdown">
						<a class="nav-link position-relative" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false" id="approvalsBell" title="Pending Approvals">
							<i class="bi bi-clipboard-check fs-5"></i>
							<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-warning text-dark" id="approvals-badge" style="display: none; font-size: 0.65rem;">0</span>
						</a>
						<div class="dropdown-menu dropdown-menu-end shadow" style="min-width: 350px; max-height: 400px; overflow-y: auto;" id="approvals-menu">
							<div class="d-flex justify-content-between align-items-center px-3 py-2 border-bottom">
								<h6 class="mb-0"><i class="bi bi-clipboard-check me-1"></i>Pending Approvals</h6>
							</div>
							<div id="approvals-list">
								<div class="text-center py-4 text-muted">
									<i class="bi bi-check-circle fs-3 d-block mb-2"></i>
									<small>No pending approvals</small>
								</div>
							</div>
						</div>
					</li>

					<!-- Help Dropdown (moved to right group) -->
					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-question-circle me-1"></i>Help
						</a>
						<ul class="dropdown-menu dropdown-menu-end">
							<li><a class="dropdown-item" href="/DIMENSIONAL_BALANCES_README.md" target="_blank"><i class="bi bi-book"></i>Dimensional Balances Guide</a></li>
							<li><a class="dropdown-item" href="/static/help-center.html"><i class="bi bi-life-preserver"></i>Help Center</a></li>
							<li><a class="dropdown-item" href="/static/documentation.html"><i class="bi bi-file-text"></i>Documentation</a></li>
							<li><a class="dropdown-item" href="/static/help/client-server-setup.html"><i class="bi bi-server"></i>Client-Server Setup Guide</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="/static/keyboard-shortcuts.html"><i class="bi bi-keyboard"></i>Keyboard Shortcuts</a></li>
							<li><a class="dropdown-item" href="/static/tutorials.html"><i class="bi bi-play-circle"></i>Video Tutorials</a></li>
							<li><a class="dropdown-item" href="/static/faq.html"><i class="bi bi-chat-left-dots"></i>FAQ</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="#" onclick="alert('Version: 20250127120000\n\nSystem: CNPERP Accounting - Dimensional Module\n\nBuild: Production'); return false;"><i class="bi bi-info-circle"></i>About</a></li>
							<li><a class="dropdown-item" href="/static/contact-support.html"><i class="bi bi-envelope"></i>Contact Support</a></li>
						</ul>
					</li>
					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">
							<i class="bi bi-person-circle me-1"></i>User
						</a>
						<ul class="dropdown-menu dropdown-menu-end">
							<li><a class="dropdown-item" href="#"><i class="bi bi-person"></i>Profile</a></li>
							<li><a class="dropdown-item" href="#"><i class="bi bi-gear"></i>Settings</a></li>
							<li><hr class="dropdown-divider"></li>
							<li><a class="dropdown-item" href="#" onclick="handleLogoutClick(); return false;"><i class="bi bi-box-arrow-right"></i>Logout</a></li>
						</ul>
					</li>
				</ul>
			</div>
		</div>
	</nav>
	`;

	return navbarHtml;
}

// Session panel removed from navbar (will be replaced later). Keep hook for callers.
function updateUserSessionInfo() {
	// no-op
}

// Helper function to fetch branch details from API
async function fetchBranchDetails(branchId) {
	try {
		const headers = window.auth && window.auth.authHeader ? window.auth.authHeader() : {};
		const response = await fetch(`/api/v1/branches/${branchId}`, { headers });
		if (response.ok) {
			return await response.json();
		}
	} catch (error) {
		console.error('Error fetching branch details:', error);
	}
	return null;
}

// Load navbar on page load
document.addEventListener('DOMContentLoaded', function () {
	// Try both navbar-container (new standard) and navbar-placeholder (legacy)
	const navbarContainer = document.getElementById('navbar-container') || document.getElementById('navbar-placeholder');
	if (navbarContainer) {
		navbarContainer.innerHTML = createNavbar();
		console.log('✅ Clean Bootstrap navbar loaded successfully');

		// Add logout handler after navbar is loaded
		setTimeout(() => {
			const logoutLinks = document.querySelectorAll('a[href="/static/logout.html"]');
			logoutLinks.forEach(link => {
				link.addEventListener('click', function (e) {
					e.preventDefault();
					console.log('🔴 Logout clicked - redirecting...');
					window.location.href = '/static/logout.html';
				});
			});

			// Update user session information
			updateUserSessionInfo();
			// Update session time every minute
			setInterval(updateUserSessionInfo, 60000);

			// Initialize notification system
			initNotificationSystem();
		}, 100);
	} else {
		console.error('❌ No navbar container found! Looking for #navbar-container or #navbar-placeholder');
	}
});

// ========== Notification System ==========

function initNotificationSystem() {
	const authSource = window.auth || window.authBootstrap;
	if (!authSource || !authSource.isAuthenticated()) {
		console.debug('[navbar] Not authenticated, skipping notification setup');
		return;
	}

	// Initial load with alert for pending approvals
	loadNotificationSummary();
	loadPendingApprovals(true); // true = show alert if pending

	// Setup periodic refresh (every 60 seconds)
	setInterval(() => {
		loadNotificationSummary();
		loadPendingApprovals(false);
	}, 60000);

	// Setup event handlers
	setupNotificationHandlers();
}

async function loadNotificationSummary() {
	try {
		const token = localStorage.getItem('token');
		if (!token) return;

		const response = await fetch('/api/v1/notifications/summary', {
			headers: { 'Authorization': `Bearer ${token}` }
		});

		if (!response.ok) return;

		const data = await response.json();
		updateNotificationBadge(data.unread_count || 0);
	} catch (error) {
		console.warn('[navbar] Error loading notifications:', error);
	}
}

async function loadPendingApprovals(showAlert = false) {
	try {
		const token = localStorage.getItem('token');
		if (!token) return;

		const response = await fetch('/api/v1/notifications/pending-approvals', {
			headers: { 'Authorization': `Bearer ${token}` }
		});

		if (!response.ok) return;

		const data = await response.json();
		const count = data.length || 0;
		updateApprovalsBadge(count);
		renderPendingApprovals(data);

		// Show prominent alert if there are pending approvals on initial load
		if (showAlert && count > 0) {
			showPendingApprovalsAlert(data);
		}
	} catch (error) {
		console.warn('[navbar] Error loading pending approvals:', error);
	}
}

function showPendingApprovalsAlert(approvals) {
	// Remove any existing toast before showing a new one
	const existingToast = document.getElementById('pending-approvals-toast');
	if (existingToast) existingToast.remove();

	// Inject toast container if not present
	let toastContainer = document.getElementById('approval-toast-container');
	if (!toastContainer) {
		toastContainer = document.createElement('div');
		toastContainer.id = 'approval-toast-container';
		toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
		toastContainer.style.zIndex = '1100';
		document.body.appendChild(toastContainer);
	}

	const count = approvals.length;
	const toastId = 'pending-approvals-toast';

	const toastHtml = `
		<div id="${toastId}" class="toast show" role="alert" aria-live="assertive" aria-atomic="true" data-bs-autohide="false">
			<div class="toast-header bg-warning text-dark">
				<i class="bi bi-clipboard-check me-2"></i>
				<strong class="me-auto">Action Required</strong>
				<small>${count} item${count > 1 ? 's' : ''}</small>
				<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
			</div>
			<div class="toast-body">
				<p class="mb-2">
					<strong>You have ${count} pending approval${count > 1 ? 's' : ''}</strong> that require${count === 1 ? 's' : ''} your attention.
				</p>
				<div class="mb-2" style="max-height: 300px; overflow-y: auto;">
					${approvals.map(a => `
						<div class="small border-bottom py-1">
							<i class="bi bi-hourglass-split text-warning me-1"></i>
							<strong>${escapeHtml(a.entity_type)}</strong>: ${escapeHtml(a.entity_name || (a.entity_id ? a.entity_id.substring(0, 8) + '...' : 'Unknown'))}
							<span class="badge bg-secondary ms-1">${escapeHtml(a.current_state)}</span>
						</div>
					`).join('')}
				</div>
				<div class="mt-2 pt-2 border-top d-flex gap-2">
					<a href="/static/notifications.html" class="btn btn-warning btn-sm flex-grow-1">
						<i class="bi bi-eye me-1"></i>View All Approvals
					</a>
					<button type="button" class="btn btn-outline-secondary btn-sm dismiss-toast-btn">
						Later
					</button>
				</div>
			</div>
		</div>
	`;

	toastContainer.insertAdjacentHTML('beforeend', toastHtml);

	// Setup close buttons
	const toast = document.getElementById(toastId);
	if (toast) {
		toast.querySelectorAll('[data-bs-dismiss="toast"], .dismiss-toast-btn').forEach(btn => {
			btn.addEventListener('click', () => toast.remove());
		});
	}
}

async function loadNotificationList() {
	try {
		const token = localStorage.getItem('token');
		const response = await fetch('/api/v1/notifications/unread?limit=10', {
			headers: { 'Authorization': `Bearer ${token}` }
		});

		if (!response.ok) return;

		const data = await response.json();
		renderNotificationList(data.notifications || []);
	} catch (error) {
		console.warn('[navbar] Error loading notification list:', error);
	}
}

function updateNotificationBadge(count) {
	const badge = document.getElementById('notification-badge');
	if (badge) {
		if (count > 0) {
			badge.textContent = count > 99 ? '99+' : count;
			badge.style.display = 'block';
		} else {
			badge.style.display = 'none';
		}
	}
}

function updateApprovalsBadge(count) {
	const badge = document.getElementById('approvals-badge');
	if (badge) {
		if (count > 0) {
			badge.textContent = count > 99 ? '99+' : count;
			badge.style.display = 'block';
		} else {
			badge.style.display = 'none';
		}
	}
}

function renderNotificationList(notifications) {
	const container = document.getElementById('notification-list');
	if (!container) return;

	if (notifications.length === 0) {
		container.innerHTML = `
			<div class="text-center py-4 text-muted">
				<i class="bi bi-check-circle fs-3"></i>
				<p class="mb-0 mt-2">No new notifications</p>
			</div>
		`;
		return;
	}

	container.innerHTML = notifications.map(n => `
		<a href="#" class="dropdown-item notification-item py-2 ${n.is_read ? '' : 'bg-light'}"
		   data-notification-id="${n.id}">
			<div class="d-flex align-items-start">
				<div class="flex-shrink-0 me-2">
					<i class="bi ${getNotificationIcon(n.notification_type)} ${getNotificationIconColor(n.notification_type)}"></i>
				</div>
				<div class="flex-grow-1">
					<div class="fw-semibold small">${escapeHtml(n.title)}</div>
					<div class="text-muted small text-truncate" style="max-width: 280px;">
						${escapeHtml(n.message)}
					</div>
					<div class="text-muted" style="font-size: 0.75rem;">
						${formatTimeAgo(n.created_at)}
					</div>
				</div>
			</div>
		</a>
	`).join('');
}

function renderPendingApprovals(approvals) {
	const container = document.getElementById('approvals-list');
	if (!container) return;

	if (approvals.length === 0) {
		container.innerHTML = `
			<div class="text-center py-4 text-muted">
				<i class="bi bi-clipboard-check fs-3"></i>
				<p class="mb-0 mt-2">No pending approvals</p>
			</div>
		`;
		return;
	}

	container.innerHTML = approvals.map(a => `
		<a href="${getApprovalLink(a)}" class="dropdown-item approval-item py-2">
			<div class="d-flex align-items-start">
				<div class="flex-shrink-0 me-2">
					<i class="bi bi-hourglass-split text-warning"></i>
				</div>
				<div class="flex-grow-1">
					<div class="fw-semibold small">${escapeHtml(a.entity_type)}: ${escapeHtml(a.entity_name || a.entity_id)}</div>
					<div class="text-muted small">
						Status: <span class="badge bg-warning text-dark">${escapeHtml(a.current_state)}</span>
					</div>
					<div class="text-muted" style="font-size: 0.75rem;">
						${formatTimeAgo(a.submitted_at)}
					</div>
				</div>
			</div>
		</a>
	`).join('');
}

function getApprovalLink(approval) {
	const entityType = (approval.entity_type || '').toLowerCase();
	const entityId = approval.entity_id;

	const links = {
		'purchase_order': `/static/purchase-orders.html?view=${entityId}`,
		'purchaseorder': `/static/purchase-orders.html?view=${entityId}`,
		'sales_invoice': `/static/sales-invoices.html?view=${entityId}`,
		'salesinvoice': `/static/sales-invoices.html?view=${entityId}`,
		'journal_entry': `/static/journal-entry.html?id=${entityId}`,
		'journalentry': `/static/journal-entry.html?id=${entityId}`,
		'payment': `/static/payments.html?view=${entityId}`,
		'receipt': `/static/receipts.html?view=${entityId}`,
		'expense': `/static/expenses.html?view=${entityId}`,
		'stock_transfer': `/static/stock-transfers.html?view=${entityId}`,
		'stocktransfer': `/static/stock-transfers.html?view=${entityId}`,
	};

	return links[entityType] || '/static/notifications.html';
}

function setupNotificationHandlers() {
	// Load notifications when dropdown opens
	const notificationBell = document.getElementById('notificationBell');
	if (notificationBell) {
		notificationBell.addEventListener('click', () => {
			loadNotificationList();
		});
	}

	// Mark all as read button
	const markAllReadBtn = document.getElementById('mark-all-read-btn');
	if (markAllReadBtn) {
		markAllReadBtn.addEventListener('click', async (e) => {
			e.preventDefault();
			e.stopPropagation();
			await markAllNotificationsRead();
		});
	}

	// Handle individual notification clicks
	document.addEventListener('click', async (e) => {
		const notificationItem = e.target.closest('.notification-item');
		if (notificationItem) {
			const notificationId = notificationItem.dataset.notificationId;
			if (notificationId) {
				await markNotificationRead(notificationId);
			}
		}
	});
}

async function markNotificationRead(notificationId) {
	try {
		const token = localStorage.getItem('token');
		await fetch('/api/v1/notifications/mark-read', {
			method: 'POST',
			headers: {
				'Authorization': `Bearer ${token}`,
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({ notification_ids: [notificationId] })
		});
		loadNotificationSummary();
	} catch (error) {
		console.warn('[navbar] Error marking notification read:', error);
	}
}

async function markAllNotificationsRead() {
	try {
		const token = localStorage.getItem('token');
		const response = await fetch('/api/v1/notifications/mark-all-read', {
			method: 'POST',
			headers: { 'Authorization': `Bearer ${token}` }
		});

		if (response.ok) {
			updateNotificationBadge(0);
			loadNotificationList();
		}
	} catch (error) {
		console.warn('[navbar] Error marking all notifications read:', error);
	}
}

function getNotificationIcon(type) {
	const icons = {
		'approval_pending': 'bi-hourglass-split',
		'approval_approved': 'bi-check-circle',
		'approval_rejected': 'bi-x-circle',
		'workflow_status': 'bi-arrow-right-circle',
		'system': 'bi-gear',
		'alert': 'bi-exclamation-triangle',
		'info': 'bi-info-circle'
	};
	return icons[type] || 'bi-bell';
}

function getNotificationIconColor(type) {
	const colors = {
		'approval_pending': 'text-warning',
		'approval_approved': 'text-success',
		'approval_rejected': 'text-danger',
		'workflow_status': 'text-info',
		'system': 'text-secondary',
		'alert': 'text-danger',
		'info': 'text-primary'
	};
	return colors[type] || 'text-secondary';
}

function formatTimeAgo(dateString) {
	if (!dateString) return '';
	const date = new Date(dateString);
	const now = new Date();
	const seconds = Math.floor((now - date) / 1000);

	if (seconds < 60) return 'Just now';
	if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
	if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
	if (seconds < 604800) return `${Math.floor(seconds / 86400)}d ago`;
	return date.toLocaleDateString();
}

function escapeHtml(text) {
	if (!text) return '';
	const div = document.createElement('div');
	div.textContent = text;
	return div.innerHTML;
}

