/**
 * Site-page picker — import URLs from the site's own published content
 * instead of pasting them manually.
 *
 * @package ContentPerformanceAnalyzer
 * @since   1.2.0
 */
(function ($) {
	'use strict';

	if (typeof cpanalyzer_site_pages === 'undefined') {
		return;
	}

	var config = cpanalyzer_site_pages;

	var $loadButton = $('#cpanalyzer-load-site-pages');
	var $picker = $('#cpanalyzer-site-pages-picker');
	var $list = $('#cpanalyzer-site-pages-list');
	var $selectAll = $('#cpanalyzer-select-all-pages');
	var $count = $('#cpanalyzer-selected-count');
	var $importButton = $('#cpanalyzer-import-selected');
	var $status = $('#cpanalyzer-import-status');

	if (!$loadButton.length) {
		return;
	}

	/**
	 * Refresh the "X of Y pages selected" counter and the select-all state.
	 */
	function updateSelectionState() {
		var $boxes = $list.find('.cpanalyzer-page-checkbox');
		var total = $boxes.length;
		var checked = $boxes.filter(':checked').length;

		$count.text(
			config.strings.selected_of
				.replace('%1$s', String(checked))
				.replace('%2$s', String(total))
		);

		$selectAll.prop('checked', total > 0 && checked === total);
		$selectAll.prop('indeterminate', checked > 0 && checked < total);
		$importButton.prop('disabled', checked === 0);
	}

	/**
	 * Render the checkbox list. Titles and paths are inserted with .text()
	 * so nothing is interpreted as HTML.
	 *
	 * @param {Array} pages Array of {path, title, type} objects.
	 */
	function renderPages(pages) {
		$list.empty();

		$.each(pages, function (index, page) {
			var $row = $('<label/>', { 'class': 'cpanalyzer-page-row' });
			var $checkbox = $('<input/>', {
				type: 'checkbox',
				'class': 'cpanalyzer-page-checkbox',
				value: page.path,
				checked: true
			});
			var $title = $('<span/>', { 'class': 'cpanalyzer-page-title' }).text(page.title);
			var $path = $('<code/>', { 'class': 'cpanalyzer-page-path' }).text(page.path);
			var $type = $('<span/>', { 'class': 'cpanalyzer-page-type' }).text(page.type);

			$row.append($checkbox, ' ', $title, ' ', $path, ' ', $type);
			$list.append($row);
		});

		$picker.show();
		updateSelectionState();
	}

	function loadPages() {
		$loadButton.prop('disabled', true).text(config.strings.loading);
		$status.text('');

		$.post(config.ajax_url, {
			action: 'cpanalyzer_get_site_pages',
			nonce: config.nonce
		})
			.done(function (response) {
				if (response && response.success && response.data && response.data.pages.length) {
					renderPages(response.data.pages);
				} else if (response && response.data && response.data.message) {
					$status.text(response.data.message);
				} else {
					$status.text(config.strings.no_pages);
				}
			})
			.fail(function () {
				$status.text(config.strings.load_failed);
			})
			.always(function () {
				$loadButton.prop('disabled', false).text(config.strings.reload_button || config.strings.load_button);
			});
	}

	// The picker is the primary way to add pages — load it immediately
	// instead of hiding it behind a button click. The button remains as a
	// refresh for pages published after the screen loaded.
	$(loadPages);
	$loadButton.on('click', loadPages);

	// Live search: filter rows by title or path as the user types.
	$(document).on('input', '#cpanalyzer-page-search', function () {
		var query = this.value.toLowerCase();
		$list.find('.cpanalyzer-page-row').each(function () {
			var matches = $(this).text().toLowerCase().indexOf(query) !== -1;
			$(this).toggle(matches);
		});
	});

	// Select all applies to the rows currently visible, so a search query
	// plus select-all bulk-selects exactly the matching pages.
	$selectAll.on('change', function () {
		var checked = this.checked;
		$list.find('.cpanalyzer-page-row:visible .cpanalyzer-page-checkbox').prop('checked', checked);
		updateSelectionState();
	});

	$list.on('change', '.cpanalyzer-page-checkbox', updateSelectionState);

	$importButton.on('click', function () {
		var paths = $list
			.find('.cpanalyzer-page-checkbox:checked')
			.map(function () {
				return this.value;
			})
			.get();

		if (!paths.length) {
			$status.text(config.strings.none_selected);
			return;
		}

		var mode = $('input[name="cpanalyzer_import_mode"]:checked').val() === 'merge' ? 'merge' : 'replace';

		if (mode === 'replace' && !window.confirm(config.strings.confirm_replace)) {
			return;
		}

		$importButton.prop('disabled', true).text(config.strings.importing);
		$status.text('');

		$.post(config.ajax_url, {
			action: 'cpanalyzer_import_site_pages',
			nonce: config.nonce,
			paths: paths,
			mode: mode
		})
			.done(function (response) {
				if (response && response.success) {
					$status.text(response.data.message);
					window.location.reload();
				} else {
					var message = response && response.data && response.data.message
						? response.data.message
						: config.strings.import_failed;
					$status.text(message);
					$importButton.prop('disabled', false).text(config.strings.import_button);
				}
			})
			.fail(function () {
				$status.text(config.strings.import_failed);
				$importButton.prop('disabled', false).text(config.strings.import_button);
			});
	});
})(jQuery);
