/**
 * AIEO — shared searchable multi-select VALUE picker (arbitrary STRING values).
 *
 * A lean sibling of dmm-product-picker.js for non-product options — marketing
 * channels, campaigns, creatives, UTM terms, etc. Same modal UX (search →
 * checkboxes → chips → Done, multi-select) but values are plain strings, so the
 * product picker's integer-id / variation / status machinery does not apply.
 * This is ADDITIVE and shares nothing mutable with the product picker.
 *
 * Markup (rendered by PHP):
 *   <span class="aieo-valpick" data-search-action="aieo_roi_value_search"
 *         data-title="Choose values" data-placeholder="Search…" data-multi="1"
 *         data-empty="— all —" data-context="type:aieo-roi-type"
 *         data-ajaxurl="…/admin-ajax.php" data-nonce="…">
 *     <input type="hidden" class="aieo-valpick-store" value="">
 *     <button type="button" class="button aieo-valpick-open">— all —</button>
 *     <span class="aieo-valpick-chips"></span>
 *   </span>
 *
 * data-multi="0"  → single-select (radio-like; picking one replaces the set).
 * data-context    → "param:elementId,…": each element's value is sent with the
 *                   search. If the element is itself a .aieo-valpick, its values
 *                   are sent as param[] (enables cascading multi-select).
 *
 * Public API (window.aieoValPicker):
 *   mount(root)            — (re)scan for .aieo-valpick wrappers (idempotent)
 *   values(wrap)           — ['a','b'] selected value strings
 *   items(wrap)            — [{value,label}]
 *   set(wrap, items)       — replace selection ([{value,label}] or ['a',…])
 *   clear(wrap)
 * Fires 'aieo-valpick:change' (bubbles) on the wrapper when the set changes.
 */
