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

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

		// Use localized data from wp_localize_script
		const i18n = wisewandArticles.i18n;
		const nonces = wisewandArticles.nonces;
		const ajaxurl = wisewandArticles.ajaxUrl;

		// Select all checkbox (both header and footer)
		$('#cb-select-all, #cb-select-all-footer').on(
			'change',
			function () {
				$('input[name="article_ids[]"]').prop('checked', this.checked);
			}
		);

		// Bulk actions (both top and bottom)
		$('#bulk-action-submit').on(
			'click',
			function (e) {
				e.preventDefault();

				const action = $('#bulk-action-selector-bottom').val() || $('#bulk-action-selector').val();
				const selectedArticles = $('input[name="article_ids[]"]:checked');

				if (!action) {
					alert(i18n.selectBulkAction);
					return;
				}

				if (selectedArticles.length === 0) {
					alert(i18n.selectOneArticle);
					return;
				}

				if (!confirm(i18n.confirmBulkAction + ' ' + selectedArticles.length + ' ' + i18n.articles)) {
					return;
				}

				const articleIds = selectedArticles.map(
					function () {
						return $(this).val();
					}
				).get();

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

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

				let ajaxAction = '';
				switch (action) {
					case 'import_ready':
						ajaxAction = 'wisewand_bulk_import';
						break;
					case 'run_generation':
						ajaxAction = 'wisewand_bulk_generate';
						break;
					default:
						$button.prop('disabled', false).text(originalText);
						alert(i18n.unknownAction);
						return;
				}

				$.ajax(
					{
						url: ajaxurl,
						type: 'POST',
						data: {
							action: ajaxAction,
							nonce: nonces.bulk,
							article_ids: articleIds
						},
						success: function (response) {
							if (response.success) {
								alert(i18n.bulkSuccess);
								location.reload();
							} else {
								alert(i18n.bulkFailed + ' ' + ((response.data && response.data.message) || 'Unknown error'));
							}
						},
						error: function () {
							alert(i18n.bulkNetworkError);
						},
						complete: function () {
							$button.prop('disabled', false).text(originalText);
						}
					}
				);
			}
		);

		// Refresh articles list
		$('.wisewand-refresh-articles').on(
			'click',
			function (e) {
				e.preventDefault();
				location.reload();
			}
		);

		// Import article
		$('.wisewand-import-article').on(
			'click',
			function (e) {
				e.preventDefault();

				const $button = $(this);
				const articleId = $button.data('article-id');
				const originalText = $button.text();

				// Get all user preferences for this article
				const $row = $button.closest('tr');
				const $languageSelect = $row.find('select.language-override-select');
				const $authorSelect = $row.find('select.author-select');
				const $categoriesSelect = $row.find('select.categories-select');
				const $postTypeSelect = $row.find('select.post-type-select');
				const $publishStateSelect = $row.find('select.publish-state-select');
				const $publishDateInput = $row.find('input.publish-date-input');
				const $productSelect = $row.find('select.existing-product-select');
				const $categorySelect = $row.find('select.parent-category-select');

				const languageOverride = $languageSelect.length ? $languageSelect.val() : '';
				const postAuthor = $authorSelect.length ? $authorSelect.val() : '';
				const postCategories = $categoriesSelect.length ? $categoriesSelect.val() : [];
				const postType = $postTypeSelect.length ? $postTypeSelect.val() : 'post';
				let publishState = $publishStateSelect.length ? $publishStateSelect.val() : 'draft';
				const publishDate = $publishDateInput.length ? $publishDateInput.val() : '';
				const existingProduct = $productSelect.length && $productSelect.is(':visible') ? $productSelect.val() : '';
				const existingCategory = $categorySelect.length && $categorySelect.is(':visible') ? $categorySelect.val() : '';

				// Get content type from URL parameters or default
				const urlParams = new URLSearchParams(window.location.search);
				const contentType = urlParams.get('content_type') || 'articles';

				// Smart validation and auto-correction
				if (publishDate) {
					const selectedDateTime = new Date(publishDate);
					const now = new Date();

					if (selectedDateTime > now && publishState !== 'future') {
						// Future date but not set to Schedule - auto-correct
						publishState = 'future';
						$publishStateSelect.val('future');
						localStorage.setItem('wisewand_publish_state_' + articleId, 'future');

						// Visual feedback for auto-correction
						$publishStateSelect.css('background-color', '#e8f4fd').delay(1500).queue(
							function () {
								$(this).css('background-color', '').dequeue();
							}
						);
					} else if (selectedDateTime <= now && publishState === 'future') {
						// Past/current date but set to Schedule - auto-correct to Publish
						publishState = 'publish';
						$publishStateSelect.val('publish');
						localStorage.setItem('wisewand_publish_state_' + articleId, 'publish');

						// Visual feedback for auto-correction
						$publishStateSelect.css('background-color', '#e8f4fd').delay(1500).queue(
							function () {
								$(this).css('background-color', '').dequeue();
							}
						);
					}
				}

				// Final validation
				if (publishState === 'future' && !publishDate) {
					alert(i18n.selectPublishDate);
					return;
				}

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

				$.ajax(
					{
						url: ajaxurl,
						type: 'POST',
						data: {
							action: 'wisewand_import_article',
							nonce: nonces.import,
							article_id: articleId,
							content_type: contentType,
							language_override: languageOverride,
							post_author: postAuthor,
							post_categories: postCategories,
							post_type: postType,
							publish_state: publishState,
							publish_date: publishDate,
							existing_product: existingProduct,
							existing_category: existingCategory
						},
						success: function (response) {
							if (response.success) {
								$button.text(i18n.imported).removeClass('button-primary').addClass('button-secondary');

								const data = response.data;
								let successMessage = i18n.contentImported;
								let editUrl = data.edit_url;

								// Customize message based on import type
								if (data.category_id) {
									const taxonomy = data.taxonomy || 'category';
									if (taxonomy === 'product_cat') {
										successMessage = i18n.wooCommerceCategoryImported;
									} else {
										successMessage = i18n.wordPressCategoryImported;
									}
								} else if (data.post_id) {
									successMessage = i18n.postImported;
								}

								// Update button to edit link
								if (editUrl) {
									$button.replaceWith('<a href="' + editUrl + '" class="button button-secondary" target="_blank">' + i18n.edit + '</a>');
								}

								// Trigger custom event for UI updates
								$(document).trigger(
									'wisewand_import_success',
									{
										article_id: articleId,
										post_id: data.post_id,
										category_id: data.category_id,
										edit_url: editUrl,
										operation: data.operation
									}
								);

								// Show success notice
								$('<div class="notice notice-success is-dismissible"><p><strong>' + successMessage + '</strong></p></div>')
									.insertAfter('.wp-header-end')
									.delay(4000)
									.fadeOut();
							} else {
								alert(i18n.importFailed + ' ' + ((response.data && response.data.message) || 'Unknown error'));
								$button.prop('disabled', false).text(originalText);
							}
						},
						error: function () {
							alert(i18n.importNetworkError);
							$button.prop('disabled', false).text(originalText);
						}
					}
				);
			}
		);

		// Run generation
		$('.wisewand-run-generation').on(
			'click',
			function (e) {
				e.preventDefault();

				const $button = $(this);
				const articleId = $button.data('article-id');
				const originalText = $button.text();

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

				$.ajax(
					{
						url: ajaxurl,
						type: 'POST',
						data: {
							action: 'wisewand_run_generation',
							nonce: nonces.generation,
							article_id: articleId
						},
						success: function (response) {
							if (response.success) {
								$button.text(i18n.generationStarted);
								setTimeout(
									function () {
										location.reload();
									},
									2000
								);
							} else {
								alert(i18n.generationFailed + ' ' + ((response.data && response.data.message) || 'Unknown error'));
								$button.prop('disabled', false).text(originalText);
							}
						},
						error: function () {
							alert(i18n.generationNetworkError);
							$button.prop('disabled', false).text(originalText);
						}
					}
				);
			}
		);

		// Language override functionality
		$('.language-override-select').on(
			'change',
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const selectedLang = $select.val();

				// Store language override for this article
				if (selectedLang) {
					localStorage.setItem('wisewand_lang_override_' + articleId, selectedLang);
					$select.next('small').find('strong:last').text(selectedLang.toUpperCase());
				} else {
					localStorage.removeItem('wisewand_lang_override_' + articleId);
				}
			}
		);

		// Load saved language overrides
		$('.language-override-select').each(
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const savedLang = localStorage.getItem('wisewand_lang_override_' + articleId);

				if (savedLang) {
					$select.val(savedLang);
				}
			}
		);

		// Publish state change handling
		$('.publish-state-select').on(
			'change',
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const selectedState = $select.val();
				const $row = $select.closest('tr');
				const $dateInput = $row.find('input.publish-date-input');

				// Store the state for this article
				localStorage.setItem('wisewand_publish_state_' + articleId, selectedState);

				// Show/hide date picker based on state
				if (selectedState === 'future') {
					$dateInput.parent().show();
					// Set min date to now for scheduled posts
					const now = new Date();
					const year = now.getFullYear();
					const month = String(now.getMonth() + 1).padStart(2, '0');
					const day = String(now.getDate()).padStart(2, '0');
					const hours = String(now.getHours()).padStart(2, '0');
					const minutes = String(now.getMinutes()).padStart(2, '0');
					$dateInput.attr('min', year + '-' + month + '-' + day + 'T' + hours + ':' + minutes);

					// Set default to 1 hour from now if empty
					if (!$dateInput.val()) {
						now.setHours(now.getHours() + 1);
						const newYear = now.getFullYear();
						const newMonth = String(now.getMonth() + 1).padStart(2, '0');
						const newDay = String(now.getDate()).padStart(2, '0');
						const newHours = String(now.getHours()).padStart(2, '0');
						const newMinutes = String(now.getMinutes()).padStart(2, '0');
						$dateInput.val(newYear + '-' + newMonth + '-' + newDay + 'T' + newHours + ':' + newMinutes);
					}
				} else {
					$dateInput.parent().hide();
				}
			}
		);

		// Load saved publish states
		$('.publish-state-select').each(
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const savedState = localStorage.getItem('wisewand_publish_state_' + articleId);

				if (savedState) {
					$select.val(savedState);
					$select.trigger('change'); // Trigger the change handler
				}
			}
		);

		// Author preference handling
		$('.author-select').on(
			'change',
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const selectedAuthor = $select.val();

				if (selectedAuthor) {
					localStorage.setItem('wisewand_author_' + articleId, selectedAuthor);
				} else {
					localStorage.removeItem('wisewand_author_' + articleId);
				}
			}
		);

		// Load saved author preferences
		$('.author-select').each(
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const savedAuthor = localStorage.getItem('wisewand_author_' + articleId);

				if (savedAuthor) {
					$select.val(savedAuthor);
				}
			}
		);

		// Category preference handling
		$('.categories-select').on(
			'change',
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const selectedCategories = $select.val();

				if (selectedCategories && selectedCategories.length > 0) {
					localStorage.setItem('wisewand_categories_' + articleId, JSON.stringify(selectedCategories));
				} else {
					localStorage.removeItem('wisewand_categories_' + articleId);
				}
			}
		);

		// Load saved category preferences
		$('.categories-select').each(
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const savedCategories = localStorage.getItem('wisewand_categories_' + articleId);

				if (savedCategories) {
					try {
						const categories = JSON.parse(savedCategories);
						$select.val(categories);
					} catch (e) {
						// Invalid JSON, ignore
					}
				}
			}
		);

		// Post type change handling
		$('.post-type-select').on(
			'change',
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const selectedType = $select.val();
				const $row = $select.closest('tr');

				// Store the type for this article
				localStorage.setItem('wisewand_post_type_' + articleId, selectedType);

				// Show/hide product/category selectors based on post type
				if (selectedType === 'product') {
					$row.find('.existing-product-select').parent().show();
					$row.find('.categories-select').parent().hide();
				} else {
					$row.find('.existing-product-select').parent().hide();
					$row.find('.categories-select').parent().show();
				}

				// For product_variation show parent product selector
				if (selectedType === 'product_variation') {
					$row.find('.existing-product-select').parent().show();
				}

				// For category types show parent category selector
				if (selectedType === 'wc_product_category' || selectedType === 'wp_category') {
					$row.find('.parent-category-select').parent().show();
					$row.find('.categories-select').parent().hide();
				} else {
					$row.find('.parent-category-select').parent().hide();
				}
			}
		);

		// Load saved post type preferences
		$('.post-type-select').each(
			function () {
				const $select = $(this);
				const articleId = $select.data('article-id');
				const savedType = localStorage.getItem('wisewand_post_type_' + articleId);

				if (savedType) {
					$select.val(savedType);
					$select.trigger('change'); // Trigger the change handler
				}
			}
		);
	}
);
