/**
 * Dashboard Page JavaScript
 *
 * @package Wisewand
 * @since 1.0.0
 */

jQuery(document).ready(function($) {
	'use strict';

	// Auto-refresh every 2 minutes
	setInterval(function() {
		location.reload();
	}, 120000);

	// Manual refresh
	$('#refresh-dashboard').on('click', function() {
		const $btn = $(this);
		const originalText = $btn.text();

		// Disable button and show loading
		$btn.prop('disabled', true).text('🔄 Refreshing...');

		console.log('🔄 Refresh Dashboard: Triggering CRON...');

		// Trigger actual CRON operations
		$.ajax({
			url: wisewandDashboard.ajaxUrl,
			type: 'POST',
			data: {
				action: 'wisewand_manual_cron_trigger',
				nonce: wisewandDashboard.nonce
			},
			success: function(response) {
				console.log('✅ CRON triggered successfully:', response);

				if (response.success) {
					// Show success feedback briefly
					$btn.text('✅ Updated!');

					// Reload after brief delay
					setTimeout(function() {
						location.reload();
					}, 500);
				} else {
					console.error('CRON trigger failed:', response);
					$btn.prop('disabled', false).text(originalText);
					alert('Failed to refresh: ' + (response.data?.message || 'Unknown error'));
				}
			},
			error: function(xhr, status, error) {
				console.error('AJAX error:', error);
				$btn.prop('disabled', false).text(originalText);
				alert('Network error during refresh');
			}
		});
	});

	// Manual CRON Trigger
	$('#manual-trigger-cron').on('click', function() {
		const $btn = $(this);
		const $logsOutput = $('#cron-logs-output');

		$btn.prop('disabled', true).text('▶️ Running CRON...');
		$logsOutput.show().html('<div style="color: #3b82f6;">⏳ Initializing CRON...</div>');

		console.log('🔄 Manual CRON Trigger: Starting...');

		function addLog(message, color = '#e2e8f0') {
			const timestamp = new Date().toLocaleTimeString();
			$logsOutput.append(`<div style="color: ${color};">[${timestamp}] ${message}</div>`);
			$logsOutput.scrollTop($logsOutput[0].scrollHeight);
		}

		$.ajax({
			url: wisewandDashboard.ajaxUrl,
			type: 'POST',
			timeout: 120000, // 2 min timeout
			data: {
				action: 'wisewand_manual_full_cron_trigger',
				nonce: wisewandDashboard.nonce
			},
			success: function(response) {
				console.log('✅ CRON completed:', response);

				if (response.success) {
					const summary = response.data.summary || {};

					addLog('✅ CRON Completed Successfully!', '#10b981');
					addLog(`Generated: ${summary.generated || 0}`, '#64748b');
					addLog(`Status Checked: ${summary.status_checked || 0}`, '#64748b');
					addLog(`Imported: ${summary.imported || 0}`, '#64748b');
					addLog(`Retried: ${summary.retried || 0}`, '#64748b');
					addLog(`Elapsed: ${summary.elapsed || 0}s`, '#64748b');

					if (response.data.logs && response.data.logs.length > 0) {
						addLog('--- Detailed Logs ---', '#3b82f6');
						response.data.logs.forEach(log => addLog(log, '#94a3b8'));
					}

					$btn.text('✅ Completed!');

					setTimeout(() => {
						location.reload();
					}, 2000);
				} else {
					addLog('❌ CRON Failed: ' + (response.data?.message || 'Unknown error'), '#ef4444');
					$btn.prop('disabled', false).text('▶️ Run CRON Manually');
				}
			},
			error: function(xhr, status, error) {
				console.error('❌ CRON AJAX error:', error);
				addLog('❌ Network Error: ' + error, '#ef4444');
				$btn.prop('disabled', false).text('▶️ Run CRON Manually');
			}
		});
	});

	// Clickable metrics - filter calendar
	$('.metric-card[data-filter]').on('click', function() {
		const filter = $(this).data('filter');
		const calendarUrl = wisewandDashboard.calendarUrl;
		window.location.href = calendarUrl + '&filter=' + filter;
	});

	// Clickable content types - filter calendar
	$('.content-type-item[data-type-filter]').on('click', function() {
		const typeFilter = $(this).data('type-filter');
		const calendarUrl = wisewandDashboard.calendarUrl;
		window.location.href = calendarUrl + '&type=' + typeFilter;
	});

	// Clickable recent activity - open in calendar
	$('.activity-item[data-entry-id]').on('click', function() {
		const entryId = $(this).data('entry-id');
		const calendarUrl = wisewandDashboard.calendarUrl;
		window.location.href = calendarUrl + '&entry=' + entryId;
	});

	// Imported metric - scroll to imported articles section
	$('.metric-card[data-view="imported"]').on('click', function() {
		const $importedSection = $('.dashboard-imported-articles');
		if ($importedSection.length) {
			$('html, body').animate({
				scrollTop: $importedSection.offset().top - 100
			}, 600);
			$importedSection.css({
				'box-shadow': '0 0 0 3px #6366f1',
				'transition': 'box-shadow 0.3s'
			});
			setTimeout(() => {
				$importedSection.css('box-shadow', 'none');
			}, 2000);
		}
	});
});