(function () {
	'use strict';

	/* -------- CSS (injected once) ---------------------------------------- */
	(function css() {
		if (document.getElementById('aieo-valpick-css')) { return; }
		var c =
			'.aieo-valpick{display:inline-flex;flex-direction:column;gap:4px;min-width:200px;vertical-align:bottom;}' +
			'.aieo-valpick-open{display:block;width:100%;min-height:30px;text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}' +
			'.aieo-valpick-chips{display:flex;flex-wrap:wrap;gap:5px;max-height:104px;overflow:auto;}' +
			'.aieo-valpick-chips:empty{display:none;}' +
			'.aieo-valpick-chips .aieo-vchip{display:inline-flex;align-items:center;gap:6px;background:#2271b1;color:#fff;border-radius:13px;padding:2px 9px;font-size:12px;line-height:1.5;max-width:100%;}' +
			'.aieo-valpick-chips .aieo-vchip-t{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:240px;}' +
			'.aieo-valpick-chips .aieo-vchip-x{cursor:pointer;font-weight:700;opacity:.85;}' +
			'.aieo-valpick-chips .aieo-vchip-x:hover{opacity:1;}' +
			'.aieo-vm-overlay{position:fixed;inset:0;z-index:100001;background:rgba(15,23,42,.55);display:flex;align-items:center;justify-content:center;padding:16px;}' +
			'.aieo-vm-card{background:#fff;border-radius:10px;box-shadow:0 24px 48px rgba(0,0,0,.25);width:min(560px,100%);height:min(80vh,680px);display:flex;flex-direction:column;overflow:hidden;}' +
			'.aieo-vm-head{display:flex;align-items:center;justify-content:space-between;padding:13px 18px;border-bottom:1px solid #e5e7eb;}' +
			'.aieo-vm-head h3{margin:0;font-size:15px;}' +
			'.aieo-vm-close{cursor:pointer;border:0;background:none;font-size:22px;line-height:1;color:#6b7280;}' +
			'.aieo-vm-search{padding:10px 18px;border-bottom:1px solid #f0f0f1;}' +
			'.aieo-vm-search input{width:100%;}' +
			'.aieo-vm-tools{display:flex;gap:12px;padding:6px 18px 0;}' +
			'.aieo-vm-tools a{font-size:12px;cursor:pointer;}' +
			'.aieo-vm-results{overflow:auto;padding:4px 10px;flex:1;min-height:160px;}' +
			'.aieo-vm-row{display:flex;align-items:center;gap:8px;padding:6px 4px;border-bottom:1px solid #f3f4f5;}' +
			'.aieo-vm-row label{display:flex;align-items:center;gap:8px;margin:0;flex:1;cursor:pointer;}' +
			'.aieo-vm-foot{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:12px 18px;border-top:1px solid #e5e7eb;background:#f9fafb;}' +
			'.aieo-vm-count{font-size:12px;color:#50575e;}' +
			'.aieo-vm-muted{color:#787c82;font-size:12px;padding:16px 10px;}';
		var s = document.createElement('style');
		s.id = 'aieo-valpick-css';
		s.textContent = c;
		document.head.appendChild(s);
	})();

	/* -------- helpers ----------------------------------------------------- */
	function esc(s) { return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
	function storeEl(w) { return w.querySelector('.aieo-valpick-store'); }
	function chipsEl(w) { return w.querySelector('.aieo-valpick-chips'); }
	function openBtn(w) { return w.querySelector('.aieo-valpick-open'); }
	function isMulti(w) { return w.getAttribute('data-multi') !== '0'; }
	function cfg(w) { return { ajax: w.getAttribute('data-ajaxurl') || window.ajaxurl || '/wp-admin/admin-ajax.php', nonce: w.getAttribute('data-nonce') || '' }; }

	// Selection is the hidden input's value (newline-joined values — newline can't
	// occur in a UTM/campaign value, so it is a safe separator) + a label map on
	// the wrapper element for display.
	function items(w) {
		var raw = (storeEl(w) && storeEl(w).value || '').trim();
		if (!raw) { return []; }
		var lm = w.__valLabels || {};
		return raw.split('\n').filter(function (v) { return v !== ''; }).map(function (v) { return { value: v, label: lm[v] || v }; });
	}
	function values(w) { return items(w).map(function (it) { return it.value; }); }
	function setItems(w, arr) {
		var lm = {}, vals = [];
		(arr || []).forEach(function (it) {
			var o = (typeof it === 'string') ? { value: it, label: it } : it;
			if (o.value == null || o.value === '') { return; }
			if (vals.indexOf(o.value) !== -1) { return; }
			vals.push(o.value);
			lm[o.value] = o.label || o.value;
		});
		w.__valLabels = lm;
		if (storeEl(w)) { storeEl(w).value = vals.join('\n'); }
		renderChips(w);
		w.dispatchEvent(new CustomEvent('aieo-valpick:change', { bubbles: true }));
	}
	function renderChips(w) {
		var box = chipsEl(w);
		var its = items(w);
		if (openBtn(w)) {
			openBtn(w).textContent = its.length
				? (its.length + ' ' + (its.length === 1 ? 'selected' : 'selected'))
				: (w.getAttribute('data-empty') || '— all —');
		}
		if (!box) { return; }
		box.innerHTML = '';
		its.forEach(function (it) {
			var c = document.createElement('span');
			c.className = 'aieo-vchip';
			c.innerHTML = '<span class="aieo-vchip-t" title="' + esc(it.label) + '">' + esc(it.label) + '</span>' +
				'<span class="aieo-vchip-x" data-v="' + esc(it.value) + '">×</span>';
			box.appendChild(c);
		});
	}

	// Build &param=… (or param[]=…) context from data-context, resolving linked
	// plain inputs/selects directly and linked .aieo-valpick wrappers as arrays.
	function contextQuery(w) {
		var raw = w.getAttribute('data-context') || '';
		var parts = [];
		raw.split(',').forEach(function (pair) {
			pair = pair.trim();
			if (!pair) { return; }
			var i = pair.indexOf(':');
			if (i < 0) { return; }
			var pname = pair.slice(0, i), eid = pair.slice(i + 1);
			var el = document.getElementById(eid);
			if (!el) { return; }
			var pw = el.closest ? el.closest('.aieo-valpick') : null;
			if (pw) {
				values(pw).forEach(function (v) { parts.push(encodeURIComponent(pname) + '[]=' + encodeURIComponent(v)); });
			} else if (el.value !== '') {
				parts.push(encodeURIComponent(pname) + '=' + encodeURIComponent(el.value));
			}
		});
		return parts.join('&');
	}

	/* -------- modal (shared singleton) ------------------------------------ */
	var vm = null, vmState = { wrap: null, sel: {} };

	function vmBuild() {
		if (vm) { return vm; }
		var ov = document.createElement('div');
		ov.className = 'aieo-vm-overlay';
		ov.style.display = 'none';
		ov.innerHTML =
			'<div class="aieo-vm-card" role="dialog" aria-modal="true">' +
			'<div class="aieo-vm-head"><h3></h3><button type="button" class="aieo-vm-close" aria-label="Close">×</button></div>' +
			'<div class="aieo-vm-search"><input type="search" class="aieo-vm-q"></div>' +
			'<div class="aieo-vm-tools"><a class="aieo-vm-all">Select all shown</a><a class="aieo-vm-none">Clear</a></div>' +
			'<div class="aieo-vm-results"></div>' +
			'<div class="aieo-vm-foot"><span class="aieo-vm-count"></span><span><button type="button" class="button aieo-vm-cancel">Cancel</button> <button type="button" class="button button-primary aieo-vm-done">Done</button></span></div>' +
			'</div>';
		document.body.appendChild(ov);
		vm = ov;
		ov.querySelector('.aieo-vm-close').addEventListener('click', vmClose);
		ov.querySelector('.aieo-vm-cancel').addEventListener('click', vmClose);
		ov.addEventListener('click', function (e) { if (e.target === ov) { vmClose(); } });
		ov.querySelector('.aieo-vm-done').addEventListener('click', vmCommit);
		ov.querySelector('.aieo-vm-all').addEventListener('click', function () {
			if (!isMulti(vmState.wrap)) { return; }
			vm.querySelectorAll('.aieo-vm-cb').forEach(function (cb) { if (!cb.checked) { cb.checked = true; vmToggle(cb); } });
		});
		ov.querySelector('.aieo-vm-none').addEventListener('click', function () { vmState.sel = {}; vm.querySelectorAll('.aieo-vm-cb').forEach(function (cb) { cb.checked = false; }); vmCount(); });
		var q = ov.querySelector('.aieo-vm-q');
		var timer;
		q.addEventListener('input', function () { clearTimeout(timer); timer = setTimeout(function () { vmSearch(q.value); }, 250); });
		ov.querySelector('.aieo-vm-results').addEventListener('change', function (e) { if (e.target.classList.contains('aieo-vm-cb')) { vmToggle(e.target); } });
		return ov;
	}
	function vmOpen(w) {
		vmBuild();
		vmState.wrap = w;
		vmState.sel = {};
		items(w).forEach(function (it) { vmState.sel[it.value] = it; });
		vm.querySelector('.aieo-vm-head h3').textContent = w.getAttribute('data-title') || 'Choose values';
		vm.querySelector('.aieo-vm-q').setAttribute('placeholder', w.getAttribute('data-placeholder') || 'Search…');
		vm.querySelector('.aieo-vm-q').value = '';
		vm.querySelector('.aieo-vm-tools').style.display = isMulti(w) ? 'flex' : 'none';
		vmCount();
		vm.style.display = 'flex';
		document.addEventListener('keydown', vmKey);
		vmSearch('');
		setTimeout(function () { vm.querySelector('.aieo-vm-q').focus(); }, 30);
	}
	function vmClose() { if (vm) { vm.style.display = 'none'; document.removeEventListener('keydown', vmKey); } }
	function vmKey(e) { if (e.key === 'Escape') { vmClose(); } }
	function vmCommit() { if (vmState.wrap) { setItems(vmState.wrap, Object.keys(vmState.sel).map(function (k) { return vmState.sel[k]; })); } vmClose(); }
	function vmCount() {
		var n = Object.keys(vmState.sel).length;
		vm.querySelector('.aieo-vm-count').textContent = n + ' ' + (n === 1 ? 'selected' : 'selected');
	}
	function vmToggle(cb) {
		var row = cb.closest('.aieo-vm-row');
		var v = row.getAttribute('data-value'), label = row.getAttribute('data-label') || v;
		if (cb.checked) {
			if (!isMulti(vmState.wrap)) {
				vmState.sel = {};
				vm.querySelectorAll('.aieo-vm-cb').forEach(function (o) { if (o !== cb) { o.checked = false; } });
			}
			vmState.sel[v] = { value: v, label: label };
		} else {
			delete vmState.sel[v];
		}
		vmCount();
	}
	function vmSearch(q) {
		var w = vmState.wrap, box = vm.querySelector('.aieo-vm-results');
		box.innerHTML = '<div class="aieo-vm-muted">Searching…</div>';
		var c = cfg(w);
		var ctx = contextQuery(w);
		var extra = w.getAttribute('data-params') || ''; // fixed key=value&… (e.g. level=source)
		var url = c.ajax + '?action=' + encodeURIComponent(w.getAttribute('data-search-action') || '') +
			'&nonce=' + encodeURIComponent(c.nonce) + '&q=' + encodeURIComponent(q || '') +
			(extra ? '&' + extra : '') + (ctx ? '&' + ctx : '');
		fetch(url, { credentials: 'same-origin' }).then(function (r) { return r.json(); }).then(function (j) {
			var rows = (j && j.results) ? j.results : ((j && j.data && j.data.results) ? j.data.results : []);
			box.innerHTML = '';
			if (!rows.length) { box.innerHTML = '<div class="aieo-vm-muted">No matches.</div>'; return; }
			rows.forEach(function (r) {
				var v = (r.value != null) ? String(r.value) : String(r);
				var label = r.label || v;
				var row = document.createElement('div');
				row.className = 'aieo-vm-row';
				row.setAttribute('data-value', v);
				row.setAttribute('data-label', label);
				row.innerHTML = '<label><input type="checkbox" class="aieo-vm-cb"><span>' + esc(label) + '</span></label>';
				row.querySelector('.aieo-vm-cb').checked = !!vmState.sel[v];
				box.appendChild(row);
			});
		}).catch(function () { box.innerHTML = '<div class="aieo-vm-muted">Search failed.</div>'; });
	}

	/* -------- mount + delegated events ------------------------------------ */
	function mountOne(w) { if (w) { renderChips(w); w.setAttribute('data-vp-mounted', '1'); } }
	function mount(root) {
		root = root || document;
		if (root.classList && root.classList.contains('aieo-valpick')) { mountOne(root); }
		var ws = root.querySelectorAll ? root.querySelectorAll('.aieo-valpick') : [];
		Array.prototype.forEach.call(ws, mountOne);
	}
	document.addEventListener('click', function (e) {
		var open = e.target.closest && e.target.closest('.aieo-valpick-open');
		if (open) { var w = open.closest('.aieo-valpick'); if (w) { vmOpen(w); } return; }
		var x = e.target.closest && e.target.closest('.aieo-valpick-chips .aieo-vchip-x');
		if (x) {
			var wrap = x.closest('.aieo-valpick');
			var v = x.getAttribute('data-v');
			if (wrap) { setItems(wrap, items(wrap).filter(function (it) { return it.value !== v; })); }
		}
	});

	window.aieoValPicker = {
		mount: mount,
		values: values,
		items: items,
		set: function (w, arr) { setItems(w, arr); },
		clear: function (w) { setItems(w, []); }
	};

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