(function () {
	'use strict';

	var cfg = window.boosaiasConfig || {};
	var apiUrl = cfg.apiUrl || '';
	var nonce  = cfg.nonce  || '';
	var language = getLanguage();
	var conversationId = null;
	var lastQuestion   = '';
	var plan = 'free';
	var chatState = {
		conversationId: null,
		messages: [],
		expiresAt: null,
	};
	var storageKey = 'boosaias-chat-state:v2:' + window.location.origin + ':' + language;
	var MAX_STORED_MESSAGES = 24;
	var CHAT_TTL_MS = 10 * 60 * 1000;
	var expiryTimer = null;
	var countdownTimer = null;

	var I18N = {
		uk: {
			assistantName: 'Асистент',
			closeAria: 'Закрити чат',
			openAria: 'Відкрити чат',
			namePlaceholder: "Ваше ім'я",
			contactPlaceholder: 'Телефон або email',
			inputPlaceholder: 'Поставте запитання...',
			sendLabel: 'Надіслати',
			skipLabel: 'Пропустити',
			online: 'Онлайн',
			contextResetsIn: 'Контекст скинеться через {time}',
			resetNotice: 'Діалог скинуто через неактивність. Почнімо заново.',
			welcome: 'Привіт! Чим можу допомогти?',
			tooManyRequests: 'Занадто багато запитів. Зачекайте трохи.',
			monthlyLimit: 'Місячний ліміт чатів вичерпано. Залиште контакт, і ми вам відповімо.',
			somethingWentWrong: 'Щось пішло не так. Спробуйте ще раз.',
			leadThankYou: 'Дякуємо! Ми зв’яжемося з вами найближчим часом. 👋',
			leadFailed: 'Не вдалося надіслати. Спробуйте ще раз.',
		},
		ru: {
			assistantName: 'Ассистент',
			closeAria: 'Закрыть чат',
			openAria: 'Открыть чат',
			namePlaceholder: 'Ваше имя',
			contactPlaceholder: 'Телефон или email',
			inputPlaceholder: 'Задайте вопрос...',
			sendLabel: 'Отправить',
			skipLabel: 'Пропустить',
			online: 'Онлайн',
			contextResetsIn: 'Контекст сбросится через {time}',
			resetNotice: 'Диалог сброшен из-за неактивности. Начнём заново.',
			welcome: 'Привет! Чем могу помочь?',
			tooManyRequests: 'Слишком много запросов. Подождите немного.',
			monthlyLimit: 'Месячный лимит чатов исчерпан. Оставьте контакт, и мы вам ответим.',
			somethingWentWrong: 'Что-то пошло не так. Попробуйте ещё раз.',
			leadThankYou: 'Спасибо! Мы свяжемся с вами в ближайшее время. 👋',
			leadFailed: 'Не удалось отправить. Попробуйте ещё раз.',
		},
		en: {
			assistantName: 'Assistant',
			closeAria: 'Close chat',
			openAria: 'Open chat',
			namePlaceholder: 'Your name',
			contactPlaceholder: 'Phone or email',
			inputPlaceholder: 'Ask a question...',
			sendLabel: 'Send',
			skipLabel: 'Skip',
			online: 'Online',
			contextResetsIn: 'Context resets in {time}',
			resetNotice: "The chat was reset because of inactivity. Let's start again.",
			welcome: 'Hello! How can I help?',
			tooManyRequests: 'Too many requests. Please wait a moment.',
			monthlyLimit: 'Monthly chat limit reached. Leave your contact and we will get back to you.',
			somethingWentWrong: 'Something went wrong. Please try again.',
			leadThankYou: "Thank you! We'll get back to you shortly. 👋",
			leadFailed: 'Could not send. Please try again.',
		},
	};

	var BOT_ICON = '<svg viewBox="0 0 24 24"><path d="M12 2a2 2 0 012 2 2 2 0 01-2 2 2 2 0 01-2-2 2 2 0 012-2m0 5c2.67 0 8 1.34 8 4v2H4v-2c0-2.66 5.33-4 8-4m0 9a1 1 0 011 1 1 1 0 01-1 1 1 1 0 01-1-1 1 1 0 011-1m4 0a1 1 0 011 1 1 1 0 01-1 1 1 1 0 01-1-1 1 1 0 011-1m-8 0a1 1 0 011 1 1 1 0 01-1 1 1 1 0 01-1-1 1 1 0 011-1z"/></svg>';
	var SEND_ICON = '<svg viewBox="0 0 24 24"><path d="M2 21l21-9L2 3v7l15 2-15 2z"/></svg>';

	function init() {
		loadChatState();

		var root = document.createElement('div');
		root.id = 'boosaias-widget';
		root.style.setProperty('--boosaias-color', cfg.widgetColor || '#2271b1');
		root.innerHTML = [
            '<div id="boosaias-window">',
            '  <div id="boosaias-header">',
            '    <div id="boosaias-avatar">' + BOT_ICON + "</div>",
            '    <div id="boosaias-header-text">',
            '      <div id="boosaias-header-name">AI Assistant</div>',
            '      <div id="boosaias-header-status">',
            '        <div id="boosaias-header-status-main">',
            '          <div id="boosaias-status-dot"></div>',
            '          <span id="boosaias-status-label"></span>',
            "        </div>",
            '        <div id="boosaias-header-timer" aria-live="polite"></div>',
            "      </div>",
            "    </div>",
            '    <button id="boosaias-close" aria-label="Close">&#x2715;</button>',
            "  </div>",
            '  <div id="boosaias-messages"></div>',
            '  <div id="boosaias-lead-form">',
            '    <input id="boosaias-lead-name"    type="text" placeholder="Your name" />',
            '    <input id="boosaias-lead-contact" type="text" placeholder="Phone or email" />',
            '    <div id="boosaias-lead-actions">',
            '      <button id="boosaias-lead-submit">Send</button>',
            '      <button id="boosaias-lead-skip">Skip</button>',
            "    </div>",
            "  </div>",
            '  <div id="boosaias-input-row">',
            '    <input id="boosaias-input" type="text" placeholder="Ask a question..." />',
            '    <button id="boosaias-send" aria-label="Send">' +
                SEND_ICON +
                "</button>",
            "  </div>",
            '  <div id="boosaias-branding"></div>',
            "</div>",
            '<button id="boosaias-toggle" aria-label="Open chat">',
            '  <svg viewBox="0 0 28 28" fill="none">',
            '    <path d="M14 3C8.477 3 4 7.03 4 12c0 2.16.84 4.14 2.23 5.68L4.5 22.5l5.34-1.68A10.8 10.8 0 0014 21c5.523 0 10-4.03 10-9s-4.477-9-10-9z" fill="rgba(255,255,255,0.15)" stroke="white" stroke-width="1.5"/>',
            '    <circle cx="9.5"  cy="12" r="1.5" fill="white"/>',
            '    <circle cx="14"   cy="12" r="1.5" fill="white"/>',
            '    <circle cx="18.5" cy="12" r="1.5" fill="white"/>',
            "  </svg>",
            "</button>",
        ].join("");

		document.body.appendChild(root);

		document.getElementById('boosaias-toggle').addEventListener('click', openWindow);
		document.getElementById('boosaias-close').addEventListener('click', closeWindow);
		document.getElementById('boosaias-send').addEventListener('click', sendMessage);
		document.getElementById('boosaias-input').addEventListener('keydown', function (e) {
			if (e.key === 'Enter') sendMessage();
		});
		document.getElementById('boosaias-lead-submit').addEventListener('click', submitLead);
		document.getElementById('boosaias-lead-skip').addEventListener('click', hideLeadForm);

		localizeUI();
		restoreChatHistory();
		if (!chatState.messages.length) {
			addBotMessage(cfg.welcomeMessage || t('welcome'), true);
			markChatStateActive();
		} else {
			updateStatusUI();
		}

		fetch(apiUrl + '/config', { headers: { 'X-WP-Nonce': nonce } })
			.then(function (r) { return r.json(); })
			.then(function (data) {
				plan = data.plan || 'free';
				setBranding();
			})
			.catch(function () {});
	}

	function openWindow() {
		document.getElementById('boosaias-window').classList.add('open');
		document.getElementById('boosaias-toggle').style.display = 'none';
		document.getElementById('boosaias-input').focus();
	}

	function closeWindow() {
		document.getElementById('boosaias-window').classList.remove('open');
		document.getElementById('boosaias-toggle').style.display = '';
	}

	function sendMessage() {
		var input = document.getElementById('boosaias-input');
		var text  = input.value.trim();
		if (!text) return;

		addUserMessage(text, true);
		lastQuestion = text;
		input.value  = '';

		var typingId = showTyping();

		fetch(apiUrl + '/chat', {
			method: 'POST',
			headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
			body: JSON.stringify({
				conversation_id: conversationId || null,
				message:  text,
				page_url: window.location.href,
			}),
		})
			.then(function (r) { return r.json().then(function (d) { return { status: r.status, data: d }; }); })
			.then(function (res) {
				removeTyping(typingId);

				if (res.status === 429) {
					addBotMessage(t('tooManyRequests'));
					return;
				}
				if (res.status === 402) {
					showLeadForm();
					addBotMessage(t('monthlyLimit'));
					return;
				}

				var data = res.data;
				if (!data) return;

				if (data.conversation_id) {
					conversationId = data.conversation_id;
					chatState.conversationId = data.conversation_id;
					markChatStateActive();
				}

				if (data.action === 'collect_lead') {
					addBotMessage(data.reply || '', true);
					showLeadForm();
				} else {
					addBotMessage(data.reply || '', true);
				}
			})
			.catch(function () {
				removeTyping(typingId);
				addBotMessage(t('somethingWentWrong'), true);
			});
	}

	/* ── Message rendering ───────────────────────────────── */

	function addBotMessage(text, shouldPersist) {
		renderMessage('bot', text);
		if (shouldPersist !== false) {
			persistMessage('bot', text);
		}
	}

	function addUserMessage(text, shouldPersist) {
		renderMessage('user', text);
		if (shouldPersist !== false) {
			persistMessage('user', text);
		}
	}

	function renderMessage(role, text) {
		var msgs = document.getElementById('boosaias-messages');
		var row  = document.createElement('div');
		row.className = 'boosaias-row ' + role;

		var bubble = document.createElement('div');
		bubble.className = 'boosaias-msg';

		if (role === 'bot') {
			var icon = document.createElement('div');
			icon.className = 'boosaias-bot-icon';
			icon.innerHTML = BOT_ICON;
			bubble.innerHTML = renderText(text);
			row.appendChild(icon);
		} else {
			bubble.textContent = text;
		}

		row.appendChild(bubble);
		msgs.appendChild(row);
		msgs.scrollTop = msgs.scrollHeight;
	}

	function showTyping() {
		var msgs = document.getElementById('boosaias-messages');
		var row  = document.createElement('div');
		var id   = 'boosaias-t-' + Date.now();
		row.id   = id;
		row.className = 'boosaias-row bot';

		var icon = document.createElement('div');
		icon.className = 'boosaias-bot-icon';
		icon.innerHTML = BOT_ICON;

		var dots = document.createElement('div');
		dots.className = 'boosaias-typing';
		dots.innerHTML = '<span></span><span></span><span></span>';

		row.appendChild(icon);
		row.appendChild(dots);
		msgs.appendChild(row);
		msgs.scrollTop = msgs.scrollHeight;
		return id;
	}

	function removeTyping(id) {
		var el = document.getElementById(id);
		if (el) el.remove();
	}

	/* ── Text formatting ─────────────────────────────────── */

	function renderText(text) {
		// 1. Extract markdown links into indexed placeholders BEFORE escaping
		//    so list/bold formatters don't break the link syntax
		var links = [];
		var withPlaceholders = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, function (_, label, href) {
			var idx = links.length;
			links.push('<a class="boosaias-btn-product" href="' + esc(href) + '" target="_blank" rel="noopener">' + esc(label) + '</a>');
			return '\x01' + idx + '\x01';
		});

		// 2. Escape HTML + apply formatting
		var html = escAndFormat(withPlaceholders);

		// 3. Restore links (\x01 and digits survive HTML escaping unchanged)
		return html.replace(/\x01(\d+)\x01/g, function (_, idx) {
			return links[parseInt(idx, 10)];
		});
	}

	function escAndFormat(text) {
		// Escape HTML
		text = String(text)
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;');

		// Bold **text**
		text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');

		// Numbered list: lines starting with "1. " etc
		text = text.replace(/((?:^\d+\.\s.+\n?)+)/gm, function (block) {
			var items = block.trim().split('\n').map(function (line) {
				return '<li>' + line.replace(/^\d+\.\s/, '') + '</li>';
			}).join('');
			return '<ol>' + items + '</ol>';
		});

		// Bullet list: lines starting with "- " or "• "
		text = text.replace(/((?:^[-•]\s.+\n?)+)/gm, function (block) {
			var items = block.trim().split('\n').map(function (line) {
				return '<li>' + line.replace(/^[-•]\s/, '') + '</li>';
			}).join('');
			return '<ul>' + items + '</ul>';
		});

		// Paragraphs: double newline → <p>
		text = text.replace(/\n{2,}/g, '</p><p>');

		// Single newline → <br>
		text = text.replace(/\n/g, '<br>');

		return '<p>' + text + '</p>';
	}

	/* ── Lead form ───────────────────────────────────────── */

	function showLeadForm() {
		document.getElementById('boosaias-lead-form').classList.add('visible');
	}

	function hideLeadForm() {
		document.getElementById('boosaias-lead-form').classList.remove('visible');
		document.getElementById('boosaias-lead-name').value    = '';
		document.getElementById('boosaias-lead-contact').value = '';
	}

	function submitLead() {
		var name    = document.getElementById('boosaias-lead-name').value.trim();
		var contact = document.getElementById('boosaias-lead-contact').value.trim();
		if (!name || !contact) return;

		fetch(apiUrl + '/lead', {
			method: 'POST',
			headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
			body: JSON.stringify({
				conversation_id: conversationId || null,
				name:     name,
				contact:  contact,
				question: lastQuestion,
				page_url: window.location.href,
			}),
		})
			.then(function () {
				hideLeadForm();
				addBotMessage(t('leadThankYou'), true);
			})
			.catch(function () {
				addBotMessage(t('leadFailed'), true);
			});
	}

	/* ── Branding ────────────────────────────────────────── */

	function setBranding() {
		var el = document.getElementById('boosaias-branding');
		if (!el) return;
		if (!cfg.showBranding) { el.style.display = 'none'; return; }
		el.innerHTML = '<a href="https://boostanova.com/en/privacy-policy" target="_blank" rel="noopener" id="boosaias-privacy">Powered by Boostanova</a>';
	}

	function esc(str) {
		return String(str)
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;');
	}

	function loadChatState() {
		try {
			var raw = window.sessionStorage.getItem(storageKey);
			if (!raw) return;

			var parsed = JSON.parse(raw);
			if (!parsed || typeof parsed !== 'object') return;

			chatState.conversationId = typeof parsed.conversationId === 'string' ? parsed.conversationId : null;
			chatState.expiresAt = typeof parsed.expiresAt === 'number' ? parsed.expiresAt : null;
			chatState.messages = Array.isArray(parsed.messages)
				? parsed.messages.filter(function (message) {
					return message && (message.role === 'user' || message.role === 'bot') && typeof message.text === 'string';
				}).slice(-MAX_STORED_MESSAGES)
				: [];

			if (chatState.expiresAt && chatState.expiresAt <= Date.now()) {
				clearChatState();
				return;
			}

			conversationId = chatState.conversationId;
			lastQuestion = findLastUserQuestion(chatState.messages);
			scheduleChatExpiry();
		} catch (e) {}
	}

	function saveChatState() {
		try {
			window.sessionStorage.setItem(storageKey, JSON.stringify(chatState));
		} catch (e) {}
	}

	function markChatStateActive() {
		chatState.expiresAt = Date.now() + CHAT_TTL_MS;
		saveChatState();
		scheduleChatExpiry();
		updateStatusUI();
	}

	function persistMessage(role, text) {
		chatState.messages.push({ role: role, text: text });
		if (chatState.messages.length > MAX_STORED_MESSAGES) {
			chatState.messages = chatState.messages.slice(-MAX_STORED_MESSAGES);
		}
		markChatStateActive();
	}

	function restoreChatHistory() {
		if (!chatState.messages.length) return;

		var msgs = document.getElementById('boosaias-messages');
		msgs.innerHTML = '';

		chatState.messages.forEach(function (message) {
			renderMessage(message.role, message.text);
		});
	}

	function scheduleChatExpiry() {
		if (expiryTimer) {
			clearTimeout(expiryTimer);
			expiryTimer = null;
		}
		if (countdownTimer) {
			clearInterval(countdownTimer);
			countdownTimer = null;
		}

		if (!chatState.expiresAt) return;

		var delay = chatState.expiresAt - Date.now();
		if (delay <= 0) {
			clearChatState();
			return;
		}

		expiryTimer = window.setTimeout(clearChatState, delay);
		countdownTimer = window.setInterval(updateStatusUI, 1000);
		updateStatusUI();
	}

	function clearChatState() {
		if (expiryTimer) {
			clearTimeout(expiryTimer);
			expiryTimer = null;
		}
		if (countdownTimer) {
			clearInterval(countdownTimer);
			countdownTimer = null;
		}

		chatState.conversationId = null;
		chatState.messages = [];
		chatState.expiresAt = null;
		conversationId = null;
		lastQuestion = '';

		try {
			window.sessionStorage.removeItem(storageKey);
		} catch (e) {}

		var msgs = document.getElementById('boosaias-messages');
		if (msgs) {
			msgs.innerHTML = '';
			addBotMessage(t('resetNotice'), false);
		}
		updateStatusUI();
	}

	function updateStatusUI() {
		var statusLabel = document.getElementById('boosaias-status-label');
		var timerLabel = document.getElementById('boosaias-header-timer');
		if (!statusLabel || !timerLabel) return;

		statusLabel.textContent = t('online');

		if (!chatState.expiresAt) {
			timerLabel.textContent = '';
			return;
		}

		var remaining = chatState.expiresAt - Date.now();
		if (remaining <= 0) {
			timerLabel.textContent = '';
			return;
		}

		timerLabel.textContent = t('contextResetsIn', {
			time: formatDuration(remaining),
		});
	}

	function formatDuration(ms) {
		var totalSeconds = Math.max(0, Math.ceil(ms / 1000));
		var minutes = Math.floor(totalSeconds / 60);
		var seconds = totalSeconds % 60;
		return String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
	}

	function getLanguage() {
		var value = String(cfg.language || 'en').toLowerCase();
		return /^(uk|ru|en)$/.test(value) ? value : 'en';
	}

	function t(key, params) {
		var dictionary = I18N[language] || I18N.en;
		var text = dictionary[key] || I18N.en[key] || key;

		if (!params) return text;

		Object.keys(params).forEach(function (paramName) {
			var pattern = new RegExp('\\{' + paramName + '\\}', 'g');
			text = text.replace(pattern, String(params[paramName]));
		});

		return text;
	}

	function localizeUI() {
		var assistantName = document.getElementById('boosaias-header-name');
		var closeButton = document.getElementById('boosaias-close');
		var toggleButton = document.getElementById('boosaias-toggle');
		var nameInput = document.getElementById('boosaias-lead-name');
		var contactInput = document.getElementById('boosaias-lead-contact');
		var sendButton = document.getElementById('boosaias-lead-submit');
		var skipButton = document.getElementById('boosaias-lead-skip');
		var chatInput = document.getElementById('boosaias-input');
		var sendChatButton = document.getElementById('boosaias-send');

		if (assistantName) assistantName.textContent = t('assistantName');
		if (closeButton) closeButton.setAttribute('aria-label', t('closeAria'));
		if (toggleButton) toggleButton.setAttribute('aria-label', t('openAria'));
		if (nameInput) nameInput.setAttribute('placeholder', t('namePlaceholder'));
		if (contactInput) contactInput.setAttribute('placeholder', t('contactPlaceholder'));
		if (sendButton) sendButton.textContent = t('sendLabel');
		if (skipButton) skipButton.textContent = t('skipLabel');
		if (chatInput) chatInput.setAttribute('placeholder', t('inputPlaceholder'));
		if (sendChatButton) sendChatButton.setAttribute('aria-label', t('sendLabel'));
	}

	function findLastUserQuestion(messages) {
		for (var i = messages.length - 1; i >= 0; i -= 1) {
			if (messages[i].role === 'user') {
				return messages[i].text;
			}
		}
		return '';
	}

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