<!-- Analytics Dashboard -->
<section class="analytics-dashboard">

	<!-- Page Titles -->
	<div class="title-wrapper">
		<h1 class="title">Analytics Dashboard</h1>
		<p class="subtitle">Overview of your equestrian event platform</p>
	</div>

	<!-- Top Cards -->
	<div class="card-group">

		<!-- Total Users -->
		<div class="card">
			<div class="card-icon-wrapper">
				<div class="btn btn-wrapper btn-card">
					<img class="icon" src="<?= base_url('public/admin_assets/images/Total Users.png'); ?>" alt="">
				</div>
			</div>
			<h3 class="card-title">Total Users</h3>
			<div class="toll-wrapper">
				<h2 class="toll"><?= $total_users ?? 0; ?></h2>
				<a href="<?= base_url('admin/users'); ?>" class="btn btn-wrapper btn-card">
					<img src="<?= base_url('public/admin_assets/images/Path 23500.png'); ?>" alt="">
				</a>
			</div>
		</div>

		<!-- Active Events -->
		<div class="card">
			<div class="card-icon-wrapper">
				<div class="btn btn-wrapper btn-card">
					<img class="icon" src="<?= base_url('public/admin_assets/images/Active Events.png'); ?>" alt="">
				</div>
			</div>
			<h3 class="card-title">Active Events</h3>
			<div class="toll-wrapper">
				<h2 class="toll"><?= $active_events ?? 0; ?></h2>
				<a href="<?= base_url('admin/content'); ?>" class="btn btn-wrapper btn-card">
					<img src="<?= base_url('public/admin_assets/images/Path 23500.png'); ?>" alt="">
				</a>
			</div>
		</div>

		<!-- Closed Events -->
		<div class="card">
			<div class="card-icon-wrapper">
				<div class="btn btn-wrapper btn-card">
					<img class="icon" src="<?= base_url('public/admin_assets/images/Active Events.png'); ?>" alt="">
				</div>
			</div>
			<h3 class="card-title">Closed Events</h3>
			<div class="toll-wrapper">
				<h2 class="toll"><?= $closed_events ?? 0; ?></h2>
				<a href="<?= base_url('admin/content'); ?>" class="btn btn-wrapper btn-card">
					<img src="<?= base_url('public/admin_assets/images/Path 23500.png'); ?>" alt="">
				</a>
			</div>
		</div>

		<!-- Scheduled -->
		<div class="card">
			<div class="card-icon-wrapper">
				<div class="btn btn-wrapper btn-card">
					<img class="icon" src="<?= base_url('public/admin_assets/images/Scheduled.png'); ?>" alt="">
				</div>
			</div>
			<h3 class="card-title">Scheduled</h3>
			<div class="toll-wrapper">
				<h2 class="toll"><?= $scheduled_events ?? 0; ?></h2>
				<a href="<?= base_url('admin/content'); ?>" class="btn btn-wrapper btn-card">
					<img src="<?= base_url('public/admin_assets/images/Path 23500.png'); ?>" alt="">
				</a>
			</div>
		</div>

	</div>

	<!-- Bottom Dashboard -->
	<div class="dashboard">

		<!-- Upcoming Events -->
		<section class="card">
			<div class="card-header">
				<h2 class="card-header-title">Upcoming Events</h2>
				<a href="<?= base_url('admin/content'); ?>">View All</a>
			</div>

			<div class="event-list">
				<?php if (!empty($upcoming_events)): ?>
					<?php foreach ($upcoming_events as $event): ?>
						<div class="event-item">
							<img src="<?= base_url('public/admin_assets/images/users-profile.png'); ?>" alt="">
							<div class="event-info">
								<h3 class="title"><?= htmlspecialchars($event['name'] ?? 'N/A'); ?></h3>
								<div class="event-calender">
									<p>Start Date:
										<span>
											<?= $event['start_date'] !== 'N/A'
												? $event['start_date']
												: 'TBD'; ?>

										</span>
									</p>
								</div>
							</div>
							<span class="tag"><?= isset($event['tiles_count']) ? (int) $event['tiles_count'] : 0; ?>
								Tiles</span>
						</div>
					<?php endforeach; ?>
				<?php else: ?>
					<p class="text-muted">No upcoming events found</p>
				<?php endif; ?>
			</div>
		</section>

		<!-- New Users -->
		<section class="card">
			<div class="card-header">
				<h2 class="card-header-title">New Users</h2>
				<a href="<?= base_url('admin/users'); ?>">View All</a>
			</div>

			<div class="user-list">
				<?php if (!empty($new_users)): ?>
					<?php foreach ($new_users as $user): ?>
						<div class="user-item">
							<div class="user-info">
								<h3 class="title"><?= htmlspecialchars($user['fullname'] ?? 'N/A'); ?></h3>
								<p><span><?= htmlspecialchars($user['email'] ?? '—'); ?></span></p>
							</div>
							<span class="time">
								<?php
								// Use userDate from Firebase and convert milliseconds -> seconds
								$created = isset($user['userDate']) ? (int)($user['userDate'] / 1000) : time();
								$diff = time() - $created;

								if ($diff < 60) {
									echo 'just now';
								} elseif ($diff < 3600) {
									echo floor($diff / 60) . ' min ago';
								} elseif ($diff < 86400) {
									echo floor($diff / 3600) . ' hours ago';
								} else {
									echo floor($diff / 86400) . ' days ago';
								}
								?>
							</span>
						</div>
					<?php endforeach; ?>
				<?php else: ?>
					<p class="text-muted">No new users found</p>
				<?php endif; ?>
			</div>
		</section>

		<!-- Real-time Notifications -->
		<section class="card">
			<div class="card-header">
				<h2 class="card-header-title">Push Notifications</h2>
				<a href="<?= base_url('admin/notifications'); ?>">View All</a>
			</div>

			<div class="notification-list" id="notificationsList">
				<p class="text-muted">Loading notifications...</p>
			</div>
		</section>

	</div>

