/**
 * Admin toggle helpers for the plugin settings screens.
 *
 * Handles the "show all post fields" toggle on the CPT schema tab and the
 * "show advanced" toggle on the post types index tab. Each block bails out
 * when its elements are not present on the current tab.
 *
 * localStorage access is wrapped in try/catch: it can be unavailable
 * (private mode, disabled storage) — the toggles still work, only the
 * persistence of the choice is lost.
 *
 * @package WLC\Algolia
 */

( function () {
	var key = 'wlc_algolia_cpt_show_fields';
	var checkbox = document.getElementById( 'wlc-cpt-show-fields' );
	var container = document.querySelector( '.wlc-cpt-fields' );
	if ( ! checkbox || ! container ) {
		return;
	}
	// Always default OFF (even if user toggled in the past).
	checkbox.checked = false;
	container.classList.remove( 'wlc-show-all' );
	try {
		if ( window.localStorage ) {
			localStorage.setItem( key, '0' );
		}
	} catch ( e ) {
		// localStorage unavailable — persistence intentionally skipped.
	}
	checkbox.addEventListener( 'change', function () {
		var isOn = !! checkbox.checked;
		// Force immediate hide/show on disabled rows to avoid "lingering" toggle visuals
		// caused by table layout overrides.
		var disabledRows = container.querySelectorAll( 'tr.wlc-cpt-row-disabled' );
		if ( isOn ) {
			disabledRows.forEach( function ( row ) {
				row.style.display = '';
			} );
			container.classList.add( 'wlc-show-all' );
		} else {
			disabledRows.forEach( function ( row ) {
				row.style.display = 'none';
			} );
			container.classList.remove( 'wlc-show-all' );
		}
		try {
			if ( window.localStorage ) {
				localStorage.setItem( key, isOn ? '1' : '0' );
			}
		} catch ( e ) {
			// localStorage unavailable — persistence intentionally skipped.
		}
	} );
} )();

( function () {
	var key = 'wlc_algolia_post_type_show_advanced';
	var checkbox = document.getElementById( 'wlc-posttype-show-advanced' );
	var form = document.querySelector( 'form.post_type_index' );
	if ( ! checkbox || ! form ) {
		return;
	}

	var saved = null;
	try {
		saved = window.localStorage ? localStorage.getItem( key ) : null;
	} catch ( e ) {
		// localStorage unavailable — persistence intentionally skipped.
	}
	var isOn = saved === '1';
	checkbox.checked = isOn;
	form.classList.toggle( 'wlc-posttype-advanced', isOn );

	checkbox.addEventListener( 'change', function () {
		var enabled = !! checkbox.checked;
		form.classList.toggle( 'wlc-posttype-advanced', enabled );
		try {
			if ( window.localStorage ) {
				localStorage.setItem( key, enabled ? '1' : '0' );
			}
		} catch ( e ) {
			// localStorage unavailable — persistence intentionally skipped.
		}
	} );
} )();
