/**
 * SuiteMkt3k admin shared helpers.
 *
 * Exposes window.wmk = { request, toast, ... }
 * Alpine.js components are registered on alpine:init so they always exist
 * before Alpine scans the DOM (avoids race with defer / script order).
 */
(function (window) {
	'use strict';

	const cfg = window.SuiteMkt3k || {};

	function request(path, options) {
		options = options || {};
		const url = (path.startsWith('http') ? path : cfg.restUrl + path.replace(/^\/+/, ''));
		const headers = Object.assign({
			'Content-Type': 'application/json',
			'X-WP-Nonce': cfg.nonce,
		}, options.headers || {});
		return fetch(url, {
			method: options.method || 'GET',
			headers: headers,
			credentials: 'same-origin',
			body: options.body ? JSON.stringify(options.body) : undefined,
		}).then((res) => res.json().then((data) => ({ ok: res.ok, status: res.status, data })));
	}

	function toast(message, type) {
		const el = document.createElement('div');
		el.className = 'wmk-flash wmk-flash-' + (type || 'success');
		el.style.position = 'fixed';
		el.style.right = '24px';
		el.style.bottom = '24px';
		el.style.zIndex = '100000';
		el.textContent = message;
		document.body.appendChild(el);
		setTimeout(() => el.remove(), 4000);
	}

	function openMediaPicker(title, onSelect) {
		if (!window.wp || !window.wp.media) {
			alert((cfg.i18n && cfg.i18n.mediaUnavailable) || 'Media library is unavailable on this screen.');
			return;
		}
		const frame = window.wp.media({
			title: title || (cfg.i18n && cfg.i18n.selectImage) || 'Select image',
			library: { type: ['image'] },
			multiple: false,
		});
		frame.on('select', function () {
			const sel = frame.state().get('selection').first();
			if (!sel) return;
			onSelect(sel.toJSON());
		});
		frame.open();
	}
	window.wmkOpenMediaPicker = openMediaPicker;

	function ensureCalendarThemeStyles() {
		const id = 'wmk-fc-theme-overrides';
		let style = document.getElementById(id);
		if (!style) {
			style = document.createElement('style');
			style.id = id;
			document.head.appendChild(style);
		}
		style.textContent = [
			'.wmk-wrap #wmk-coupon-calendar, .wmk-wrap #wmk-coupon-calendar .fc {',
			'--fc-button-bg-color:#fff;--fc-button-border-color:#E2E8F0;--fc-button-text-color:#475569;',
			'--fc-button-hover-bg-color:rgba(42,178,229,.08);--fc-button-hover-border-color:#2ab2e5;',
			'--fc-button-active-bg-color:rgba(42,178,229,.14);--fc-button-active-border-color:#2ab2e5;',
			'}',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-button,',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-button-primary,',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-button-group > .fc-button {',
			'background-color:#fff !important;border:1px solid #E2E8F0 !important;color:#475569 !important;',
			'border-radius:10px !important;box-shadow:none !important;font-weight:600 !important;',
			'}',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-button:hover,',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-button-primary:hover,',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-button-group > .fc-button:hover {',
			'background-color:rgba(42,178,229,.08) !important;border-color:#2ab2e5 !important;color:#2ab2e5 !important;',
			'}',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-button-primary:not(:disabled).fc-button-active,',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-button-primary:not(:disabled):active,',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-button-group > .fc-button.fc-button-active {',
			'background-color:rgba(42,178,229,.14) !important;border-color:#2ab2e5 !important;color:#2ab2e5 !important;',
			'}',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-direction-ltr .fc-button-group > .fc-button:not(:first-child) {',
			'margin-left:6px !important;border-top-left-radius:10px !important;border-bottom-left-radius:10px !important;',
			'}',
			'.wmk-wrap #wmk-coupon-calendar .fc .fc-direction-ltr .fc-button-group > .fc-button:not(:last-child) {',
			'border-top-right-radius:10px !important;border-bottom-right-radius:10px !important;',
			'}',
		].join('');
	}

	function applyCalendarThemeVars(root) {
		if (!root) return;
		[
			['--fc-button-bg-color', '#ffffff'],
			['--fc-button-border-color', '#E2E8F0'],
			['--fc-button-text-color', '#475569'],
			['--fc-button-hover-bg-color', 'rgba(42, 178, 229, 0.08)'],
			['--fc-button-hover-border-color', '#2ab2e5'],
			['--fc-button-active-bg-color', 'rgba(42, 178, 229, 0.14)'],
			['--fc-button-active-border-color', '#2ab2e5'],
		].forEach(function (pair) {
			root.style.setProperty(pair[0], pair[1]);
		});
	}

	function initCouponCalendar() {
		const el = document.getElementById('wmk-coupon-calendar');
		const data = window.SuiteMkt3kCalendar;
		if (!el || !data || !window.FullCalendar) {
			return;
		}
		ensureCalendarThemeStyles();
		const locale = data.locale === 'es' ? 'es' : 'en';
		const cal = new window.FullCalendar.Calendar(el, {
			initialView: 'dayGridMonth',
			locale: locale,
			height: 'auto',
			contentHeight: 'auto',
			dayMaxEventRows: 2,
			events: data.events || [],
			headerToolbar: {
				left: 'prev,next today',
				center: 'title',
				right: 'dayGridMonth,timeGridWeek',
			},
		});
		cal.render();
		ensureCalendarThemeStyles();
		const fcRoot = el.querySelector('.fc');
		applyCalendarThemeVars(el);
		applyCalendarThemeVars(fcRoot);
		requestAnimationFrame(function () {
			ensureCalendarThemeStyles();
			applyCalendarThemeVars(el);
			applyCalendarThemeVars(el.querySelector('.fc'));
		});
	}

	function initLogoPicker() {
		const root = document.getElementById('wmk-logo-picker');
		if (!root || !window.wp || !window.wp.media) return;
		const idInput = root.querySelector('#wmk-logo-id');
		const preview = root.querySelector('#wmk-logo-preview');
		const choose  = root.querySelector('#wmk-logo-choose');
		const remove  = root.querySelector('#wmk-logo-remove');
		let frame = null;
		if (choose) {
			choose.addEventListener('click', function (e) {
				e.preventDefault();
				if (!frame) {
					frame = window.wp.media({
						title: (cfg.i18n && cfg.i18n.selectLogo) || 'Select logo',
						library: { type: ['image'] },
						multiple: false,
					});
					frame.on('select', function () {
						const sel = frame.state().get('selection').first();
						if (!sel) return;
						const att = sel.toJSON();
						if (idInput) idInput.value = att.id;
						if (preview) {
							preview.src = att.url;
							preview.style.display = '';
						}
						if (remove) remove.style.display = '';
					});
				}
				frame.open();
			});
		}
		if (remove) {
			remove.addEventListener('click', function (e) {
				e.preventDefault();
				if (idInput) idInput.value = '0';
				if (preview) { preview.src = ''; preview.style.display = 'none'; }
				remove.style.display = 'none';
			});
		}
	}

	function registerAlpineComponents() {
		/* Reserved for future Alpine.data components (sidebar, modals, etc.). */
	}

	/**
	 * Rebuild blog post <select> options (Alpine x-for inside <select> is unreliable in browsers).
	 *
	 * @param {HTMLSelectElement|null} selectEl
	 * @param {Array<{id:number,title:string}>} posts
	 * @param {string} placeholder
	 * @param {string} [keepValue]
	 */
	function fillBlogPostSelect(selectEl, posts, placeholder, keepValue) {
		if (!selectEl) {
			return;
		}
		const previous = keepValue !== undefined ? keepValue : selectEl.value;
		selectEl.innerHTML = '';
		const empty = document.createElement('option');
		empty.value = '';
		empty.textContent = placeholder || '—';
		selectEl.appendChild(empty);
		(posts || []).forEach(function (post) {
			const opt = document.createElement('option');
			opt.value = String(post.id);
			opt.textContent = String(post.title || '');
			if (post.import) {
				opt.setAttribute('data-wmk-import', JSON.stringify(post.import));
			}
			selectEl.appendChild(opt);
		});
		if (previous) {
			selectEl.value = String(previous);
		}
	}

	function selectedBlogPostId(data, selectEl) {
		const fromState = Number(data && data.importPostId);
		if (fromState > 0) {
			return fromState;
		}
		if (selectEl && selectEl.value) {
			return Number(selectEl.value);
		}
		return 0;
	}

	function parseImportPayload(raw) {
		if (!raw) {
			return null;
		}
		try {
			const p = typeof raw === 'string' ? JSON.parse(raw) : raw;
			return p && typeof p === 'object' ? p : null;
		} catch (e) {
			return null;
		}
	}

	function importPayloadFromSelect(selectEl) {
		if (!selectEl || selectEl.selectedIndex < 0) {
			return null;
		}
		const opt = selectEl.options[selectEl.selectedIndex];
		if (!opt) {
			return null;
		}
		return parseImportPayload(opt.getAttribute('data-wmk-import'));
	}

	function setFormField(form, name, value) {
		if (!form) {
			return;
		}
		const el = form.querySelector('[name="' + name + '"]');
		if (!el) {
			return;
		}
		el.value = value == null ? '' : String(value);
		el.dispatchEvent(new Event('input', { bubbles: true }));
		el.dispatchEvent(new Event('change', { bubbles: true }));
	}

	function alpineDataFromEl(el) {
		if (!el || !el._x_dataStack || !el._x_dataStack.length) {
			return null;
		}
		return el._x_dataStack[0];
	}

	function applyImportedPost(data, form, p) {
		if (!p) {
			return false;
		}
		if (p.title) {
			if (data) {
				data.heading = p.title;
			}
			setFormField(form, 'content[heading]', p.title);
		}
		if (p.subject) {
			if (data) {
				data.subject = p.subject;
			}
			setFormField(form, 'subject', p.subject);
		}
		if (p.excerpt) {
			if (data) {
				data.body = p.excerpt;
			}
			setFormField(form, 'content[body]', p.excerpt);
		}
		if (p.image_url) {
			const imageId = Number(p.image_id || 0);
			if (data) {
				data.image_url = p.image_url;
				data.image_id  = imageId;
			}
			setFormField(form, 'content[image_url]', p.image_url);
			setFormField(form, 'content[image_id]', imageId);
		}
		if (p.link) {
			if (data) {
				data.cta_url = p.link;
			}
			setFormField(form, 'content[cta_url]', p.link);
		}
		if (typeof window.wmkSyncEmailPreview === 'function') {
			window.requestAnimationFrame(function () {
				window.wmkSyncEmailPreview();
			});
		}
		return true;
	}

	function runBlogPostImport(triggerEl) {
		const grid = triggerEl && triggerEl.closest ? triggerEl.closest('[data-wmk-designer="newsletter"]') : null;
		if (!grid) {
			toast((cfg.i18n && cfg.i18n.importFailed) || 'Could not import this post.', 'error');
			return false;
		}
		const select = grid.querySelector('[data-wmk-blog-post-select]');
		const form = grid.querySelector('.wmk-designer-main form') || grid.querySelector('form.wmk-card');
		const main = grid.querySelector('.wmk-designer-main');
		const alpineData = main ? alpineDataFromEl(main) : null;

		if (!select || !select.value) {
			toast((cfg.i18n && cfg.i18n.selectPostFirst) || 'Select a post first.', 'error');
			return false;
		}

		if (alpineData) {
			alpineData.importPostId = select.value;
		}

		const embedded = importPayloadFromSelect(select);
		if (embedded && applyImportedPost(alpineData, form, embedded)) {
			toast((cfg.i18n && cfg.i18n.importSuccess) || 'Post imported into the campaign.', 'success');
			return true;
		}

		const id = Number(select.value);
		if (!id) {
			toast((cfg.i18n && cfg.i18n.selectPostFirst) || 'Select a post first.', 'error');
			return false;
		}

		request('posts/' + id).then(function (res) {
			if (!res.ok || !res.data || res.data.ok === false) {
				toast((cfg.i18n && cfg.i18n.importFailed) || 'Could not import this post.', 'error');
				return;
			}
			if (applyImportedPost(alpineData, form, res.data)) {
				toast((cfg.i18n && cfg.i18n.importSuccess) || 'Post imported into the campaign.', 'success');
			}
		}).catch(function () {
			toast((cfg.i18n && cfg.i18n.importFailed) || 'Could not import this post.', 'error');
		});
		return true;
	}

	function initNewsletterBlogImport() {
		document.addEventListener('click', function (e) {
			const btn = e.target.closest('[data-wmk-blog-import-btn]');
			if (!btn) {
				return;
			}
			e.preventDefault();
			e.stopPropagation();
			runBlogPostImport(btn);
		});
	}

	window.wmkImportBlogPostClick = function (event) {
		if (event && event.preventDefault) {
			event.preventDefault();
		}
		const el = (event && event.currentTarget) ? event.currentTarget : null;
		if (el) {
			runBlogPostImport(el);
		}
		return false;
	};

	/**
	 * Attach newsletter designer actions to inline x-data (predesign loaded from PHP JSON).
	 *
	 * @param {Record<string, unknown>} data Alpine $data
	 * @param {HTMLElement} [root] Designer root (.wmk-designer-main)
	 */
	window.wmkNewsletterInit = function (data, root) {
		if (!data || typeof data !== 'object') {
			return;
		}

		const scope = root && root.querySelector ? root : document;
		const form = scope.querySelector('form.wmk-card') || scope.querySelector('form');
		const blogSelect = scope.querySelector('[data-wmk-blog-post-select]');
		const importBtn  = scope.querySelector('[data-wmk-blog-import-btn]');
		const postsPlaceholder = (cfg.i18n && cfg.i18n.selectBlogPost) || '— Select a post —';

		if (blogSelect) {
			blogSelect.addEventListener('change', function () {
				data.importPostId = blogSelect.value;
			});
		}

		data.pickImage = function () {
			openMediaPicker(
				(cfg.i18n && cfg.i18n.selectImage) || 'Select image',
				function (att) {
					data.image_id  = Number(att.id || 0);
					data.image_url = String(att.url || '');
					if (typeof window.wmkSyncEmailPreview === 'function') {
						window.wmkSyncEmailPreview();
					}
				}
			);
		};

		data.applyTemplate = function () {
			const templates = (window.SuiteMkt3k && window.SuiteMkt3k.newsletterTemplates) || cfg.newsletterTemplates || {};
			const t = templates[data.template];
			if (!t) {
				return;
			}
			if (t.subject) {
				data.subject = t.subject;
			}
			data.heading   = t.heading;
			data.body      = t.body;
			data.cta_label = t.cta_label;
			data.accent    = t.accent;
			if (typeof t.header_color !== 'undefined') {
				data.header_color = t.header_color;
			}
			if (typeof t.secondary_accent !== 'undefined') {
				data.secondary_accent = t.secondary_accent;
			}
			if (typeof t.badge_label !== 'undefined') {
				data.badge_label = t.badge_label;
			}
			if (typeof t.cta_radius !== 'undefined') {
				data.cta_radius = t.cta_radius;
			}
			if (t.cta_url) {
				data.cta_url = t.cta_url;
			}
			if (typeof t.preheader !== 'undefined') {
				data.preheader = t.preheader;
			}
			if (typeof t.footer_color !== 'undefined') {
				data.footer_color = t.footer_color;
			}
			if (t.unsubscribe_text) {
				data.unsubscribe_text = t.unsubscribe_text;
			}
			if (t.unsubscribe_cta) {
				data.unsubscribe_cta = t.unsubscribe_cta;
			}
			if (typeof window.wmkSyncEmailPreview === 'function') {
				window.wmkSyncEmailPreview();
			}
		};

		data.loadBlogPosts = function () {
			request('posts?per_page=30').then(function (res) {
				if (res.ok && res.data && res.data.posts) {
					data.blogPosts = res.data.posts;
					data.blogPostsLoaded = true;
					// Only rebuild when the dropdown is empty (PHP already rendered options on load).
					if (blogSelect && blogSelect.options.length <= 1) {
						fillBlogPostSelect(blogSelect, data.blogPosts, postsPlaceholder, data.importPostId);
						if (blogSelect.value) {
							data.importPostId = blogSelect.value;
						}
					}
					return;
				}
				if (blogSelect && blogSelect.options.length <= 1) {
					toast((cfg.i18n && cfg.i18n.postsLoadFailed) || 'Could not load blog posts.', 'error');
				}
			}).catch(function () {
				if (blogSelect && blogSelect.options.length <= 1) {
					toast((cfg.i18n && cfg.i18n.postsLoadFailed) || 'Could not load blog posts.', 'error');
				}
			});
		};

		data.importBlogPost = function () {
			runBlogPostImport(importBtn || blogSelect || root);
		};

		data.loadBlogPosts();
	};

	function bootAlpineDesigners() {
		registerAlpineComponents();
		if (typeof window.__wmkAlpineStart === 'function') {
			window.__wmkAlpineStart();
			delete window.__wmkAlpineStart;
		}
		if (typeof window.wmkInitEmailPreview === 'function') {
			window.wmkInitEmailPreview();
		}
		if (typeof window.wmkSyncEmailPreview === 'function') {
			window.requestAnimationFrame(function () {
				window.wmkSyncEmailPreview();
			});
		}
	}

	document.addEventListener('alpine:init', registerAlpineComponents);

	function initDonationPopup() {
		var popup = document.getElementById('wmk-donation-popup');
		if (!popup) {
			return;
		}
		// Legacy: do not persist dismiss across Dashboard visits.
		if (window.localStorage) {
			localStorage.removeItem('suitemkt3k_donation_dismissed');
		}
		popup.removeAttribute('hidden');
		window.setTimeout(function () {
			popup.classList.add('show');
		}, 700);
		var closeBtn = popup.querySelector('.wmk-donation-close');
		if (!closeBtn) {
			return;
		}
		closeBtn.addEventListener('click', function () {
			popup.classList.remove('show');
			window.setTimeout(function () {
				popup.setAttribute('hidden', 'hidden');
			}, 500);
		});
	}

	/**
	 * Ensure WP/third-party notices sit above the SuiteMkt3k header, not inside it.
	 * Complements core common.js (insertAfter .wp-header-end / first .wrap h1).
	 */
	function relocateAdminNotices() {
		const wrap = document.querySelector('.wrap.wmk-wrap');
		if (!wrap) {
			return;
		}
		const anchor = wrap.querySelector('.wp-header-end');
		if (!anchor || !anchor.parentNode) {
			return;
		}
		const trapped = wrap.querySelectorAll('.wmk-header-banner .notice, .wmk-header-banner .updated, .wmk-header-banner .error, .wmk-header-banner .update-nag');
		trapped.forEach(function (el) {
			if (el.classList.contains('inline') || el.classList.contains('below-h2')) {
				return;
			}
			anchor.parentNode.insertBefore(el, anchor.nextSibling);
		});
	}

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

	ready(function () {
		initNewsletterBlogImport();
		initLogoPicker();
		initCouponCalendar();
		initDonationPopup();
		bootAlpineDesigners();
		relocateAdminNotices();
		// Core common.js also runs on ready; re-check shortly after.
		window.setTimeout(relocateAdminNotices, 0);
		window.setTimeout(relocateAdminNotices, 100);
	});

	window.wmk = { request, toast, cfg, openMediaPicker };
})(window);
