/**
 * Newsroom OS — Command palette (Ctrl+K / ⌘K).
 */
(function (global) {
	'use strict';

	var commands = [];
	var overlay = null;
	var inputEl = null;
	var listEl = null;
	var activeIndex = 0;
	var filtered = [];

	function esc(s) {
		var d = document.createElement('div');
		d.textContent = String(s == null ? '' : s);
		return d.innerHTML;
	}

	function __(text) {
		if (global.wp && wp.i18n && typeof wp.i18n.__ === 'function') {
			return wp.i18n.__(text, 'newsroom-ai-assistant');
		}
		return text;
	}

	function register(cmd) {
		if (!cmd || !cmd.id || typeof cmd.run !== 'function') {
			return;
		}
		var existing = -1;
		for (var i = 0; i < commands.length; i++) {
			if (commands[i].id === cmd.id) {
				existing = i;
				break;
			}
		}
		var entry = {
			id: cmd.id,
			label: cmd.label || cmd.id,
			hint: cmd.hint || '',
			group: cmd.group || '',
			keywords: (cmd.keywords || '').toLowerCase(),
			when: typeof cmd.when === 'function' ? cmd.when : function () { return true; },
			run: cmd.run
		};
		if (existing >= 0) {
			commands[existing] = entry;
		} else {
			commands.push(entry);
		}
	}

	function ensureDom() {
		if (overlay) {
			return;
		}
		overlay = document.createElement('div');
		overlay.className = 'nros-palette-overlay';
		overlay.hidden = true;
		overlay.setAttribute('role', 'dialog');
		overlay.setAttribute('aria-modal', 'true');
		overlay.setAttribute('aria-label', __('Command palette'));

		var panel = document.createElement('div');
		panel.className = 'nros-palette';

		inputEl = document.createElement('input');
		inputEl.type = 'text';
		inputEl.className = 'nros-palette__input';
		inputEl.setAttribute('autocomplete', 'off');
		inputEl.setAttribute('spellcheck', 'false');
		inputEl.placeholder = __('Type a command…');

		listEl = document.createElement('ul');
		listEl.className = 'nros-palette__list';

		var foot = document.createElement('div');
		foot.className = 'nros-palette__foot';
		foot.textContent = __('↑↓ navigate · Enter run · Esc close');

		panel.appendChild(inputEl);
		panel.appendChild(listEl);
		panel.appendChild(foot);
		overlay.appendChild(panel);
		document.body.appendChild(overlay);

		overlay.addEventListener('click', function (e) {
			if (e.target === overlay) {
				close();
			}
		});

		inputEl.addEventListener('input', function () {
			renderList(inputEl.value);
		});

		inputEl.addEventListener('keydown', function (e) {
			if (e.key === 'Escape') {
				e.preventDefault();
				close();
				return;
			}
			if (e.key === 'ArrowDown') {
				e.preventDefault();
				activeIndex = Math.min(activeIndex + 1, filtered.length - 1);
				highlightActive();
				return;
			}
			if (e.key === 'ArrowUp') {
				e.preventDefault();
				activeIndex = Math.max(activeIndex - 1, 0);
				highlightActive();
				return;
			}
			if (e.key === 'Enter') {
				e.preventDefault();
				runActive();
			}
		});
	}

	function getVisible() {
		return commands.filter(function (c) {
			try {
				return c.when();
			} catch (err) {
				return false;
			}
		});
	}

	function score(cmd, q) {
		if (!q) {
			return 1;
		}
		var hay = (cmd.label + ' ' + cmd.hint + ' ' + cmd.keywords + ' ' + cmd.group).toLowerCase();
		if (hay.indexOf(q) !== -1) {
			return 2;
		}
		var parts = q.split(/\s+/).filter(Boolean);
		for (var i = 0; i < parts.length; i++) {
			if (hay.indexOf(parts[i]) === -1) {
				return 0;
			}
		}
		return 1;
	}

	function renderList(query) {
		var q = String(query || '').toLowerCase().trim();
		filtered = getVisible()
			.map(function (c) {
				return { cmd: c, s: score(c, q) };
			})
			.filter(function (row) {
				return row.s > 0;
			})
			.sort(function (a, b) {
				return b.s - a.s;
			})
			.map(function (row) {
				return row.cmd;
			});
		activeIndex = 0;
		if (!filtered.length) {
			listEl.innerHTML = '<li class="nros-palette__empty">' + esc(__('No matching commands')) + '</li>';
			return;
		}
		var html = '';
		filtered.forEach(function (c, idx) {
			html += '<li class="nros-palette__item' + (idx === 0 ? ' is-active' : '') + '" data-idx="' + idx + '">';
			html += '<span class="nros-palette__item-label">' + esc(c.label) + '</span>';
			if (c.hint) {
				html += '<span class="nros-palette__item-hint">' + esc(c.hint) + '</span>';
			}
			html += '</li>';
		});
		listEl.innerHTML = html;
		listEl.querySelectorAll('.nros-palette__item').forEach(function (el) {
			el.addEventListener('click', function () {
				var idx = parseInt(el.getAttribute('data-idx'), 10);
				if (!isNaN(idx) && filtered[idx]) {
					execute(filtered[idx]);
				}
			});
		});
	}

	function highlightActive() {
		var items = listEl.querySelectorAll('.nros-palette__item');
		for (var i = 0; i < items.length; i++) {
			items[i].classList.toggle('is-active', i === activeIndex);
		}
		var active = items[activeIndex];
		if (active && active.scrollIntoView) {
			active.scrollIntoView({ block: 'nearest' });
		}
	}

	function execute(cmd) {
		close();
		try {
			cmd.run();
		} catch (err) {
			// eslint-disable-next-line no-console
			console.warn('nrosCommandPalette', err);
		}
	}

	function runActive() {
		if (filtered[activeIndex]) {
			execute(filtered[activeIndex]);
		}
	}

	function open() {
		ensureDom();
		overlay.hidden = false;
		inputEl.value = '';
		renderList('');
		setTimeout(function () {
			inputEl.focus();
		}, 0);
	}

	function close() {
		if (overlay) {
			overlay.hidden = true;
		}
	}

	function onKeydown(e) {
		var key = e.key || '';
		if ((e.ctrlKey || e.metaKey) && (key === 'k' || key === 'K')) {
			var tag = (e.target && e.target.tagName) ? e.target.tagName.toLowerCase() : '';
			if (tag === 'input' || tag === 'textarea' || (e.target && e.target.isContentEditable)) {
				return;
			}
			e.preventDefault();
			if (overlay && !overlay.hidden) {
				close();
			} else {
				open();
			}
		}
	}

	function clickAiTask(task) {
		var btn = document.querySelector('.newsai-ai-action[data-task="' + task + '"]');
		if (btn) {
			btn.click();
			return true;
		}
		return false;
	}

	function openDetails(id) {
		var el = document.getElementById(id);
		if (!el) {
			return false;
		}
		if (el.tagName === 'DETAILS') {
			el.open = true;
		}
		el.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
		return true;
	}

	function navigateAdmin(tab) {
		var base = 'admin.php?page=newsai-settings';
		if (tab) {
			window.location.href = base + '&tab=' + encodeURIComponent(tab);
		} else {
			window.location.href = base;
		}
	}

	function registerDefaults() {
		register({
			id: 'nav-dashboard',
			label: __('Open Dashboard'),
			hint: __('Admin'),
			keywords: 'dashboard tasks alerts',
			group: 'nav',
			run: function () { navigateAdmin('alerts'); }
		});
		register({
			id: 'nav-insights',
			label: __('Open Chief Insights'),
			hint: __('Admin'),
			keywords: 'insights chief kpi gsc',
			group: 'nav',
			run: function () { navigateAdmin('insights'); }
		});
		register({
			id: 'nav-settings',
			label: __('Open Settings'),
			hint: __('Admin'),
			keywords: 'settings prompts team',
			group: 'nav',
			when: function () { return true; },
			run: function () { navigateAdmin('settings'); }
		});

		register({
			id: 'chief-ai-brief',
			label: __('AI Daily Brief'),
			hint: __('Chief Insights'),
			keywords: 'ai brief summary morning evening',
			when: function () { return !!document.getElementById('nros-insights-ai-brief'); },
			run: function () {
				var btn = document.getElementById('nros-insights-ai-brief');
				if (btn) { btn.click(); }
			}
		});
		register({
			id: 'chief-print',
			label: __('Print / export PDF'),
			hint: __('Chief Insights'),
			keywords: 'print pdf export report',
			when: function () { return !!document.getElementById('nros-insights-print'); },
			run: function () {
				var btn = document.getElementById('nros-insights-print');
				if (btn) { btn.click(); }
			}
		});
		register({
			id: 'chief-window-7',
			label: __('Chief Insights: 7-day window'),
			hint: __('Period'),
			when: function () { return !!document.getElementById('nros-insights-days'); },
			run: function () {
				window.location.href = 'admin.php?page=newsai-settings&tab=insights&days=7';
			}
		});
		register({
			id: 'chief-window-30',
			label: __('Chief Insights: 30-day window'),
			hint: __('Period'),
			when: function () { return !!document.getElementById('nros-insights-days'); },
			run: function () {
				window.location.href = 'admin.php?page=newsai-settings&tab=insights&days=30';
			}
		});
		register({
			id: 'chief-window-90',
			label: __('Chief Insights: 90-day window'),
			hint: __('Period'),
			when: function () { return !!document.getElementById('nros-insights-days'); },
			run: function () {
				window.location.href = 'admin.php?page=newsai-settings&tab=insights&days=90';
			}
		});
		register({
			id: 'palette-open',
			label: __('Open command palette'),
			hint: __('Shortcuts'),
			keywords: 'command palette search',
			run: function () { open(); }
		});
		register({
			id: 'chief-gsc-sync',
			label: __('Sync Search Console now'),
			hint: __('Settings'),
			keywords: 'gsc sync google search console',
			when: function () { return !!document.getElementById('newsai-gsc-sync'); },
			run: function () {
				var btn = document.getElementById('newsai-gsc-sync');
				if (btn) { btn.click(); }
			}
		});

		register({
			id: 'kanban-mark-all-done',
			label: __('Mark all tasks as done'),
			hint: __('Dashboard'),
			keywords: 'kanban tasks done complete bulk mark all',
			when: function () {
				return !!document.getElementById('nros-kanban-view') &&
					!!(global.nrosKanban && typeof global.nrosKanban.markAllDone === 'function');
			},
			run: function () {
				if (global.nrosKanban && typeof global.nrosKanban.markAllDone === 'function') {
					global.nrosKanban.markAllDone();
				}
			}
		});

		register({
			id: 'kanban-select-all',
			label: __('Select all tasks'),
			hint: __('Dashboard'),
			keywords: 'kanban tasks select all bulk',
			when: function () {
				return !!document.getElementById('nros-kanban-view') &&
					!!(global.nrosKanban && typeof global.nrosKanban.selectAll === 'function');
			},
			run: function () {
				if (global.nrosKanban && typeof global.nrosKanban.selectAll === 'function') {
					global.nrosKanban.selectAll();
				}
			}
		});

		register({
			id: 'editor-title-suggest',
			label: __('Suggest new titles'),
			hint: __('AI Assist'),
			keywords: 'title headline ai',
			when: function () { return !!document.querySelector('.newsai-ai-action[data-task="title_suggest"]'); },
			run: function () { clickAiTask('title_suggest'); openDetails('newsai-ai-assist'); }
		});
		register({
			id: 'editor-optimize',
			label: __('Optimize content'),
			hint: __('AI Assist'),
			keywords: 'optimize seo content ai',
			when: function () { return !!document.querySelector('.newsai-ai-action[data-task="optimize_content"]'); },
			run: function () { clickAiTask('optimize_content'); openDetails('newsai-ai-assist'); }
		});
		register({
			id: 'editor-trend-kw',
			label: __('Trending keywords'),
			hint: __('AI Assist'),
			keywords: 'trends keywords google',
			when: function () { return !!document.querySelector('.newsai-ai-action[data-task="trend_keywords"]'); },
			run: function () { clickAiTask('trend_keywords'); openDetails('newsai-ai-assist'); }
		});
		register({
			id: 'editor-meta',
			label: __('Generate meta description'),
			hint: __('AI Assist'),
			keywords: 'meta description seo',
			when: function () { return !!document.querySelector('.newsai-ai-action[data-task="meta_description"]'); },
			run: function () { clickAiTask('meta_description'); openDetails('newsai-ai-assist'); }
		});
		register({
			id: 'desk-content-brief',
			label: __('Generate content brief from trend'),
			hint: __('Trend Radar'),
			keywords: 'brief trend topic radar desk',
			when: function () { return !!document.getElementById('newsai-brief-generate'); },
			run: function () {
				var bar = document.getElementById('newsai-brief-bar');
				if (bar) {
					bar.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
				}
				var topic = document.getElementById('newsai-brief-topic');
				if (topic && !topic.value.trim()) {
					topic.focus();
					return;
				}
				var btn = document.getElementById('newsai-brief-generate');
				if (btn) { btn.click(); }
			}
		});
		register({
			id: 'editor-discover',
			label: __('Scroll to AI Readiness'),
			hint: __('Editor'),
			keywords: 'readiness discover score gauge ai',
			when: function () { return !!document.getElementById('nros-readiness-score'); },
			run: function () {
				var el = document.getElementById('nros-readiness-score');
				if (el) {
					openDetails('newsai_sidebar');
					el.closest('.nros-card, .postbox') && el.closest('.nros-card, .postbox').scrollIntoView({ behavior: 'smooth', block: 'center' });
				}
			}
		});
	}

	function init() {
		registerDefaults();
		document.addEventListener('keydown', onKeydown);
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}

	global.nrosCommandPalette = {
		register: register,
		open: open,
		close: close
	};
})(typeof window !== 'undefined' ? window : this);
