/* global window, document */

// Export function to register the setup tasks component
export function registerSetupTasks(Alpine) {
	Alpine.data('setupTasks', () => ({
		// Initialize from localized WordPress data with safe defaults
		tasks: window.rewardsWP?.checklistTasks || [],

		dismissed: window.rewardsWP?.checklistDismissed || false,
		loading: false,
		menuOpen: false,

		get progress() {
			const completed = this.tasks.filter(task => task.status === 'complete').length;
			return Math.round((completed / this.tasks.length) * 100);
		},

		get hasIncompleteTasks() {
			return this.tasks.some(task => task.status === 'incomplete');
		},

		get completedCount() {
			return this.tasks.filter(task => task.status === 'complete').length;
		},

		get remainingCount() {
			return this.tasks.filter(task => task.status === 'incomplete').length;
		},

		async dismiss() {
			// Immediately hide the checklist for instant feedback
			this.dismissed = true;

			// Then save the state in the background
			const formData = new FormData();
			formData.append('action', 'rewardswp_dismiss_checklist');
			formData.append('_ajax_nonce', window.rewardsWP?.nonce || '');

			try {
				const response = await fetch(window.ajaxurl || ajaxurl, {
					method: 'POST',
					body: formData
				});
				const data = await response.json();

				// If it failed, revert the dismissal
				if (!data.success) {
					this.dismissed = false;
				}
			} catch (error) {
				console.error('Failed to dismiss checklist:', error);
				// Revert on error
				this.dismissed = false;
			}
		},

		async undismiss() {
			// Immediately show the checklist for instant feedback
			this.dismissed = false;

			// Then save the state in the background
			const formData = new FormData();
			formData.append('action', 'rewardswp_show_checklist');
			formData.append('_ajax_nonce', window.rewardsWP?.nonce || '');

			try {
				const response = await fetch(window.ajaxurl || ajaxurl, {
					method: 'POST',
					body: formData
				});
				const data = await response.json();

				// If it failed, revert
				if (!data.success) {
					this.dismissed = true;
				}
			} catch (error) {
				console.error('Failed to show checklist:', error);
				// Revert on error
				this.dismissed = true;
			}
		},

		markTaskComplete(taskId) {
			// Only track explore_widget_settings - other tasks are tracked automatically
			if (taskId !== 'explore_widget_settings') {
				return;
			}

			// Fire and forget - no need to wait for response
			const formData = new FormData();
			formData.append('action', 'rewardswp_mark_widget_explored');
			formData.append('_ajax_nonce', window.rewardsWP?.nonce || '');
			fetch(window.ajaxurl || ajaxurl, { method: 'POST', body: formData });
		}
	}));
}