</section>



<script>
	let db;
	let notificationsUnsubscribe = null;
	const userNameCache = {};

	// Initialize Firebase
	async function initFirebaseForNotifications() {
		try {
			const response = await fetch('<?php echo base_url("admin/getFirebaseConfig"); ?>');
			const firebaseConfig = await response.json();

			if (!firebase.apps.length) {
				firebase.initializeApp(firebaseConfig);
			}

			db = firebase.firestore();
			loadRealtimeNotifications();
		} catch (error) {
			console.error('Firebase initialization error:', error);
			document.getElementById('notificationsList').innerHTML =
				'<p class="text-muted">Failed to load notifications</p>';
		}
	}

	// Get user name from Firebase (with caching)
	async function getUserNameForNotification(userId) {
		if (!userId) return 'Unknown User';
		if (userNameCache[userId]) return userNameCache[userId];

		try {
			const snap = await db.collection('Users').doc(userId).get();
			if (snap.exists) {
				const data = snap.data();
				const name = data.fullname || 'User';
				userNameCache[userId] = name;
				return name;
			}
		} catch (err) {
			console.error('Error fetching user name:', err);
		}

		return 'User';
	}

	// Load real-time notifications with Firebase listener
	function loadRealtimeNotifications() {
		const container = document.getElementById('notificationsList');

		// Clean up existing listener if any
		if (notificationsUnsubscribe) {
			notificationsUnsubscribe();
		}

		// Listen to admin_notifications collection in real-time
		notificationsUnsubscribe = db.collection('admin_notifications')
			.orderBy('createdAt', 'desc')
			.limit(50) // Limit to last 50 notifications
			.onSnapshot(async (snapshot) => {
				if (snapshot.empty) {
					container.innerHTML = '<p class="text-muted">No notifications found</p>';
					return;
				}

				// Collect all notifications
				const allNotifications = [];
				snapshot.forEach(doc => {
					const data = doc.data();
					data.id = doc.id;
					allNotifications.push(data);
				});

				// Display all notifications (chat and scratch)
				await displayAllNotifications(allNotifications, container);
			}, (error) => {
				console.error('Error listening to notifications:', error);
				container.innerHTML = '<p class="text-muted">Error loading notifications</p>';
			});
	}

	async function displayAllNotifications(allNotifications, container) {
		container.innerHTML = '';

		// Sort ALL notifications by createdAt (most recent first)
		allNotifications.sort((a, b) => {
			const timeA = a.createdAt || 0;
			const timeB = b.createdAt || 0;
			return timeB - timeA; // Descending order (newest first)
		});

		let displayCount = 0;
		const maxDisplay = 10; // Show max 10 items on dashboard

		// Process notifications in chronological order (newest first)
		for (const notif of allNotifications) {
			if (displayCount >= maxDisplay) break;

			if (notif.type === 'chat') {
				const userName = await getUserNameForNotification(notif.userId);
				// For chat notifications, we'll show them individually now
				await displayChatNotification(container, notif, userName, 1, [notif]);
				displayCount++;
			} else if (notif.type === 'scratch') {
				await displayScratchNotification(container, notif);
				displayCount++;
			}
		}

		if (displayCount === 0) {
			container.innerHTML = '<p class="text-muted">No notifications found</p>';
		}
	}

	// Display a chat notification
	async function displayChatNotification(container, latestNotif, userName, unreadCount, userNotifications) {
		// Create notification item
		const notifItem = document.createElement('div');
		notifItem.className = 'notification-item';
		notifItem.style.padding = '10px';
		notifItem.style.marginBottom = '8px';
		notifItem.style.borderRadius = '6px';
		notifItem.style.transition = 'background 0.2s';
		notifItem.style.display = 'flex';
		notifItem.style.alignItems = 'center';
		notifItem.style.gap = '10px';

		// Unread indicator (dot)
		const unreadIndicator = document.createElement('div');
		unreadIndicator.className = 'unread-indicator';
		unreadIndicator.style.width = '8px';
		unreadIndicator.style.height = '8px';
		unreadIndicator.style.borderRadius = '50%';
		unreadIndicator.style.flexShrink = '0';
		unreadIndicator.style.backgroundColor = latestNotif.isRead ? 'transparent' : '#09bb00ff';
		notifItem.appendChild(unreadIndicator);

		// Main content wrapper (clickable)
		const contentWrapper = document.createElement('div');
		contentWrapper.style.flex = '1';
		contentWrapper.style.cursor = 'pointer';
		contentWrapper.style.display = 'flex';
		contentWrapper.style.justifyContent = 'space-between';
		contentWrapper.style.alignItems = 'center';

		// Add hover effect
		contentWrapper.onmouseover = function() {
			notifItem.style.background = '#edd99b';
		};
		contentWrapper.onmouseout = function() {
			notifItem.style.background = 'transparent';
		};

		// Make content clickable and mark as read
		contentWrapper.onclick = async function(e) {
			e.stopPropagation();
			if (latestNotif.link) {
				await markNotificationsAsRead(userNotifications);
				window.location.href = latestNotif.link;
			}
		};

		// Build notification HTML
		const badgeHTML = unreadCount > 0 ?
			`<span class="badge bg-gray" style="margin-left: 8px; padding: 2px 6px; border-radius: 10px; font-size: 11px;">${unreadCount}</span>` :
			'';

		contentWrapper.innerHTML = `
			<div class="notification-info">
				<h3 class="title" style="margin: 0; font-size: 14px; font-weight: 500;">
					<i class="ri-message-3-line"></i> ${escapeHtml(userName)} 
				</h3>
				<p style="margin: 4px 0 0 0; font-size: 12px; color: #666;">
					<span>${escapeHtml(latestNotif.body || 'New message')}</span>
				</p>
			</div>
			<span class="time" style="font-size: 11px; color: #999;">${timeAgo(latestNotif.createdAt)}</span>
		`;

		notifItem.appendChild(contentWrapper);
		container.appendChild(notifItem);
	}

	// Display a scratch notification
	async function displayScratchNotification(container, scratchNotif) {
		// Create notification item
		const notifItem = document.createElement('div');
		notifItem.className = 'notification-item';
		notifItem.style.padding = '10px';
		notifItem.style.marginBottom = '8px';
		notifItem.style.borderRadius = '6px';
		notifItem.style.transition = 'background 0.2s';
		notifItem.style.display = 'flex';
		notifItem.style.alignItems = 'center';
		notifItem.style.gap = '10px';

		// Unread indicator (dot) - SAME GREEN COLOR AS MESSAGES
		const unreadIndicator = document.createElement('div');
		unreadIndicator.className = 'unread-indicator';
		unreadIndicator.style.width = '8px';
		unreadIndicator.style.height = '8px';
		unreadIndicator.style.borderRadius = '50%';
		unreadIndicator.style.flexShrink = '0';
		unreadIndicator.style.backgroundColor = scratchNotif.isRead ? 'transparent' : '#09bb00ff'; // Same green as messages
		notifItem.appendChild(unreadIndicator);

		// Main content wrapper (clickable)
		const contentWrapper = document.createElement('div');
		contentWrapper.style.flex = '1';
		contentWrapper.style.cursor = 'pointer';
		contentWrapper.style.display = 'flex';
		contentWrapper.style.justifyContent = 'space-between';
		contentWrapper.style.alignItems = 'center';

		// Add hover effect
		contentWrapper.onmouseover = function() {
			notifItem.style.background = '#edd99b';
		};
		contentWrapper.onmouseout = function() {
			notifItem.style.background = 'transparent';
		};

		// Make content clickable and mark as read
		contentWrapper.onclick = async function(e) {
			e.stopPropagation();
			await markScratchNotificationAsRead(scratchNotif.id);
			window.location.href = '<?= base_url("admin/requests"); ?>';
		};

		// Get scratch type icon - UPDATED ICONS
		const scratchIcon = scratchNotif.scratchType === 'Scratch' ?
			'<i class="ri-indeterminate-circle-line"></i>' : // Better icon for scratch
			'<i class="ri-file-edit-line"></i>'; // Better icon for entry request

		contentWrapper.innerHTML = `
		<div class="notification-info">
			<h3 class="title" style="margin: 0; font-size: 14px; font-weight: 500;">
				${scratchIcon} ${escapeHtml(scratchNotif.scratchType || 'Request')}
			</h3>
			<p style="margin: 4px 0 0 0; font-size: 12px; color: #666;">
				<span>${escapeHtml(scratchNotif.body || scratchNotif.title || 'New request')}</span>
			</p>
		</div>
		<span class="time" style="font-size: 11px; color: #999;">${timeAgo(scratchNotif.createdAt)}</span>
		`;

		notifItem.appendChild(contentWrapper);
		container.appendChild(notifItem);
	}

	// Escape HTML to prevent XSS
	function escapeHtml(text) {
		const div = document.createElement('div');
		div.textContent = text;
		return div.innerHTML;
	}

	// Mark chat notifications as read
	async function markNotificationsAsRead(notifications) {
		try {
			const batch = db.batch();

			for (const notif of notifications) {
				if (!notif.isRead) {
					const notifRef = db.collection('admin_notifications').doc(notif.id);
					batch.update(notifRef, {
						isRead: true
					});
				}
			}

			await batch.commit();
			console.log('Notifications marked as read');
		} catch (error) {
			console.error('Error marking notifications as read:', error);
		}
	}

	// Mark scratch notification as read
	async function markScratchNotificationAsRead(notifId) {
		try {
			await db.collection('admin_notifications').doc(notifId).update({
				isRead: true
			});
			console.log('Scratch notification marked as read');
		} catch (error) {
			console.error('Error marking scratch notification as read:', error);
		}
	}

	// Convert milliseconds timestamp to "time ago"
	function timeAgo(ms) {
		if (!ms) return 'just now';
		const diff = Math.floor((Date.now() - ms) / 1000); // seconds
		if (diff < 60) return 'just now';
		if (diff < 3600) return Math.floor(diff / 60) + ' min ago';
		if (diff < 86400) return Math.floor(diff / 3600) + ' hours ago';
		return Math.floor(diff / 86400) + ' days ago';
	}

	// Initialize on page load
	document.addEventListener('DOMContentLoaded', initFirebaseForNotifications);

	// Clean up listener when page unloads
	window.addEventListener('beforeunload', () => {
		if (notificationsUnsubscribe) {
			notificationsUnsubscribe();
		}
	});
