/**
 * Heatmaps Page Scripts
 * Handles AJAX table rendering, sorting, pagination, and session counts
 * 
 * @package OptiBehavior
 */

(function(){
	// Perf debug: page load timing
	var optibehaviorPageStart = performance.now();
	window.addEventListener('load', function(){
		var secs = ((performance.now() - optibehaviorPageStart)/1000).toFixed(2);
		// console.log('[optibehavior] Heatmaps admin page load complete in ' + secs + 's');
	});
	function render(html){
		var panel = document.querySelector('.heatmaps-panel'); if(!panel) return;
		var container = panel.querySelector('[data-optibehavior-table-wrapper]');
		if(!container){ container = document.createElement('div'); container.setAttribute('data-optibehavior-table-wrapper',''); panel.appendChild(container); }
		container.innerHTML = html;
	// removed stray call; map is updated from updateRealtimeVisitors()
		var wrap = container.querySelector('[data-optibehavior-table]');
		var active = wrap && wrap.querySelector('thead a[data-sort][data-active="1"]');
		var orderby = active ? active.getAttribute('data-sort') : 'last_updated';
		var order = active ? (active.getAttribute('data-current') || 'desc') : 'desc';
		if(wrap){ wrap.dataset.orderby = orderby; wrap.dataset.order = order; }
		var oldShell = document.querySelector('.simplified-heatmap-table'); if(oldShell){ oldShell.style.display='none'; }
		// Initialize Lucide icons after rendering
		if(typeof lucide !== 'undefined'){ lucide.createIcons(); }
	}
	function loading(on){ let w = document.querySelector('.heatmaps-panel'); if(!w) return; w.classList.toggle('is-loading', !!on); }
	function fetchTable(params){
		loading(true);
		var t0 = performance.now();
		// console.time('[optibehavior] Heatmap table AJAX');
		var form = new FormData();
		form.append('action','optibehavior_heatmaps_table');
		form.append('nonce', (opti_behaviorData && opti_behaviorData.nonce) || '');
		var periodEl = document.getElementById('dashboard-period');
		var sEl = document.getElementById('start-date');
		var eEl = document.getElementById('end-date');
		var defaultPeriod = 'last30days';
		if(periodEl){ form.append('period', periodEl.value || defaultPeriod); } else { form.append('period', defaultPeriod); }
		if(sEl && eEl){ if((periodEl && periodEl.value==='custom') || (sEl.value && eEl.value)){ form.append('start_date', sEl.value || ''); form.append('end_date', eEl.value || ''); } }
		Object.keys(params).forEach(k=>form.append(k,params[k]));
		fetch(opti_behaviorData.ajaxUrl, {method:'POST', credentials:'same-origin', body:form})
		.then(function(r){ var t1 = performance.now(); /* console.log('[optibehavior] admin-ajax responded in ' + ((t1 - t0)/1000).toFixed(2) + 's'); */ return r.json(); })
		.then(function(resp){
			// console.log('[optibehavior] DEBUG: Full AJAX response:', resp);
			if(resp && resp.success){
				// console.log('[optibehavior] DEBUG: Response data:', resp.data);
				render(resp.data.html);
			} else {
				// console.warn('[optibehavior] Unexpected response', resp);
			}
		})
		.catch(function(err){ /* console.error('[optibehavior] AJAX error', err); */ })
		.finally(function(){ /* console.timeEnd('[optibehavior] Heatmap table AJAX'); */ var secs = ((performance.now() - t0)/1000).toFixed(2); /* console.log('[optibehavior] Heatmaps table render completed in ' + secs + 's'); */ loading(false); });
	}
	function getFrontendStatsDeepLink(){
		var params = new URLSearchParams(window.location.search);
		return {
			pageUrl: params.get('page_url') || '',
			dateRange: params.get('date_range') || ''
		};
	}
	function applyFrontendStatsDeepLink(){
		var deepLink = getFrontendStatsDeepLink();
		var searchInput = document.getElementById('heatmaps-search');
		var periodEl = document.getElementById('dashboard-period');

		if(deepLink.pageUrl && searchInput){
			searchInput.value = deepLink.pageUrl;
		}

		if(deepLink.dateRange && periodEl){
			for(var i = 0; i < periodEl.options.length; i++){
				if(periodEl.options[i].value === deepLink.dateRange){
					periodEl.value = deepLink.dateRange;
					break;
				}
			}
		}

		return deepLink;
	}
	document.addEventListener('DOMContentLoaded', function(){
		var deepLink = applyFrontendStatsDeepLink();
		fetchTable({orderby:'last_updated', order:'desc', paged:1, per_page:10, search:deepLink.pageUrl || ''});
	});
	document.addEventListener('click', function(e){ var a=e.target.closest('[data-optibehavior-table] thead a[data-sort]'); if(a){ e.preventDefault(); var wrap = a.closest('[data-optibehavior-table]'); var orderby = a.getAttribute('data-sort'); var nextOrder = a.getAttribute('data-order') || 'desc'; if(wrap){ wrap.dataset.orderby = orderby; wrap.dataset.order = nextOrder; } var searchInput = document.getElementById('heatmaps-search'); var search = searchInput ? searchInput.value.trim() : ''; fetchTable({orderby:orderby, order:nextOrder, paged:1, per_page:10, search:search}); }});
	document.addEventListener('click', function(e){ var p=e.target.closest('[data-paging] .pagination-btn'); if(!p||p.hasAttribute('disabled')) return; e.preventDefault(); var pag = e.target.closest('.table-pagination'); var cur = pag && pag.querySelector('.pagination-current'); var page = parseInt(cur && cur.textContent || '1',10); var totalPages = parseInt((pag && pag.getAttribute('data-total-pages'))||'1',10); if(p.hasAttribute('data-first')) page=1; else if(p.hasAttribute('data-prev')) page=Math.max(1,page-1); else if(p.hasAttribute('data-next')) page=Math.min(totalPages,page+1); else if(p.hasAttribute('data-last')) page=totalPages; else if(p.hasAttribute('data-page')) page=parseInt(p.getAttribute('data-page'),10); var orderby = pag ? (pag.getAttribute('data-orderby') || 'last_updated') : 'last_updated'; var order = pag ? (pag.getAttribute('data-order') || 'desc') : 'desc'; var searchInput = document.getElementById('heatmaps-search'); var search = searchInput ? searchInput.value.trim() : ''; fetchTable({orderby:orderby, order:order, paged:page, per_page:10, search:search}); });

	// Search handler with debounce
	var searchTimeout;
	document.addEventListener('input', function(e){
		if(e.target && e.target.id === 'heatmaps-search'){
			clearTimeout(searchTimeout);
			searchTimeout = setTimeout(function(){
				var searchTerm = e.target.value.trim();
				var wrap = document.querySelector('[data-optibehavior-table]');
				var orderby = wrap ? (wrap.dataset.orderby || 'last_updated') : 'last_updated';
				var order = wrap ? (wrap.dataset.order || 'desc') : 'desc';
				fetchTable({orderby:orderby, order:order, paged:1, per_page:10, search:searchTerm});
			}, 300);
		}
	});

	// Handle delete form confirmations
	document.addEventListener('submit', function(e){
		var form = e.target.closest('.optibehavior-delete-form');
		if(form){
			var msg = form.getAttribute('data-confirm');
			if(msg && !confirm(msg)){
				e.preventDefault();
			}
		}
	});
})();

