/**
 * Wisewand Dashboard Admin JS
 * Handles dashboard interactions, auto-refresh, and automation triggers.
 */
jQuery(document).ready(function ($) {
	'use strict';

	const Dashboard = {
		init: function () {
			this.initAutoRefresh();
			this.initTooltips();
			this.initAutomation();
		},

		initAutoRefresh: function () {
			// Auto-refresh dashboard every 60 seconds to keep metrics live
			setInterval(function () {
				// Only refresh if tab is active
				if (!document.hidden) {
					// Simple reload for now to fetch fresh PHP data
					// In a future update, we can make this an AJAX partial update
					// location.reload(); 
					// NOTE: Disabling auto-reload for now to prevent user interruption
				}
			}, 60000);
		},

		initTooltips: function () {
			// Simple tooltip behavior if needed
			$('.metric-card').on('mouseenter', function () {
				$(this).addClass('hovered');
			}).on('mouseleave', function () {
				$(this).removeClass('hovered');
			});
		},

		initAutomation: function () {
			$('.run-automation').on('click', function (e) {
				e.preventDefault();
				const $btn = $(this);
				const action = $btn.data('action');
				const originalText = $btn.text();

				if ($btn.prop('disabled')) return;

				// Set loading state
				$btn.prop('disabled', true).text('Running...');

				$.ajax({
					url: wisewandDashboard.ajaxUrl,
					type: 'POST',
					data: {
						action: action,
						nonce: wisewandDashboard.nonce
					},
					success: function (response) {
						if (response.success) {
							$btn.text('Done!').addClass('ww-btn-success');
							setTimeout(function () {
								$btn.prop('disabled', false).text(originalText).removeClass('ww-btn-success');
								// Optional: Reload page to show updated stats
								// location.reload();
							}, 2000);
						} else {
							alert('Error: ' + (response.data.message || 'Unknown error'));
							$btn.prop('disabled', false).text(originalText);
						}
					},
					error: function () {
						alert('Network error occurred.');
						$btn.prop('disabled', false).text(originalText);
					}
				});
			});
		}
	};

	Dashboard.init();
});
