/**
 * Signocore Multilanguage - Admin JavaScript
 *
 * @package Signocore\Multilanguage
 */

(function ($) {
	'use strict';

	var SML = {
		/**
		 * Send an AJAX request with nonce verification.
		 *
		 * @param {string} action   - WordPress AJAX action name.
		 * @param {Object} data     - Additional data to send.
		 * @param {string} [method] - HTTP method, defaults to POST.
		 * @returns {jQuery.Deferred}
		 */
		ajax: function (action, data, method) {
			data = data || {};
			data.action = action;
			data._ajax_nonce = smlAdmin.nonce;

			return $.ajax({
				url: smlAdmin.ajaxUrl,
				type: method || 'POST',
				data: data,
				dataType: 'json',
			});
		},

		/**
		 * Initialize all admin features.
		 */
		init: function () {
			this.initTabs();
			this.initLangPills();
			this.initLanguageManagement();
			this.initLanguagePicker();
			this.initStrategyCards();
			this.initSelect2();
			this.initPurgeButtons();
			this.initMetaboxCopyContent();
			this.initMetaboxLinkExisting();
			this.initPermalinkSlugInputs();
		},

		/**
		 * Language pill-tab switching (Site Title & Tagline section).
		 */
		initLangPills: function () {
			$(document).on('click', '.sml-lang-pill', function (e) {
				e.preventDefault();

				var $pill = $(this);
				var lang = $pill.data('lang');
				var $card = $pill.closest('.sml-card-body');

				// Update active pill
				$card.find('.sml-lang-pill').removeClass('active');
				$pill.addClass('active');

				// Show/hide panels
				$card.find('.sml-lang-panel').removeClass('active').hide();
				$card.find('.sml-lang-panel[data-lang="' + lang + '"]').addClass('active').show();
			});
		},

		/**
		 * Settings page tab switching.
		 */
		initTabs: function () {
			var $tabs = $('.sml-settings-tabs');
			if (!$tabs.length) {
				return;
			}

			$tabs.on('click', '.sml-tab', function (e) {
				e.preventDefault();

				var $tab = $(this);
				var target = $tab.data('tab');

				// Update active tab
				$tabs.find('.sml-tab').removeClass('active');
				$tab.addClass('active');

				// Show target panel
				$('.sml-settings-panel').removeClass('active');
				$('#sml-panel-' + target).addClass('active');

				// Update URL hash without scrolling
				if (history.replaceState) {
					history.replaceState(null, null, '#' + target);
				}
			});

			// Restore tab from URL hash
			var hash = window.location.hash.replace('#', '');
			if (hash) {
				var $target = $tabs.find('[data-tab="' + hash + '"]');
				if ($target.length) {
					$target.trigger('click');
				}
			}
		},

		/**
		 * Language management (add/remove).
		 */
		initLanguageManagement: function () {
			// Add language (legacy AJAX handler)
			$(document).on('click', '.sml-add-language-btn', function (e) {
				e.preventDefault();

				var $btn = $(this);
				var code = $('#sml-add-language-select').val();

				if (!code) {
					return;
				}

				$btn.prop('disabled', true).addClass('sml-loading');

				SML.ajax('sml_add_language', { code: code })
					.done(function (response) {
						if (response.success) {
							window.location.reload();
						} else {
							alert(response.data || 'Failed to add language.');
						}
					})
					.fail(function () {
						alert('A server error occurred. Please try again.');
					})
					.always(function () {
						$btn.prop('disabled', false).removeClass('sml-loading');
					});
			});

			// Remove language
			$(document).on('click', '.sml-remove-language', function (e) {
				e.preventDefault();

				var $link = $(this);
				var code = $link.data('code');
				var name = $link.data('name') || code;

				if (!confirm('Are you sure you want to remove "' + name + '"? All translations for this language will be deleted.')) {
					return;
				}

				$link.css('opacity', '0.5').css('pointer-events', 'none');

				SML.ajax('sml_remove_language', { code: code })
					.done(function (response) {
						if (response.success) {
							window.location.reload();
						} else {
							alert(response.data || 'Failed to remove language.');
							$link.css('opacity', '').css('pointer-events', '');
						}
					})
					.fail(function () {
						alert('A server error occurred. Please try again.');
						$link.css('opacity', '').css('pointer-events', '');
					});
			});

			// Set default language
			$(document).on('click', '.sml-set-default-language', function (e) {
				e.preventDefault();

				var $link = $(this);
				var code = $link.data('code');

				$link.css('opacity', '0.5').css('pointer-events', 'none');

				SML.ajax('sml_set_default_language', { code: code })
					.done(function (response) {
						if (response.success) {
							window.location.reload();
						} else {
							alert(response.data || 'Failed to set default language.');
							$link.css('opacity', '').css('pointer-events', '');
						}
					})
					.fail(function () {
						alert('A server error occurred. Please try again.');
						$link.css('opacity', '').css('pointer-events', '');
					});
			});
		},

		/**
		 * Language picker search filter (Languages admin page).
		 */
		initLanguagePicker: function () {
			var $search = $('#sml-lang-picker-search');
			if (!$search.length) {
				return;
			}

			var $grid = $('#sml-lang-picker-grid');
			var $items = $grid.find('.sml-lang-picker-item');
			var $noResults = $('#sml-lang-picker-no-results');
			var $count = $('#sml-lang-picker-count');
			var totalCount = $items.length;

			$search.on('input', function () {
				var query = this.value.toLowerCase().trim();
				var visibleCount = 0;

				$items.each(function () {
					var $item = $(this);
					var name = ($item.data('name') || '').toLowerCase();
					var native = ($item.data('native') || '').toLowerCase();
					var code = ($item.data('code') || '').toLowerCase();
					var matches = !query || name.indexOf(query) !== -1 || native.indexOf(query) !== -1 || code.indexOf(query) !== -1;

					$item.toggleClass('hidden', !matches);
					if (matches) {
						visibleCount++;
					}
				});

				$noResults.toggle(visibleCount === 0);

				if ($count.length) {
					if (query && visibleCount < totalCount) {
						$count.text(visibleCount + ' of ' + totalCount + ' languages');
					} else {
						$count.text(totalCount + ' languages available');
					}
				}
			});

			// Focus search on page load
			$search.focus();
		},

		/**
		 * URL strategy radio card selection.
		 */
		initStrategyCards: function () {
			var $domainConfig = $('#sml-domain-mapping-config');

			function toggleDomainConfig(value) {
				if ($domainConfig.length) {
					$domainConfig[value === 'domain' ? 'slideDown' : 'slideUp'](200);
				}
			}

			// Set initial visibility on page load
			var $checked = $('.sml-strategy-option input[type="radio"]:checked');
			if ($checked.length) {
				toggleDomainConfig($checked.val());
			}

			$(document).on('change', '.sml-strategy-option input[type="radio"]', function () {
				$('.sml-strategy-option').removeClass('selected');
				$(this).closest('.sml-strategy-option').addClass('selected');
				toggleDomainConfig($(this).val());
			});

			// Live validation: secondary language domains must not match the home domain
			var homeDomain = $('.sml-domain-mapping-list').data('home-domain') || '';

			$(document).on('input', '.sml-domain-input', function () {
				var $input = $(this);
				var val = $input.val().replace(/^https?:\/\//, '').replace(/\/+$/, '');
				var $row = $input.closest('.sml-domain-mapping-row');
				var $error = $row.find('.sml-domain-error');

				if (val && val === homeDomain) {
					if (!$error.length) {
						$error = $('<span class="sml-domain-error"></span>');
						$input.after($error);
					}
					$error.text(smlAdmin.i18n?.domainSameAsHome || 'Cannot be the same as the default language domain.');
					$input.addClass('sml-input-error');
				} else {
					$error.remove();
					$input.removeClass('sml-input-error');
				}
			});
		},

		/**
		 * Initialize Select2 on styled selects.
		 */
		initSelect2: function () {
			if (typeof $.fn.select2 !== 'undefined') {
				$('select.sml-styled-select').select2();
			}
		},

		/**
		 * "Copy content from source" button in the translation metabox.
		 */
		initMetaboxCopyContent: function () {
			var $metabox = $('.sml-metabox');
			if (!$metabox.length) {
				return;
			}

			$metabox.on('click', '.sml-metabox__copy-btn', function () {
				var $btn = $(this);
				var $copy = $btn.closest('.sml-metabox__copy');
				var sourceId = $copy.data('source-id');
				var targetId = $metabox.data('post-id');

				if (!sourceId || !targetId) {
					return;
				}

				if (!confirm('This will replace the current title, content, excerpt, and metadata. Continue?')) {
					return;
				}

				$btn.prop('disabled', true).addClass('sml-loading');

				SML.ajax('sml_copy_source_content', {
					source_post_id: sourceId,
					target_post_id: targetId,
				})
					.done(function (response) {
						if (!response.success) {
							alert(response.data || 'Failed to copy content.');
							return;
						}

						$btn.text('Copied!');
						setTimeout(function () {
							window.location.reload();
						}, 500);
					})
					.fail(function () {
						alert('A server error occurred. Please try again.');
					})
					.always(function () {
						$btn.prop('disabled', false).removeClass('sml-loading');
					});
			});
		},

		/**
		 * "Link existing post" search in the translation metabox.
		 */
		initMetaboxLinkExisting: function () {
			var $metabox = $('.sml-metabox');
			if (!$metabox.length) {
				return;
			}

			var searchTimer = null;

			// Toggle search row
			$metabox.on('click', '.sml-metabox__link-btn', function () {
				var lang = $(this).data('lang');
				var $row = $metabox.find('.sml-metabox__link-row[data-lang="' + lang + '"]');
				$row.toggle();

				if ($row.is(':visible')) {
					$row.find('.sml-metabox__search-input').val('').focus();
					$row.find('.sml-metabox__search-results').empty();
				}
			});

			// Search with debounce
			$metabox.on('input', '.sml-metabox__search-input', function () {
				var $input = $(this);
				var query = $input.val();
				var $results = $input.siblings('.sml-metabox__search-results');

				clearTimeout(searchTimer);

				if (query.length < 2) {
					$results.empty();
					return;
				}

				searchTimer = setTimeout(function () {
					$results.html('<div class="sml-metabox__search-loading">Searching...</div>');

					SML.ajax('sml_search_linkable_posts', {
						search: query,
						post_type: $metabox.data('post-type'),
						exclude_post_id: $metabox.data('post-id'),
					})
						.done(function (response) {
							$results.empty();

							if (!response.success || !response.data.posts.length) {
								$results.html('<div class="sml-metabox__search-empty">No posts found.</div>');
								return;
							}

							$.each(response.data.posts, function (i, post) {
								var $item = $('<div class="sml-metabox__search-result"></div>');
								$item.attr('data-post-id', post.id);
								$item.html(
									'<span class="sml-metabox__search-title">' +
										$('<span>').text(post.title || '(no title)').html() +
									'</span>' +
									'<span class="sml-metabox__search-status">' +
										$('<span>').text(post.status).html() +
									'</span>'
								);
								$results.append($item);
							});
						})
						.fail(function () {
							$results.html('<div class="sml-metabox__search-empty">Search failed.</div>');
						});
				}, 300);
			});

			// Click a search result to link
			$metabox.on('click', '.sml-metabox__search-result', function () {
				var $result = $(this);
				var targetId = $result.data('post-id');
				var title = $result.find('.sml-metabox__search-title').text();
				var $row = $result.closest('.sml-metabox__link-row');
				var lang = $row.data('lang');

				if (!confirm('Link "' + title + '" as the ' + lang + ' translation?')) {
					return;
				}

				$result.css('opacity', '0.5');

				SML.ajax('sml_link_translation', {
					source_id: $metabox.data('post-id'),
					target_id: targetId,
					lang: lang,
				})
					.done(function (response) {
						if (response.success) {
							window.location.reload();
						} else {
							alert(response.data || 'Could not link post.');
							$result.css('opacity', '');
						}
					})
					.fail(function () {
						alert('A server error occurred. Please try again.');
						$result.css('opacity', '');
					});
			});
		},

		/**
		 * Purge button handler (e.g. license disable).
		 */
		initPurgeButtons: function () {
			$(document).on('click', '.sml-button.purge', function (e) {
				e.preventDefault();

				var $btn = $(this);
				var confirmMsg = $btn.data('confirm');

				if (confirmMsg && !confirm(confirmMsg)) {
					return;
				}

				$btn.prop('disabled', true).addClass('sml-loading');

				SML.ajax('sml_purge_license', {})
					.done(function (response) {
						if (response.success) {
							window.location.reload();
						} else {
							alert(response.data || 'Failed.');
						}
					})
					.fail(function () {
						alert('A server error occurred. Please try again.');
					})
					.always(function () {
						$btn.prop('disabled', false).removeClass('sml-loading');
					});
			});
		},

		/**
		 * Sanitize permalink slug inputs to URL-safe characters.
		 */
		initPermalinkSlugInputs: function () {
			$(document).on('input', '.sml-permalink-slug-input', function () {
				var raw = this.value;
				var hasLeading = raw.charAt(0) === '/';
				var hasTrailing = raw.length > 1 && raw.charAt(raw.length - 1) === '/';

				// Sanitize the inner part (without boundary slashes)
				var inner = raw.replace(/^\//, '').replace(/\/$/, '');
				inner = inner
					.toLowerCase()
					.replace(/\s+/g, '-')
					.replace(/[^a-z0-9\-æøåäöü]/g, '')
					.replace(/-{2,}/g, '-')
					.replace(/^-/, '');

				this.value = (hasLeading ? '/' : '') + inner + (hasTrailing ? '/' : '');
			});

			// Re-add slashes on blur if user removed them
			$(document).on('blur', '.sml-permalink-slug-input', function () {
				var val = this.value.replace(/^\//, '').replace(/\/$/, '');
				if (val !== '') {
					this.value = '/' + val + '/';
				}
			});
		},
	};

	$(document).ready(function () {
		SML.init();
	});
})(jQuery);
