/**
 * Notification System - FAB + Slide Panel JavaScript
 *
 * @package KNS_Dynamic_Discounts
 */

(function($) {
	'use strict';

	/**
	 * Notification Panel Manager
	 */
	class NotificationPanel {
		constructor() {
			this.fab = $('#knsdd-notification-fab');
			this.panel = $('#knsdd-notification-panel');
			this.overlay = $('#knsdd-notification-overlay');
			this.listContainer = $('.knsdd-notifications-list');
			this.loadingState = $('.knsdd-notifications-loading');
			this.emptyState = $('.knsdd-notifications-empty');
			this.errorState = $('.knsdd-notifications-error');
			this.footer = $('.knsdd-panel-footer');
			this.loadMoreBtn = $('.knsdd-load-more');
			
			this.offset = 0;
			this.limit = 10;
			this.total = 0;
			this.isLoading = false;
			this.isOpen = false;

			this.init();
		}

		init() {
			// FAB click - open panel
			this.fab.on('click', '.knsdd-fab-button', (e) => {
				e.preventDefault();
				this.openPanel();
			});

			// Close button
			this.panel.on('click', '.knsdd-panel-close', (e) => {
				e.preventDefault();
				this.closePanel();
			});

			// Overlay click - close panel
			this.overlay.on('click', (e) => {
				e.preventDefault();
				this.closePanel();
			});

			// Dismiss notification
			this.panel.on('click', '.knsdd-dismiss-notification', (e) => {
				e.preventDefault();
				const notificationId = $(e.currentTarget).data('id');
				this.dismissNotification(notificationId, $(e.currentTarget).closest('.knsdd-notification-item'));
			});

			// Mark notification as read
			this.panel.on('click', '.knsdd-mark-read-notification', (e) => {
				e.preventDefault();
				const notificationId = $(e.currentTarget).data('id');
				this.markNotificationAsRead(notificationId, $(e.currentTarget).closest('.knsdd-notification-item'));
			});

			// Handle notification action clicks (for focus integration)
			this.panel.on('click', '.knsdd-notification-actions a', (e) => {
				const url = $(e.currentTarget).attr('href');
				
				// Check if URL has focus parameter (groups page)
				if (url && url.includes('page=knsdd-groups') && url.includes('focus=')) {
					e.preventDefault();
					
					// Extract group name from focus parameter
					const match = url.match(/focus=([^&]+)/);
					if (match && match[1]) {
						const groupName = decodeURIComponent(match[1]);
						
						// Close notification panel
						this.closePanel();
						
						// Set focus via localStorage (existing focus system)
						try {
							if (window.localStorage) {
								localStorage.setItem('lastGroup', groupName);
							}
						} catch (e) {}
						
						// If we're already on groups page, trigger focus directly
						if (window.location.href.includes('page=knsdd-groups')) {
							// Trigger the existing focus system
							setTimeout(() => {
								const $row = $('#knsdd-toggle-tbody').find('tr').filter(function() {
									return $(this).data('group') === groupName;
								});
								
								if ($row.length) {
									// Scroll to row
									const el = $row.get(0);
									if (el && el.scrollIntoView) {
										el.scrollIntoView({ behavior: 'smooth', block: 'center' });
									}
									
									// Add focus highlight
									$row.addClass('knsdd-return-focus');
									setTimeout(() => {
										$row.removeClass('knsdd-return-focus');
									}, 3500);
								}
							}, 100);
						} else {
							// Navigate to groups page
							window.location.href = url;
						}
					}
				}
				// Check if URL has group parameter (rules page)
				else if (url && url.includes('page=knsdd-rules') && url.includes('group=')) {
					e.preventDefault();
					
					// Extract group name from group parameter
					const match = url.match(/group=([^&]+)/);
					if (match && match[1]) {
						const groupName = decodeURIComponent(match[1]);
						
						// Close notification panel
						this.closePanel();
						
						// Set group via localStorage (rules page uses this)
						try {
							if (window.localStorage) {
								localStorage.setItem('lastGroup', groupName);
							}
						} catch (e) {}
						
						// Navigate to rules page (it will auto-select the group)
						window.location.href = url;
					}
				}
			});

			// Load more
			this.loadMoreBtn.on('click', (e) => {
				e.preventDefault();
				this.loadNotifications();
			});

			// ESC key to close
			$(document).on('keydown', (e) => {
				if (e.key === 'Escape' && this.isOpen) {
					this.closePanel();
				}
			});
		}

		openPanel() {
			this.isOpen = true;
			this.panel.addClass('open');
			this.overlay.addClass('active');
			$('body').css('overflow', 'hidden');

			// Load notifications if first time
			if (this.offset === 0) {
				this.loadNotifications();
			}

			// Don't auto-clear badge - user will mark as read manually

			// Focus trap
			this.panel.find('.knsdd-panel-close').focus();
		}

		closePanel() {
			this.isOpen = false;
			this.panel.removeClass('open');
			this.overlay.removeClass('active');
			$('body').css('overflow', '');
		}

		loadNotifications() {
			if (this.isLoading) {
				return;
			}

			this.isLoading = true;
			this.showLoading();

			$.ajax({
				url: knsddNotifications.ajaxUrl,
				type: 'POST',
				data: {
					action: 'knsdd_get_notifications',
					nonce: knsddNotifications.nonce,
					offset: this.offset,
					limit: this.limit
				},
				success: (response) => {
					if (response.success && response.data) {
						this.renderNotifications(response.data);
					} else {
						this.showError();
					}
				},
				error: () => {
					this.showError();
				},
				complete: () => {
					this.isLoading = false;
					this.hideLoading();
				}
			});
		}

		renderNotifications(data) {
			const notifications = data.notifications || [];
			this.total = data.total || 0;
			this.offset = data.offset || 0;

			if (notifications.length === 0 && this.offset === 0) {
				this.showEmpty();
				return;
			}

			this.hideEmpty();
			this.hideError();
			this.listContainer.show();

			// Render each notification
			notifications.forEach((notification) => {
				const html = this.renderNotificationItem(notification);
				this.listContainer.append(html);
			});
			// Update offset
			this.offset += notifications.length;

			// Update badge on first load
			if (this.offset === notifications.length) {
				// Calculate unread count by excluding read notifications from sessionStorage
				let unreadCount = this.total;
				try {
					if (window.sessionStorage) {
						const readNotifications = JSON.parse(sessionStorage.getItem('knsdd_read_notifications') || '[]');
						// Count how many current notifications are in the read list
						const currentIds = notifications.map(n => n.id);
						const readCurrentCount = currentIds.filter(id => readNotifications.includes(id)).length;
						unreadCount = Math.max(0, this.total - readCurrentCount);
					}
				} catch (e) {}
				
				this.updateBadgeCount(unreadCount);
			}

			// Show/hide load more button
			if (data.hasMore) {
				const remaining = this.total - this.offset;
				this.footer.show();
				this.loadMoreBtn.find('.knsdd-remaining-count').text(
					'(' + remaining + ' ' + knsddNotifications.i18n.remaining + ')'
				);
			} else {
				this.footer.hide();
			}
		}

		renderNotificationItem(notification) {
			const id = notification.id || '';
			const icon = notification.icon || '📢'; // Don't escape - allow HTML for Iconify
			const message = this.escapeHtml(notification.message || '');
			const actions = notification.actions || [];
			const priority = notification.priority || 50;

			// Check if notification is already read
			let isRead = false;
			let readClass = '';
			let readButtonStyle = '';
			try {
				if (window.sessionStorage) {
					const readNotifications = JSON.parse(sessionStorage.getItem('knsdd_read_notifications') || '[]');
					if (readNotifications.includes(id)) {
						isRead = true;
						readClass = ' read';
						readButtonStyle = ' style="display:none;"';
					}
				}
			} catch (e) {}

			let actionsHtml = '';
			actions.forEach((action) => {
				if (action.url) {
					const label = this.escapeHtml(action.label || '');
					const url = this.escapeHtml(action.url || '');
					const type = action.type || 'secondary';
					actionsHtml += `<a href="${url}" class="button button-${type}" target="_blank">${label}</a>`;
				}
			});

			return `
				<div class="knsdd-notification-item${readClass}" data-id="${this.escapeHtml(id)}" data-priority="${priority}">
					<div class="knsdd-notification-content">
						<span class="knsdd-notification-icon">${icon}</span>
						<span class="knsdd-notification-message">${message}</span>
					</div>
					<div class="knsdd-notification-actions">
						<div class="knsdd-notification-action-buttons">
							${actionsHtml}
						</div>
						<div class="knsdd-notification-control-buttons">
							<button type="button" class="knsdd-mark-read-notification" data-id="${this.escapeHtml(id)}" aria-label="${knsddNotifications.i18n.markAsRead}"${readButtonStyle}>${knsddNotifications.i18n.markAsRead}</button>
							<button type="button" class="knsdd-dismiss-notification" data-id="${this.escapeHtml(id)}" aria-label="${knsddNotifications.i18n.dismiss}">${knsddNotifications.i18n.dismiss}</button>
						</div>
					</div>
				</div>
			`;
		}

		dismissNotification(notificationId, $item) {
			// Animate out
			$item.addClass('dismissed');

			// Send AJAX request
			$.ajax({
				url: knsddNotifications.ajaxUrl,
				type: 'POST',
				data: {
					action: 'knsdd_dismiss_notification',
					nonce: knsddNotifications.nonce,
					notification_id: notificationId
				},
				success: (response) => {
					if (response.success) {
						// Update badge count
						const newCount = response.data.unreadCount || 0;
						this.updateBadgeCount(newCount);

						// Remove item after animation
						setTimeout(() => {
							$item.remove();

							// Check if list is empty
							if (this.listContainer.children().length === 0) {
								this.showEmpty();
								this.footer.hide();
							}
						}, 300);
					}
				},
				error: () => {
					// Revert animation on error
					$item.removeClass('dismissed');
				}
			});
		}

		markNotificationAsRead(notificationId, $item) {
			// Add visual read state
			$item.addClass('read');

			// Save to sessionStorage
			try {
				if (window.sessionStorage) {
					const readNotifications = JSON.parse(sessionStorage.getItem('knsdd_read_notifications') || '[]');
					if (!readNotifications.includes(notificationId)) {
						readNotifications.push(notificationId);
						sessionStorage.setItem('knsdd_read_notifications', JSON.stringify(readNotifications));
					}
				}
			} catch (e) {}

			// Send AJAX to mark as read (doesn't add to dismissed list)
			$.ajax({
				url: knsddNotifications.ajaxUrl,
				type: 'POST',
				data: {
					action: 'knsdd_mark_notification_read',
					nonce: knsddNotifications.nonce,
					notification_id: notificationId
				},
				success: (response) => {
					if (response.success) {
						// Update badge count by decrementing current badge
						const $badge = this.fab.find('.knsdd-fab-badge');
						const currentCount = parseInt($badge.text()) || 0;
						const newCount = Math.max(0, currentCount - 1);
						this.updateBadgeCount(newCount);

						// Hide the "Mark as Read" button
						$item.find('.knsdd-mark-read-notification').fadeOut(200);
					}
				},
				error: () => {
					// Revert on error
					$item.removeClass('read');
				}
			});
		}

		updateBadgeCount(count) {
			const $badge = this.fab.find('.knsdd-fab-badge');
			
			if (count > 0) {
				if ($badge.length) {
					$badge.text(count).addClass('knsdd-badge-ready');
				} else {
					this.fab.find('.knsdd-fab-button').append(
						`<span class="knsdd-fab-badge knsdd-badge-ready">${count}</span>`
					);
				}
			} else {
				$badge.remove();
			}

			this.fab.attr('data-unread', count);
		}

		showLoading() {
			this.loadingState.show();
		}

		hideLoading() {
			this.loadingState.hide();
		}

		showEmpty() {
			this.listContainer.hide();
			this.emptyState.show();
			this.errorState.hide();
		}

		hideEmpty() {
			this.emptyState.hide();
		}

		showError() {
			this.listContainer.hide();
			this.emptyState.hide();
			this.errorState.show();
		}

		hideError() {
			this.errorState.hide();
		}

		escapeHtml(text) {
			const map = {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				'"': '&quot;',
				"'": '&#039;'
			};
			return text.replace(/[&<>"']/g, (m) => map[m]);
		}
	}

	// Initialize on document ready
	$(document).ready(function() {
		if ($('#knsdd-notification-fab').length) {
			const panel = new NotificationPanel();
			
			// Correct badge count on page load based on sessionStorage
			try {
				if (window.sessionStorage) {
					const serverCount = parseInt(panel.fab.attr('data-unread')) || 0;
					
					if (serverCount > 0) {
						// Get current notification IDs to calculate accurate count
						$.ajax({
							url: knsddNotifications.ajaxUrl,
							type: 'POST',
							data: {
								action: 'knsdd_get_notifications',
								nonce: knsddNotifications.nonce,
								offset: 0,
								limit: 100 // Get all to check against sessionStorage
							},
							success: function(response) {
								if (response.success && response.data && response.data.notifications) {
									const readNotifications = JSON.parse(sessionStorage.getItem('knsdd_read_notifications') || '[]');
									const currentIds = response.data.notifications.map(n => n.id);
									
									// Clean up sessionStorage: remove IDs that no longer exist
									const validReadIds = readNotifications.filter(id => currentIds.includes(id));
									if (validReadIds.length !== readNotifications.length) {
										sessionStorage.setItem('knsdd_read_notifications', JSON.stringify(validReadIds));
									}
									
									const readCurrentCount = validReadIds.length;
									const correctedCount = Math.max(0, response.data.total - readCurrentCount);
									panel.updateBadgeCount(correctedCount);
								}
							}
						});
					} else {
						// No notifications, ensure badge is hidden
						panel.fab.find('.knsdd-fab-badge').remove();
					}
				}
			} catch (e) {}
			
			// Expose globally for external refresh
			window.KNSDDNotificationPanel = {
				refreshNotifications: function() {
					panel.offset = 0;
					panel.listContainer.empty();
					panel.loadNotifications();
					
					// Update badge count via AJAX (considering sessionStorage)
					$.ajax({
						url: knsddNotifications.ajaxUrl,
						type: 'POST',
						data: {
							action: 'knsdd_get_notifications',
							nonce: knsddNotifications.nonce,
							offset: 0,
							limit: 100
						},
						success: function(response) {
							if (response.success && response.data) {
								try {
									if (window.sessionStorage) {
										const readNotifications = JSON.parse(sessionStorage.getItem('knsdd_read_notifications') || '[]');
										const currentIds = response.data.notifications.map(n => n.id);
										
										// Clean up sessionStorage
										const validReadIds = readNotifications.filter(id => currentIds.includes(id));
										if (validReadIds.length !== readNotifications.length) {
											sessionStorage.setItem('knsdd_read_notifications', JSON.stringify(validReadIds));
										}
										
										const correctedCount = Math.max(0, response.data.total - validReadIds.length);
										panel.updateBadgeCount(correctedCount);
									} else {
										panel.updateBadgeCount(response.data.total || 0);
									}
								} catch (e) {
									panel.updateBadgeCount(response.data.total || 0);
								}
							}
						}
					});
				}
			};
		}
	});

})(jQuery);
