(function () {
	'use strict';

	var cfg = window.axagbuinAdmin || {};
	var L = {
		en: { reg_no: 'Registration number', vat: 'VAT number', seller_name: 'Seller name', seller_address: 'Seller address', seller_bank: 'Bank name', seller_iban: 'IBAN', seller_email: 'Seller email', seller_phone: 'Seller phone', seller_website: 'Seller website', logo_url: 'Logo URL', product_images: 'Product images in invoice', invoice_title: 'Invoice title', header_color: 'Table header color', invoice_footer: 'Footer note', date_from: 'Start date', date_to: 'End date', order_id_from: 'Start order number / ID', order_number_meta: 'Order number meta key', status: 'Order status', limit: 'Max orders', order_number: 'Order number', order_date: 'Order date', payment: 'Payment', product: 'Product', qty: 'Qty', price: 'Price', subtotal: 'Subtotal', discount: 'Discount', tax: 'Tax', shipping: 'Shipping', total: 'Total' },
		et: { reg_no: 'Registrikood', vat: 'KMKR nr', seller_name: 'Müüja nimi', seller_address: 'Müüja aadress', seller_bank: 'Panga nimi', seller_iban: 'IBAN', seller_email: 'Müüja e-post', seller_phone: 'Müüja telefon', seller_website: 'Müüja veebisait', logo_url: 'Logo URL', product_images: 'Tootefotod arvel', invoice_title: 'Arve pealkiri', header_color: 'Tabeli päise värv', invoice_footer: 'Jaluse märkus', date_from: 'Alguskuupäev', date_to: 'Lõppkuupäev', order_id_from: 'Alguse tellimuse number', order_number_meta: 'Tellimuse numbri võti', status: 'Tellimuse olek', limit: 'Maksimaalne tellimuste arv', order_number: 'Tellimuse number', order_date: 'Tellimuse kuupäev', payment: 'Makseviis', product: 'Toode', qty: 'Kogus', price: 'Hind', subtotal: 'Vahesumma', discount: 'Soodustus', tax: 'Maksud', shipping: 'Transport', total: 'Kokku' },
		ru: { reg_no: 'Рег. номер', vat: 'НДС номер', seller_name: 'Продавец', seller_address: 'Адрес продавца', seller_bank: 'Банк', seller_iban: 'IBAN', seller_email: 'Email продавца', seller_phone: 'Телефон продавца', seller_website: 'Сайт продавца', logo_url: 'URL логотипа', product_images: 'Фото товаров в счёте', invoice_title: 'Заголовок счёта', header_color: 'Цвет заголовка таблицы', invoice_footer: 'Примечание', date_from: 'Начальная дата', date_to: 'Конечная дата', order_id_from: 'Начальный номер заказа', order_number_meta: 'Мета-ключ номера заказа', status: 'Статус заказа', limit: 'Макс. заказов', order_number: 'Номер заказа', order_date: 'Дата заказа', payment: 'Оплата', product: 'Товар', qty: 'Кол-во', price: 'Цена', subtotal: 'Подытог', discount: 'Скидка', tax: 'Налог', shipping: 'Доставка', total: 'Итого' }
	};
	var formLabels = [
		['lbl-seller-name', 'seller_name'], ['lbl-seller-reg', 'reg_no'], ['lbl-seller-vat', 'vat'],
		['lbl-seller-address', 'seller_address'], ['lbl-seller-bank', 'seller_bank'], ['lbl-seller-iban', 'seller_iban'],
		['lbl-seller-email', 'seller_email'], ['lbl-seller-phone', 'seller_phone'], ['lbl-seller-website', 'seller_website'],
		['lbl-logo-url', 'logo_url'], ['lbl-product-images', 'product_images'], ['lbl-invoice-title', 'invoice_title'],
		['lbl-header-color', 'header_color'], ['lbl-invoice-footer', 'invoice_footer'],
		['lbl-date-from', 'date_from'], ['lbl-date-to', 'date_to'], ['lbl-order-id-from', 'order_id_from'],
		['lbl-order-number-meta', 'order_number_meta'], ['lbl-status', 'status'], ['lbl-limit', 'limit']
	];

	function updateLang(lang) {
		var lbl = L[lang] || L.en;
		var en = L.en;
		for (var i = 0; i < formLabels.length; i++) {
			var el = document.getElementById(formLabels[i][0]);
			if (el) el.textContent = lbl[formLabels[i][1]] || en[formLabels[i][1]];
		}
	}

	var langSel = document.getElementById('invoice_language');
	if (langSel) {
		langSel.addEventListener('change', function () { updateLang(this.value); });
		updateLang(langSel.value);
	}

	// ── ZIP generation with polling-based progress ────────────────────
	var dlForm = document.getElementById('axagen-download-form');
	if (!dlForm) return;
	dlForm.addEventListener('submit', function (e) {
		e.preventDefault();
		var btn = dlForm.querySelector('[type="submit"]');
		var progress = document.getElementById('axagen-progress');
		var postUrl = dlForm.action;
		var ajaxUrl = cfg.ajaxUrl || postUrl.replace('admin-post.php', 'admin-ajax.php');
		btn.disabled = true;
		btn.textContent = 'Starting…';
		progress.style.display = 'block';
		progress.innerHTML = '<p style="margin:0">Counting orders…</p>';

		var progressNonce = cfg.progressNonce || '';
		var jobKey = 'axj' + Date.now().toString(36) + Math.random().toString(36).substr(2, 6);
		var fd = new FormData(dlForm);
		fd.set('action', 'axagbuin_bulk_invoice_stream');
		fd.set('axagbuin_job_key', jobKey);

		var finished = false;
		var pollTimer = null;

		var cancelBtn = document.createElement('button');
		cancelBtn.type = 'button';
		cancelBtn.textContent = 'Cancel';
		cancelBtn.className = 'axagbuin-cancel-btn';
		cancelBtn.addEventListener('click', function () {
			if (finished) return; finished = true; stopAll();
			cancelBtn.remove();
			progress.innerHTML = '<p style="color:#888;margin:0">Generation cancelled.</p>';
			btn.disabled = false; btn.textContent = 'Generate ZIP';
		});
		btn.parentNode.insertBefore(cancelBtn, btn.nextSibling);

		function stopAll() {
			if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
			cancelBtn.remove();
		}

		function showError(msg) {
			if (finished) return; finished = true; stopAll();
			progress.innerHTML = '<p style="color:#cc0000;margin:0">❌ ' + msg + '</p>';
			btn.disabled = false; btn.textContent = 'Generate ZIP';
		}

		function triggerDone(data) {
			if (finished) return; finished = true; stopAll();
			progress.innerHTML = '<p style="color:#00a32a;margin:0">✓ Done! Downloading ZIP…</p>';
			btn.disabled = false; btn.textContent = 'Generate ZIP';
			window.location.href = ajaxUrl + '?action=axagbuin_bulk_invoice_fetch_zip&token=' + encodeURIComponent(data.token) + '&_wpnonce=' + encodeURIComponent(data.fetch_nonce) + '&filename=' + encodeURIComponent(data.filename);
		}

		function updateBar(count, total) {
			var pct = total ? Math.round(count / total * 100) : 0;
			if (!document.getElementById('axagen-cnt')) {
				progress.innerHTML = '<p style="margin:0 0 6px">Generating invoices: <b id="axagen-cnt">' + count + ' / ' + total + '</b></p><div style="background:#ddd;border-radius:4px;height:14px;overflow:hidden"><div id="axagen-bar" style="height:100%;width:' + pct + '%;background:#2271b1;transition:width 0.4s ease"></div></div>';
			} else {
				var cnt = document.getElementById('axagen-cnt');
				var bar = document.getElementById('axagen-bar');
				if (cnt) cnt.textContent = count + ' / ' + total;
				if (bar) bar.style.width = pct + '%';
			}
			btn.textContent = 'Generating… ' + pct + '%';
		}

		// Poll progress every 600ms
		pollTimer = setInterval(function () {
			var pfd = new FormData();
			pfd.set('action', 'axagbuin_bulk_invoice_progress');
			pfd.set('axagbuin_job_key', jobKey);
			pfd.set('_progress_nonce', progressNonce);
			fetch(ajaxUrl, { method: 'POST', body: pfd, credentials: 'same-origin' })
				.then(function (r) { return r.json(); })
				.then(function (d) {
					if (finished) return;
					if (d.error) { showError(d.error); return; }
					if (d.done) { triggerDone(d); return; }
					if (d.total !== undefined && d.count !== undefined) { updateBar(d.count, d.total); }
				})
				.catch(function () {});
		}, 600);

		// Main fetch — read response as backup and for errors
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function (res) {
				if (!res.ok) { showError('HTTP ' + res.status + '. Check plugin is uploaded correctly.'); return; }
				return res.text();
			})
			.then(function (text) {
				if (!text || finished) return;
				var lines = text.split('\n');
				for (var i = 0; i < lines.length; i++) {
					var line = lines[i].trim(); if (!line) continue;
					try {
						var msg = JSON.parse(line);
						if (msg.error) { showError(msg.error); return; }
						if (msg.done) { triggerDone(msg); return; }
					} catch (x) {}
				}
				if (!finished) showError('No response from server. Try re-uploading the plugin.');
			})
			.catch(function (err) { showError(err.message); });
	});
})();
