/**
 * Frontend Stats Bar — JavaScript
 *
 * Loads stats via AJAX, populates the skeleton bar, and manages
 * hide/unhide toggle with localStorage persistence.
 *
 * No jQuery dependency — vanilla JS only.
 *
 * @package opti-behavior
 * @since   1.2.3
 */

(function () {
	'use strict';

	var STORAGE_KEY = 'opti_behavior_stats_bar_collapsed';
	var config      = window.optiBehaviorStatsBar || {};
	var bar         = document.getElementById('opti-stats-bar');
	var pill        = document.getElementById('opti-stats-bar-pill');
	var layoutFrame = null;

	if (!bar || !pill || !config.ajax_url) {
		return;
	}

	/* ------------------------------------------------------------------
	   Body offset — push page content below the fixed bar
	   ------------------------------------------------------------------ */
	function updateBodyOffset() {
		if (bar.style.display === 'none' || bar.offsetHeight === 0) {
			document.body.classList.remove('opti-stats-bar-active');
			document.body.classList.add('opti-stats-bar-collapsed');
		} else {
			var barHeight = bar.offsetHeight;
			document.body.style.setProperty('--osb-bar-height', barHeight + 'px');
			document.body.classList.add('opti-stats-bar-active');
			document.body.classList.remove('opti-stats-bar-collapsed');
		}
	}

	/* ------------------------------------------------------------------
	   Lucide icons — create them if the global lucide object exists
	   ------------------------------------------------------------------ */
	function initIcons() {
		if (window.lucide && typeof window.lucide.createIcons === 'function') {
			window.lucide.createIcons();
		}
	}

	function getStatsPeriod() {
		return config.settings && config.settings.period ? config.settings.period : 'last30days';
	}

	function buildCurrentPageAdminUrl(baseUrl) {
		if (!baseUrl) {
			return '';
		}

		var separator = baseUrl.indexOf('?') === -1 ? '?' : '&';

		return baseUrl +
			separator +
			'page_url=' + encodeURIComponent(window.location.href) +
			'&date_range=' + encodeURIComponent(getStatsPeriod());
	}

	/* ------------------------------------------------------------------
	   Sessions link — jump to heatmaps filtered to current page
	   ------------------------------------------------------------------ */
	function getHeatmapDetailUrl(pageId) {
		if (!config.heatmap_detail_url || !pageId || pageId <= 0) {
			return '';
		}

		var separator = config.heatmap_detail_url.indexOf('?') === -1 ? '?' : '&';

		return config.heatmap_detail_url +
			separator +
			'page_id=' + encodeURIComponent(pageId) +
			'&type=click&device=desktop' +
			'&date_range=' + encodeURIComponent(getStatsPeriod());
	}

	function getHeatmapsUrl(pageId) {
		var detailUrl = getHeatmapDetailUrl(pageId);
		if (detailUrl) {
			return detailUrl;
		}

		return buildCurrentPageAdminUrl(config.heatmaps_url);
	}

	function updateHeatmapsLinks(pageId) {
		var heatmapsUrl = getHeatmapsUrl(pageId);
		var links = bar.querySelectorAll('.opti-stats-bar__item--sessions-link');

		if (!heatmapsUrl || !links.length) {
			return;
		}

		for (var i = 0; i < links.length; i++) {
			links[i].setAttribute('href', heatmapsUrl);
		}
	}

	/* ------------------------------------------------------------------
	   Recordings link — jump to Pro recordings filtered to current page
	   ------------------------------------------------------------------ */
	function getRecordingsUrl() {
		return buildCurrentPageAdminUrl(config.recordings_url);
	}

	function updateRecordingsLinks() {
		var recordingsUrl = getRecordingsUrl();
		var links = bar.querySelectorAll('.opti-stats-bar__item--recordings-link');

		if (!recordingsUrl || !links.length) {
			return;
		}

		for (var i = 0; i < links.length; i++) {
			links[i].setAttribute('href', recordingsUrl);
		}
	}

	/* ------------------------------------------------------------------
	   Responsive layout — fit enabled Free/Pro stats to the admin viewport
	   ------------------------------------------------------------------ */
	function layoutOverflows(inner, stats) {
		return (
			stats.scrollWidth - stats.clientWidth > 1 ||
			inner.scrollWidth - inner.clientWidth > 1
		);
	}

	function applyResponsiveLayout() {
		var inner = bar.querySelector('.opti-stats-bar__inner');
		var stats = bar.querySelector('.opti-stats-bar__stats');

		if (!inner || !stats) {
			return;
		}

		bar.setAttribute('data-stat-count', stats.querySelectorAll('.opti-stats-bar__item').length);
		bar.classList.remove('opti-stats-bar--compact', 'opti-stats-bar--wrap');

		if (bar.style.display === 'none' || bar.offsetHeight === 0) {
			updateBodyOffset();
			return;
		}

		// First try the full-label single-row layout, then progressively compact.
		if (layoutOverflows(inner, stats)) {
			bar.classList.add('opti-stats-bar--compact');
		}

		// If compact chips still do not fit, wrap the stat viewport instead of
		// hiding the Forms/last Pro chip behind the fixed hide button.
		if (layoutOverflows(inner, stats)) {
			bar.classList.add('opti-stats-bar--wrap');
		}

		updateBodyOffset();
	}

	function scheduleResponsiveLayout() {
		if (layoutFrame) {
			window.cancelAnimationFrame(layoutFrame);
		}

		layoutFrame = window.requestAnimationFrame(function () {
			layoutFrame = null;
			applyResponsiveLayout();
		});
	}

	/* ------------------------------------------------------------------
	   Collapse / Expand
	   ------------------------------------------------------------------ */
	function isCollapsed() {
		try {
			return localStorage.getItem(STORAGE_KEY) === '1';
		} catch (e) {
			return false;
		}
	}

	function setCollapsed(val) {
		try {
			localStorage.setItem(STORAGE_KEY, val ? '1' : '0');
		} catch (e) {
			// localStorage not available — fail silently.
		}
	}

	function collapse() {
		bar.style.transform = 'translateY(-100%)';
		bar.style.opacity   = '0';
		document.body.classList.remove('opti-stats-bar-active');
		document.body.classList.add('opti-stats-bar-collapsed');
		setTimeout(function () {
			bar.style.display  = 'none';
			pill.style.display = 'flex';
			initIcons();
		}, 300);
		setCollapsed(true);
	}

	function expand() {
		pill.style.display = 'none';
		bar.style.display  = 'block';
		// Force reflow before animating.
		void bar.offsetHeight;
		bar.style.transform = 'translateY(0)';
		bar.style.opacity   = '1';
		setCollapsed(false);
		initIcons();
		scheduleResponsiveLayout();
	}

	// Apply initial state.
	if (isCollapsed()) {
		bar.style.display  = 'none';
		bar.style.transform = 'translateY(-100%)';
		bar.style.opacity   = '0';
		pill.style.display = 'flex';
		document.body.classList.add('opti-stats-bar-collapsed');
	} else {
		scheduleResponsiveLayout();
	}

	// Bind toggle button.
	var toggleBtn = bar.querySelector('.opti-stats-bar__toggle');
	if (toggleBtn) {
		toggleBtn.addEventListener('click', function (e) {
			e.preventDefault();
			collapse();
		});
	}

	pill.addEventListener('click', function (e) {
		e.preventDefault();
		expand();
	});

	/* ------------------------------------------------------------------
	   AJAX: Load stats asynchronously
	   ------------------------------------------------------------------ */
	function setLoading(on) {
		var values = bar.querySelectorAll('.opti-stats-bar__value');
		for (var i = 0; i < values.length; i++) {
			if (on) {
				values[i].setAttribute('data-loading', 'true');
				values[i].textContent = '';
			} else {
				values[i].removeAttribute('data-loading');
			}
		}
		scheduleResponsiveLayout();
	}

	/**
	 * Resolve a dotted key like "pro.recordings" against a data object.
	 */
	function resolveKey(obj, key) {
		var parts = key.split('.');
		var val = obj;
		for (var i = 0; i < parts.length; i++) {
			if (val === undefined || val === null) return '—';
			val = val[parts[i]];
		}
		return (val !== undefined && val !== null) ? val : '—';
	}

	function populateStats(data) {
		var values = bar.querySelectorAll('.opti-stats-bar__value');
		for (var i = 0; i < values.length; i++) {
			var key = values[i].getAttribute('data-key');
			if (key) {
				var val = resolveKey(data, key);
				values[i].textContent = (typeof val === 'number') ? val.toLocaleString() : val;
			}
		}
		updateHeatmapsLinks(data && data.page_id ? parseInt(data.page_id, 10) : 0);
		scheduleResponsiveLayout();
	}

	function loadStats() {
		setLoading(true);

		var xhr = new XMLHttpRequest();
		xhr.open('POST', config.ajax_url, true);
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		xhr.onreadystatechange = function () {
			if (xhr.readyState !== 4) return;

			setLoading(false);

			if (xhr.status === 200) {
				try {
					var resp = JSON.parse(xhr.responseText);
					if (resp.success && resp.data) {
						populateStats(resp.data);
					}
				} catch (e) {
					// JSON parse failed — leave placeholders.
				}
			}
		};

		xhr.send(
			'action=opti_behavior_frontend_stats&nonce=' + encodeURIComponent(config.nonce) +
			'&page_url=' + encodeURIComponent(window.location.href)
		);
	}

	/* ------------------------------------------------------------------
	   Boot
	   ------------------------------------------------------------------ */
	updateHeatmapsLinks();
	updateRecordingsLinks();
	initIcons();
	scheduleResponsiveLayout();
	window.addEventListener('resize', scheduleResponsiveLayout);
	window.addEventListener('orientationchange', scheduleResponsiveLayout);

	if (document.fonts && typeof document.fonts.ready === 'object') {
		document.fonts.ready.then(scheduleResponsiveLayout).catch(function () {});
	}

	loadStats();

})();
