/**
 * Service Worker Message Handler
 *
 * Handles messages from service worker (like notification actions)
 * and coordinates with the main application.
 */

import { pushState } from '$app/navigation';

interface ServiceWorkerMessage {
	type: string;
	action?: string;
	data?: any;
}

class ServiceWorkerMessageHandler {
	private retryCallbacks = new Map<string, () => void>();

	constructor() {
		this.initializeMessageListener();
	}

	/**
	 * Listen for messages from service worker
	 */
	private initializeMessageListener(): void {
		if ('serviceWorker' in navigator) {
			navigator.serviceWorker.addEventListener('message', (event) => {
				this.handleMessage(event.data);
			});
		}
	}

	/**
	 * Handle messages from service worker
	 */
	private handleMessage(message: ServiceWorkerMessage): void {
		console.log('[SW-Handler] Message received:', message);

		switch (message.type) {
			case 'notification-action':
				this.handleNotificationAction(message.action, message.data);
				break;

			default:
				console.log('[SW-Handler] Unknown message type:', message.type);
		}
	}

	/**
	 * Handle notification action clicks
	 */
	private handleNotificationAction(action: string | undefined, data: any): void {
		if (!action || !data?.itemId) {
			console.warn('[SW-Handler] Invalid notification action:', { action, data });
			return;
		}

		switch (action) {
			case 'view':
				this.handleViewAction(data.itemId);
				break;

			case 'retry':
				this.handleRetryAction(data.itemId);
				break;

			default:
				console.log('[SW-Handler] Unknown notification action:', action);
		}
	}

	/**
	 * Handle "view" action - scroll to item and highlight
	 */
	private handleViewAction(itemId: string): void {
		console.log('[SW-Handler] View action for item:', itemId);

		// Find the queue item card and scroll to it
		const element = document.querySelector(`[data-queue-item="${itemId}"]`);
		if (element) {
			element.scrollIntoView({
				behavior: 'smooth',
				block: 'center'
			});

			// Add temporary highlight effect
			element.classList.add('ring-2', 'ring-blue-500');
			setTimeout(() => {
				element.classList.remove('ring-2', 'ring-blue-500');
			}, 3000);
		} else {
			// If not found, navigate to homepage with highlight
			const url = new URL(window.location.href);
			url.searchParams.set('highlight', itemId);
			pushState(url, {});

			// Refresh page to show the item
			//window.location.reload();
		}
	}

	/**
	 * Handle "retry" action - trigger retry for failed item
	 */
	private async handleRetryAction(itemId: string): Promise<void> {
		console.log('[SW-Handler] Retry action for item:', itemId);

		// Check if there's a registered callback
		const callback = this.retryCallbacks.get(itemId);
		if (callback) {
			callback();
			return;
		}

		// Fallback: direct API call
		try {
			const response = await fetch(`/api/queue/${itemId}/retry`, {
				method: 'POST'
			});

			if (response.ok) {
				console.log('[SW-Handler] Retry initiated via API');

				// Show user feedback
				this.showRetryFeedback(true);
			} else {
				throw new Error('Retry request failed');
			}
		} catch (error) {
			console.error('[SW-Handler] Retry failed:', error);
			this.showRetryFeedback(false);
		}
	}

	/**
	 * Register retry callback for a queue item
	 */
	registerRetryCallback(itemId: string, callback: () => void): void {
		this.retryCallbacks.set(itemId, callback);
	}

	/**
	 * Unregister retry callback
	 */
	unregisterRetryCallback(itemId: string): void {
		this.retryCallbacks.delete(itemId);
	}

	/**
	 * Show retry feedback to user
	 */
	private showRetryFeedback(success: boolean): void {
		// Create temporary toast notification
		const toast = document.createElement('div');
		toast.className = `fixed bottom-4 left-4 px-4 py-2 rounded-lg text-white text-sm font-medium z-50 ${
			success ? 'bg-green-600' : 'bg-red-600'
		}`;
		toast.textContent = success
			? 'Retry initiated - check the queue for updates'
			: 'Failed to retry - please try again manually';

		document.body.appendChild(toast);

		// Auto-remove after 5 seconds
		setTimeout(() => {
			document.body.removeChild(toast);
		}, 5000);
	}

	/**
	 * Send message to service worker
	 */
	async sendMessageToSW(message: any): Promise<any> {
		if (!('serviceWorker' in navigator)) {
			throw new Error('Service worker not supported');
		}

		const registration = await navigator.serviceWorker.ready;
		if (!registration.active) {
			throw new Error('Service worker not active');
		}

		return new Promise((resolve, reject) => {
			const channel = new MessageChannel();
			channel.port1.onmessage = (event) => {
				resolve(event.data);
			};

			registration.active?.postMessage(message, [channel.port2]);

			// Timeout after 5 seconds
			setTimeout(() => {
				reject(new Error('Service worker message timeout'));
			}, 5000);
		});
	}
}

// Singleton instance
export const serviceWorkerMessageHandler = new ServiceWorkerMessageHandler();
