/**
 * Admin Settings Page JavaScript
 *
 * @package Wisewand
 * @since 1.0.0
 */

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

	/**
	 * Show WordPress admin notice
	 * @param {string} type - Notice type: 'success', 'error', 'warning', 'info'
	 * @param {string} message - Message to display
	 */
	function showAdminNotice(type, message) {
		// Remove any existing Wisewand notices
		$('.wisewand-admin-notice').remove();

		// Create notice element
		const $notice = $('<div>')
			.addClass('notice notice-' + type + ' is-dismissible wisewand-admin-notice')
			.html('<p>' + message + '</p>');

		// Add dismiss button functionality
		const $dismissButton = $('<button>')
			.addClass('notice-dismiss')
			.attr('type', 'button')
			.html('<span class="screen-reader-text">Dismiss this notice.</span>')
			.on('click', function() {
				$notice.fadeOut(300, function() {
					$(this).remove();
				});
			});

		$notice.append($dismissButton);

		// Insert at top of page
		if ($('.wrap > h1').length > 0) {
			$notice.insertAfter('.wrap > h1');
		} else if ($('.wrap').length > 0) {
			$notice.prependTo('.wrap');
		} else {
			$notice.prependTo('#wpbody-content');
		}

		// Auto-dismiss after 8 seconds for non-error notices
		if (type !== 'error') {
			setTimeout(function() {
				$notice.fadeOut(300, function() {
					$(this).remove();
				});
			}, 8000);
		}
	}

	// Generate secret key
	$('#generate-secret').on('click', function() {
		const secret = Array(65).join().split(',').map(() => Math.random().toString(36).charAt(2)).join('');
		$(this).prev('input').val(secret);
	});

	// Toggle OpenAI API key visibility
	$('#toggle-openai-key').on('click', function(e) {
		e.preventDefault();
		const $input = $('#wisewand_openai_api_key');
		const type = $input.attr('type') === 'password' ? 'text' : 'password';
		$input.attr('type', type);
	});

	// Inline images range slider - Show/hide count config
	$('#toggle-inline-images-setting').on('change', function() {
		$('#settings-inline-count-config').toggle($(this).is(':checked'));
	});

	// Inline images range slider - Update display and cost
	$('#settings-inline-count-slider').on('input', function() {
		const count = parseInt($(this).val()) || 1;
		const cost = count * 0.5;
		$('#settings-inline-count-value').text(count + ' ' + wisewandSettings.i18n.images);
		$('#settings-inline-count-cost').text(count + ' × 0.5 = ' + cost.toFixed(1) + ' ' + wisewandSettings.i18n.credits);
		$('#settings-inline-cost').text('+' + cost.toFixed(1));
	});

	// Test API connection
	$('#test-api').on('click', function() {
		const $btn = $(this);
		$btn.prop('disabled', true).text(wisewandSettings.i18n.testing);

		$.post(wisewandSettings.ajaxUrl, {
			action: 'wisewand_test_api_connection',
			nonce: wisewandSettings.nonces.apiTest
		}, function(response) {
			if (response.success) {
				alert(wisewandSettings.i18n.apiSuccess);
			} else {
				alert(wisewandSettings.i18n.apiFailed + ' ' + response.data.message);
			}
		}).always(function() {
			$btn.prop('disabled', false).text(wisewandSettings.i18n.testApi);
		});
	});

	// Debug projects
	$('#debug-projects').on('click', function() {
		const $btn = $(this);
		$btn.prop('disabled', true).text(wisewandSettings.i18n.debugging);

		$.post(wisewandSettings.ajaxUrl, {
			action: 'wisewand_debug_projects',
			nonce: wisewandSettings.nonces.debug
		}, function(response) {
			if (response.success) {
				const data = response.data;
				let debugInfo = 'Projects Debug Info:\n\n';
				debugInfo += 'Total projects: ' + (data.total_projects || 0) + '\n\n';

				if (data.first_project_raw) {
					debugInfo += 'First project structure:\n';
					debugInfo += JSON.stringify(data.first_project_raw, null, 2);
				}

				alert(debugInfo);
			} else {
				alert(wisewandSettings.i18n.debugFailed + ' ' + response.data.message);
			}
		}).always(function() {
			$btn.prop('disabled', false).text(wisewandSettings.i18n.debugProjects);
		});
	});

	/**
	 * Load projects for calendar settings dropdown
	 */
	function loadProjectsForSettings() {
		const $select = $('#default-project-select');

		// Check if dropdown exists
		if ($select.length === 0) {
			console.log('Wisewand: Projects dropdown not found on this page');
			return;
		}

		console.log('Wisewand: Loading projects...');
		console.log('Wisewand: Using AJAX URL:', wisewandSettings.ajaxUrl);
		console.log('Wisewand: Using calendar nonce:', wisewandSettings.nonces.calendar);

		$.ajax({
			url: wisewandSettings.ajaxUrl,
			type: 'POST',
			data: {
				action: 'wisewand_get_projects',
				nonce: wisewandSettings.nonces.calendar
			},
			success: function(response) {
				console.log('Wisewand: Projects AJAX response:', response);

				if (response.success && response.data && response.data.projects) {
					const projects = response.data.projects;
					console.log('Wisewand: Found ' + projects.length + ' projects');

					$select.html('<option value="">' + wisewandSettings.i18n.selectProject + '</option>');

					projects.forEach(function(project) {
						const option = $('<option></option>')
							.val(project.id)
							.text(project.name + (project.website ? ' (' + project.website + ')' : ''))
							.data('project', project);
						$select.append(option);
					});

					if (wisewandSettings.currentProjectId) {
						$select.val(wisewandSettings.currentProjectId);
						$select.trigger('change');
					}

					console.log('Wisewand: Projects loaded successfully');
				} else {
					console.error('Wisewand: Failed to load projects:', response);
					const errorMsg = response.data && response.data.message ? response.data.message : 'Unknown error';
					$select.html('<option value="">⚠️ Error: ' + errorMsg + '</option>');

					// Show admin notice
					showAdminNotice('error', 'Failed to load Wisewand projects: ' + errorMsg + '. Check browser console for details.');
				}
			},
			error: function(xhr, status, error) {
				console.error('Wisewand: AJAX error loading projects:', {xhr: xhr, status: status, error: error});
				$select.html('<option value="">⚠️ Network error - please refresh</option>');

				// Show admin notice
				const detailedError = xhr.responseText || error || status;
				showAdminNotice('error', 'Network error loading projects: ' + detailedError + '. Please refresh the page.');
			}
		});
	}

	/**
	 * Load personas for settings dropdowns
	 */
	function loadPersonasForSettings() {
		const $selectFr = $('#persona-fr-select');
		const $selectEn = $('#persona-en-select');

		// Check if dropdowns exist
		if ($selectFr.length === 0 && $selectEn.length === 0) {
			console.log('Wisewand: Persona dropdowns not found on this page');
			return;
		}

		console.log('Wisewand: Loading personas...');
		console.log('Wisewand: Using AJAX URL:', wisewandSettings.ajaxUrl);
		console.log('Wisewand: Using calendar nonce:', wisewandSettings.nonces.calendar);

		$.ajax({
			url: wisewandSettings.ajaxUrl,
			type: 'POST',
			data: {
				action: 'wisewand_get_personas',
				nonce: wisewandSettings.nonces.calendar
			},
			success: function(response) {
				console.log('Wisewand: Personas AJAX response:', response);

				if (response.success && response.data && response.data.personas) {
					const personas = response.data.personas;
					console.log('Wisewand: Found ' + personas.length + ' personas');

					// Populate French personas
					if ($selectFr.length > 0) {
						$selectFr.html('<option value="">' + wisewandSettings.i18n.selectPersona + '</option>');
						personas.forEach(function(persona) {
							const option = $('<option></option>')
								.val(persona.id)
								.text(persona.name + (persona.description ? ' - ' + persona.description : ''));
							$selectFr.append(option);
						});
						if (wisewandSettings.currentPersonaFr) {
							$selectFr.val(wisewandSettings.currentPersonaFr);
						}
					}

					// Populate English personas
					if ($selectEn.length > 0) {
						$selectEn.html('<option value="">' + wisewandSettings.i18n.selectPersona + '</option>');
						personas.forEach(function(persona) {
							const option = $('<option></option>')
								.val(persona.id)
								.text(persona.name + (persona.description ? ' - ' + persona.description : ''));
							$selectEn.append(option);
						});
						if (wisewandSettings.currentPersonaEn) {
							$selectEn.val(wisewandSettings.currentPersonaEn);
						}
					}

					console.log('Wisewand: Personas loaded successfully');
				} else {
					console.error('Wisewand: Failed to load personas:', response);
					const errorMsg = response.data && response.data.message ? response.data.message : 'Unknown error';
					if ($selectFr.length > 0) $selectFr.html('<option value="">⚠️ Error: ' + errorMsg + '</option>');
					if ($selectEn.length > 0) $selectEn.html('<option value="">⚠️ Error: ' + errorMsg + '</option>');

					// Show admin notice
					showAdminNotice('error', 'Failed to load Wisewand personas: ' + errorMsg + '. Check browser console for details.');
				}
			},
			error: function(xhr, status, error) {
				console.error('Wisewand: AJAX error loading personas:', {xhr: xhr, status: status, error: error});
				if ($selectFr.length > 0) $selectFr.html('<option value="">⚠️ Network error - please refresh</option>');
				if ($selectEn.length > 0) $selectEn.html('<option value="">⚠️ Network error - please refresh</option>');

				// Show admin notice
				const detailedError = xhr.responseText || error || status;
				showAdminNotice('error', 'Network error loading personas: ' + detailedError + '. Please refresh the page.');
			}
		});
	}

	// When project changes, load its details to show brief
	$('#default-project-select').on('change', function() {
		const projectId = $(this).val();

		if (!projectId) {
			$('#project-brief-row').hide();
			return;
		}

		// Fetch project details
		$.post(wisewandSettings.ajaxUrl, {
			action: 'wisewand_get_project_details',
			project_id: projectId,
			nonce: wisewandSettings.nonces.settings
		}, function(response) {
			if (response.success && response.data.project) {
				const brief = response.data.project.brief || '';
				const charCount = brief.length;

				$('#project-brief-display').val(brief);
				$('#brief-char-count').text(charCount);

				// Show warning if > 500 chars
				if (charCount > 500) {
					$('#brief-warning').show();
				} else {
					$('#brief-warning').hide();
				}

				$('#project-brief-row').show();
			}
		});
	});

	// Remove API key
	$('#remove-api-key').on('click', function(e) {
		e.preventDefault();

		if (!confirm('Are you sure you want to remove the Wisewand API key? This will disable all Wisewand features.')) {
			return;
		}

		const $button = $(this);
		const originalText = $button.text();

		$button.prop('disabled', true).text('Removing...');

		$.ajax({
			url: wisewandSettings.ajaxUrl,
			type: 'POST',
			data: {
				action: 'wisewand_remove_api_key',
				nonce: wisewandSettings.nonces.settings
			},
			success: function(response) {
				if (response.success) {
					location.reload();
				} else {
					alert('Failed to remove API key: ' + (response.data?.message || 'Unknown error'));
					$button.prop('disabled', false).text(originalText);
				}
			},
			error: function() {
				alert('Network error. Please try again.');
				$button.prop('disabled', false).text(originalText);
			}
		});
	});

	// Load data on page ready
	loadProjectsForSettings();
	loadPersonasForSettings();
});
