/**
 * Public Qualified Leads viewer — filter tabs + mark-handled toggle.
 *
 * No-login surface: auth is the leads token already in the page URL. The toggle
 * POSTs back to the same URL (SiteStaffr_Leads::maybe_render_leads_page handles
 * `sitestaffr_action=toggle_handled` and returns JSON). Optimistic UI with
 * revert on failure. Vanilla JS, no dependencies.
 */
( function () {
	'use strict';

	var table = document.querySelector( '.sitestaffr-leads-table' );
	var tabs = Array.prototype.slice.call( document.querySelectorAll( '.sitestaffr-leads-filter-tab' ) );
	var emptyMsg = document.querySelector( '.sitestaffr-leads-empty-filter' );
	if ( ! table ) {
		return;
	}

	var currentFilter = 'all';

	function rows() {
		return Array.prototype.slice.call( table.querySelectorAll( 'tbody tr[data-lead-id]' ) );
	}

	function rowMatches( row, filter ) {
		var handled = row.getAttribute( 'data-handled' ) === '1';
		if ( 'handled' === filter ) {
			return handled;
		}
		if ( 'followup' === filter ) {
			return ! handled;
		}
		return true; // all
	}

	function applyFilter() {
		var visible = 0;
		rows().forEach( function ( row ) {
			var show = rowMatches( row, currentFilter );
			row.hidden = ! show;
			if ( show ) {
				visible++;
			}
		} );
		if ( emptyMsg ) {
			emptyMsg.hidden = visible !== 0;
		}
	}

	function updateCounts() {
		var all = rows();
		var handled = all.filter( function ( r ) {
			return r.getAttribute( 'data-handled' ) === '1';
		} ).length;
		var counts = { all: all.length, handled: handled, followup: all.length - handled };
		tabs.forEach( function ( tab ) {
			var el = tab.querySelector( '.sitestaffr-leads-filter-count' );
			var key = tab.getAttribute( 'data-filter' );
			if ( el && counts.hasOwnProperty( key ) ) {
				el.textContent = String( counts[ key ] );
			}
		} );
	}

	tabs.forEach( function ( tab ) {
		tab.addEventListener( 'click', function () {
			currentFilter = tab.getAttribute( 'data-filter' ) || 'all';
			tabs.forEach( function ( t ) {
				var active = t === tab;
				t.classList.toggle( 'is-active', active );
				t.setAttribute( 'aria-pressed', active ? 'true' : 'false' );
			} );
			applyFilter();
		} );
	} );

	function setRowHandled( row, handled ) {
		row.setAttribute( 'data-handled', handled ? '1' : '0' );
		var btn = row.querySelector( '.sitestaffr-leads-handled-btn' );
		if ( btn ) {
			btn.setAttribute( 'aria-pressed', handled ? 'true' : 'false' );
		}
	}

	table.addEventListener( 'click', function ( evt ) {
		var btn = evt.target.closest ? evt.target.closest( '.sitestaffr-leads-handled-btn' ) : null;
		if ( ! btn ) {
			return;
		}
		var row = btn.closest( 'tr[data-lead-id]' );
		if ( ! row || btn.disabled ) {
			return;
		}
		var leadId = row.getAttribute( 'data-lead-id' );
		var wasHandled = row.getAttribute( 'data-handled' ) === '1';
		var next = ! wasHandled;

		// Optimistic: flip immediately, then reconcile with the server.
		setRowHandled( row, next );
		updateCounts();
		applyFilter();
		btn.disabled = true;

		var body = new URLSearchParams();
		body.set( 'sitestaffr_action', 'toggle_handled' );
		body.set( 'call_id', leadId );
		body.set( 'handled', next ? '1' : '0' );

		fetch( window.location.href, {
			method: 'POST',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
			credentials: 'same-origin',
			body: body.toString()
		} )
			.then( function ( res ) {
				return res.json();
			} )
			.then( function ( data ) {
				if ( ! data || ! data.success ) {
					throw new Error( 'toggle failed' );
				}
			} )
			.catch( function () {
				// Revert on failure.
				setRowHandled( row, wasHandled );
				updateCounts();
				applyFilter();
			} )
			.then( function () {
				btn.disabled = false;
			} );
	} );
}() );
