(function () {
	'use strict';

	var config = window.NiwaTemplateLibrary || {};
	var notice = document.querySelector('[data-niwa-template-notice]');
	var briefPanel = document.querySelector('[data-niwa-template-brief]');
	var briefText = document.querySelector('[data-niwa-template-brief-text]');

	function showNotice(message, isError) {
		if (!notice) {
			return;
		}
		notice.hidden = false;
		notice.textContent = message;
		notice.classList.toggle('is-error', !!isError);
	}

	function post(path, body) {
		return window.wp.apiFetch({
			path: '/niwa-ai/v1/template-library' + path,
			method: 'POST',
			data: body || {}
		});
	}

	function buildChatPrompt(card) {
		var id = card ? card.getAttribute('data-template-id') || '' : '';
		var title = card ? card.getAttribute('data-template-title') || '' : '';
		if (!title && card) {
			title = (card.querySelector('h2') || {}).textContent || '';
		}
		title = title.trim();
		return [
			'Use Niwa Template Library template #' + id + ' "' + title + '" to build a real Elementor section.',
			'First identify the target Elementor page/post I mean. If I did not give enough detail, ask me for the missing target page, section position, copy, images, colors, and CTA.',
			'When the target is clear, use template_library_insert_elementor so the template becomes real Elementor JSON and can be reverted through Niwa rollback.',
			'Do not create or publish a shortcode snippet unless Elementor is inactive or I explicitly ask for shortcode fallback.',
			'Target page/section details: '
		].join('\n');
	}

	function setChatInput(prompt) {
		var morph = window.Niwa && window.Niwa.MorphController ? window.Niwa.MorphController : null;
		if (morph && typeof morph.open === 'function') {
			morph.open('template_library');
		} else if (window.niwaAI && typeof window.niwaAI.openChat === 'function') {
			window.niwaAI.openChat();
		}

		window.setTimeout(function () {
			var textarea = morph && typeof morph.getTextarea === 'function' ? morph.getTextarea() : document.getElementById('niwaChatheadInput');
			if (!textarea) {
				showNotice((config.i18n && config.i18n.chatMissing) || 'Niwa chat is not available on this screen yet. Copy the prompt and send it from Niwa chat.', true);
				return;
			}
			textarea.focus();
			textarea.value = prompt;
			textarea.dispatchEvent(new window.Event('input', { bubbles: true }));
			if (morph && typeof morph.syncTextareaLayout === 'function') {
				morph.syncTextareaLayout();
			}
			showNotice((config.i18n && config.i18n.chatReady) || 'Niwa chat is ready with this template request. Add the target page/section details and send it.', false);
		}, 180);
	}

	function writeBrief(prompt) {
		if (!briefPanel || !briefText) {
			return;
		}
		briefPanel.hidden = false;
		briefText.value = prompt;
		briefText.focus();
		briefText.setSelectionRange(briefText.value.length, briefText.value.length);
	}

	if (window.wp && window.wp.apiFetch && config.nonce) {
		window.wp.apiFetch.use(window.wp.apiFetch.createNonceMiddleware(config.nonce));
	}

	document.querySelectorAll('.niwa-template-tab').forEach(function (tab) {
		tab.addEventListener('click', function () {
			var type = tab.getAttribute('data-type');
			document.querySelectorAll('.niwa-template-tab').forEach(function (item) {
				item.classList.toggle('is-active', item === tab);
			});
			document.querySelectorAll('.niwa-template-card').forEach(function (card) {
				card.hidden = card.getAttribute('data-type') !== type;
			});
		});
	});
	var activeTab = document.querySelector('.niwa-template-tab.is-active');
	if (activeTab) {
		activeTab.click();
	}

	document.querySelectorAll('.niwa-template-use').forEach(function (button) {
		button.addEventListener('click', function () {
			var card = button.closest('.niwa-template-card');
			var prompt = buildChatPrompt(card);
			writeBrief(prompt);
			showNotice((config.i18n && config.i18n.briefReady) || 'Template brief ready. Ask Niwa in chat to build it on a target Elementor page.', false);
		});
	});

	document.querySelectorAll('[data-niwa-template-open-chat]').forEach(function (button) {
		button.addEventListener('click', function () {
			var prompt = briefText ? briefText.value : '';
			if (prompt.trim()) {
				setChatInput(prompt);
			}
		});
	});

	document.querySelectorAll('[data-niwa-template-copy]').forEach(function (button) {
		button.addEventListener('click', function () {
			var prompt = briefText ? briefText.value : '';
			if (!prompt.trim()) {
				return;
			}
			if (window.navigator && window.navigator.clipboard && window.navigator.clipboard.writeText) {
				window.navigator.clipboard.writeText(prompt).then(function () {
					showNotice('Prompt copied.', false);
				}).catch(function () {
					showNotice('Prompt is selected. Press Ctrl+C to copy it.', false);
					briefText.focus();
					briefText.select();
				});
			} else {
				briefText.focus();
				briefText.select();
				showNotice('Prompt is selected. Press Ctrl+C to copy it.', false);
			}
		});
	});

	document.querySelectorAll('[data-niwa-template-create]').forEach(function (form) {
		form.addEventListener('submit', function (event) {
			event.preventDefault();
			var data = new window.FormData(form);
			var title = (data.get('title') || '').toString();
			var type = (data.get('type') || 'featured').toString();
			post('/templates', {
				title: title,
				subtitle: title,
				type: type,
				prompt: title,
				agent_prompt: 'Use this template from Niwa chat when the founder asks to build: ' + title,
				elementor_schema: {
					kind: 'content_section',
					title: title
				},
				manifest: {
					version: 1,
					output_mode: type === 'elementor-widget' ? 'elementor_widget' : 'shortcode',
					fallback: 'shortcode',
					requires_llm: true
				}
			}).then(function () {
				showNotice('Template added.', false);
				window.setTimeout(function () {
					window.location.reload();
				}, 500);
			}).catch(function (error) {
				showNotice((error && error.message) || 'Template could not be added.', true);
			});
		});
	});

	document.querySelectorAll('[data-niwa-snippet-validate]').forEach(function (button) {
		button.addEventListener('click', function () {
			var id = parseInt(button.getAttribute('data-niwa-snippet-validate'), 10);
			button.disabled = true;
			post('/snippets/' + id + '/validate', {}).then(function () {
				showNotice((config.i18n && config.i18n.validated) || 'Snippet validated.', false);
			}).catch(function (error) {
				showNotice((error && error.message) || ((config.i18n && config.i18n.actionFailed) || 'Snippet action failed.'), true);
			}).finally(function () {
				button.disabled = false;
			});
		});
	});

	document.querySelectorAll('[data-niwa-snippet-publish]').forEach(function (button) {
		button.addEventListener('click', function () {
			var id = parseInt(button.getAttribute('data-niwa-snippet-publish'), 10);
			button.disabled = true;
			post('/snippets/' + id + '/publish', {}).then(function () {
				showNotice((config.i18n && config.i18n.published) || 'Snippet published.', false);
				window.setTimeout(function () {
					window.location.reload();
				}, 700);
			}).catch(function (error) {
				showNotice((error && error.message) || ((config.i18n && config.i18n.actionFailed) || 'Snippet action failed.'), true);
			}).finally(function () {
				button.disabled = false;
			});
		});
	});
}());