</script>

<style>
	/* Notification List Container with Scroll */
	#notificationsList {
		max-height: 400px;
		overflow-y: auto;
		padding-right: 5px;
	}

	/* Custom Scrollbar */
	#notificationsList::-webkit-scrollbar {
		width: 6px;
	}

	#notificationsList::-webkit-scrollbar-track {
		background: #f1f1f1;
		border-radius: 10px;
	}

	#notificationsList::-webkit-scrollbar-thumb {
		background: #888;
		border-radius: 10px;
	}

	#notificationsList::-webkit-scrollbar-thumb:hover {
		background: #555;
	}

	/* Notifications Wrapper */
	.notifications-wrapper {
		display: flex;
		flex-direction: column;
		gap: 0;
	}

	/* Notification Item */
	.notification-item {
		display: flex;
		align-items: center;
		padding: 10px;
		border-radius: 6px;
		transition: background 0.2s;
		gap: 10px;
		cursor: pointer;
	}

	.notification-item:hover {
		background: #edd99b;
	}

	/* Unread Indicator Dot */
	.unread-indicator {
		width: 8px;
		height: 8px;
		border-radius: 50%;
		flex-shrink: 0;
	}

	/* Notification Content */
	.notification-content {
		flex: 1;
		cursor: pointer;
		display: flex;
		justify-content: space-between;
		align-items: center;
		min-width: 0;
	}

	/* Notification Info */
	.notification-info {
		flex: 1;
		min-width: 0;
	}

	.notification-info .title {
		margin: 0;
		font-size: 14px;
		font-weight: 500;
		display: flex;
		align-items: center;
		gap: 6px;
		flex-wrap: wrap;
	}

	.notification-info p {
		margin: 4px 0 0 0;
		font-size: 12px;
		color: #666;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	/* Time Display */
	.notification-item .time {
		font-size: 11px;
		color: #999;
		white-space: nowrap;
		margin-left: 10px;
		flex-shrink: 0;
	}

	/* Badge for Unread Count */
	.badge {
		display: inline-block;
		padding: 2px 6px;
		border-radius: 10px;
		font-size: 11px;
		font-weight: 600;
		margin-left: 8px;
	}

	.badge.bg-success {
		background-color: #09bb00ff;
		color: white;
	}

	/* Show More Button */
	.show-more-btn {
		width: 100%;
		padding: 10px;
		margin-top: 10px;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		border: none;
		border-radius: 6px;
		font-size: 13px;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.3s ease;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.show-more-btn:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
		background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
	}

	.show-more-btn:active {
		transform: translateY(0);
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	/* Text Muted */
	.text-muted {
		color: #999;
		font-size: 13px;
		text-align: center;
		padding: 20px;
		margin: 0;
	}

	.notification-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px;
		border-radius: 6px;
		transition: background 0.2s;
		gap: 10px;
	}

	.notification-item:hover {
		background: #edd99b;
	}

	.unread-indicator {
		width: 8px;
		height: 8px;
		border-radius: 50%;
		flex-shrink: 0;
	}

	.notification-info {
		flex: 1;
	}

	.notification-info .title {
		margin: 0;
		font-size: 14px;
		font-weight: 500;
		display: flex;
		align-items: center;
		gap: 6px;
	}

	.notification-info p {
		margin: 4px 0 0 0;
		font-size: 12px;
		color: #666;
	}

	.notification-item .time {
		font-size: 11px;
		color: #999;
		white-space: nowrap;
		margin-left: 10px;
	}

	.badge {
		display: inline-block;
		padding: 2px 6px;
		border-radius: 10px;
		font-size: 11px;
		font-weight: 600;
	}

	.badge.bg-success {
		background-color: green;
		color: white;
	}
</style>

<style>
	.notification-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px;
		border-radius: 6px;
		transition: background 0.2s;
		gap: 10px;
	}

	.notification-item:hover {
		background: #edd99b;
	}

	.unread-indicator {
		width: 8px;
		height: 8px;
		border-radius: 50%;
		flex-shrink: 0;
	}

	.notification-info {
		flex: 1;
	}

	.notification-info .title {
		margin: 0;
		font-size: 14px;
		font-weight: 500;
		display: flex;
		align-items: center;
		gap: 6px;
	}

	.notification-info p {
		margin: 4px 0 0 0;
		font-size: 12px;
		color: #666;
	}

	.notification-item .time {
		font-size: 11px;
		color: #999;
		white-space: nowrap;
		margin-left: 10px;
	}

	.badge {
		display: inline-block;
		padding: 2px 6px;
		border-radius: 10px;
		font-size: 11px;
		font-weight: 600;
	}

	.badge.bg-success {
		background-color: green;
		color: white;
	}
</style>