/**
 * Biscotti CMP — Settings page (local admin script)
 *
 * Tab switching + per-tab save flows. Consent/Operator/Region persist through
 * the authenticated admin-ajax proxy (biscotti_proxy -> save-settings). Plugin
 * language, connection credentials and disconnect use local admin-ajax handlers.
 * All local, no remote code.
 *
 * @package Biscotti_CMP
 */
( function ( $ ) {
	'use strict';

	var cfg = window.biscottiAdmin || {};
	var i18n = cfg.i18n || {};
	function t( k, f ) { return i18n[ k ] || f; }

	function status( msg, isError ) {
		var el = document.getElementById( 'biscotti-settings-status' );
		if ( ! el ) { return; }
		el.textContent = msg;
		el.style.color = isError ? '#dc2626' : '#16a34a';
		if ( msg ) { setTimeout( function () { if ( el.textContent === msg ) { el.textContent = ''; } }, 4000 ); }
	}

	function v( id ) { var e = document.getElementById( id ); return e ? e.value : ''; }
	function ck( id ) { var e = document.getElementById( id ); return !! ( e && e.checked ); }

	// Persist a set of fields through the save-settings proxy.
	function saveSettings( payload, btn ) {
		var original = btn.textContent;
		btn.disabled = true;
		btn.textContent = t( 'saving', 'Saving…' );
		$.ajax( {
			url: cfg.ajaxUrl,
			method: 'POST',
			data: {
				action: 'biscotti_proxy',
				nonce: cfg.nonce,
				proxy_action: 'save-settings',
				payload: JSON.stringify( payload )
			}
		} )
			.done( function ( res ) {
				if ( res && res.success ) { status( '✅ ' + t( 'saved', 'Saved!' ), false ); }
				else { status( '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true ); }
			} )
			.fail( function () { status( '❌ ' + t( 'connectionError', 'Connection error' ), true ); } )
			.always( function () { btn.disabled = false; btn.textContent = original; } );
	}

	// Generic local admin-ajax POST helper.
	function ajaxPost( data, btn, onSuccess ) {
		var original = btn.textContent;
		btn.disabled = true;
		btn.textContent = t( 'saving', 'Saving…' );
		data.nonce = cfg.nonce;
		$.post( cfg.ajaxUrl, data )
			.done( function ( res ) {
				if ( res && ( res.success || res.data ) ) {
					status( '✅ ' + t( 'saved', 'Saved!' ), false );
					if ( onSuccess ) { onSuccess(); }
				} else {
					status( '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true );
				}
			} )
			.fail( function () { status( '❌ ' + t( 'connectionError', 'Connection error' ), true ); } )
			.always( function () { btn.disabled = false; btn.textContent = original; } );
	}

	$( function () {
		// --- Tabs ---
		$( '.biscotti-tab-btn' ).on( 'click', function () {
			var tab = $( this ).data( 'tab' );
			$( '.biscotti-tab-btn' ).removeClass( 'nav-tab-active' );
			$( this ).addClass( 'nav-tab-active' );
			$( '.biscotti-tab-panel' ).hide();
			$( '.biscotti-tab-panel[data-tab="' + tab + '"]' ).show();
		} );

		// --- Connection: edit / cancel / save credentials ---
		$( '#biscotti-edit-conn' ).on( 'click', function () { $( '#biscotti-conn-edit' ).show(); } );
		$( '#biscotti-cancel-conn' ).on( 'click', function () { $( '#biscotti-conn-edit' ).hide(); } );
		$( '#biscotti-save-conn' ).on( 'click', function () {
			var id = v( 'biscotti-new-website-id' ).trim();
			var key = v( 'biscotti-new-api-key' ).trim();
			if ( ! id || ! key ) { status( '❌ ' + t( 'fillBothFields', 'Please fill in both fields.' ), true ); return; }
			ajaxPost( { action: 'biscotti_save_credentials', website_id: id, api_key: key }, this, function () {
				setTimeout( function () { window.location.reload(); }, 1200 );
			} );
		} );

		// --- Disconnect ---
		$( '#biscotti-disconnect' ).on( 'click', function () {
			if ( ! window.confirm( t( 'disconnectConfirm', 'Disconnect this site from Biscotti?' ) ) ) { return; }
			ajaxPost( { action: 'biscotti_disconnect' }, this, function () {
				setTimeout( function () { window.location.reload(); }, 1200 );
			} );
		} );

		// --- Consent features ---
		$( '#biscotti-save-consent' ).on( 'click', function () {
			saveSettings( {
				tcfEnabled: ck( 'biscotti-field-tcfEnabled' ),
				geoIp: ck( 'biscotti-field-geoIp' ),
				emailNotifications: ck( 'biscotti-field-emailNotifications' ),
				ajaxBlocking: ck( 'biscotti-field-ajaxBlocking' ),
				debugMode: ck( 'biscotti-field-debugMode' ),
				consentRetention: parseInt( v( 'biscotti-field-consentRetention' ), 10 ) || 18
			}, this );
		} );

		// --- Operator ---
		$( '#biscotti-save-operator' ).on( 'click', function () {
			saveSettings( {
				operatorName: v( 'biscotti-field-operator_name' ).trim(),
				operatorAddress: v( 'biscotti-field-operator_address' ).trim(),
				operatorPrivacyUrl: v( 'biscotti-field-operator_privacy_url' ).trim()
			}, this );
		} );

		// --- Region ---
		$( '#biscotti-save-region' ).on( 'click', function () {
			saveSettings( { targetRegion: v( 'biscotti-field-target_region' ) }, this );
		} );

		// --- Plugin language (local option; reload to apply) ---
		$( '#biscotti-save-language' ).on( 'click', function () {
			ajaxPost( { action: 'biscotti_save_language', language: v( 'biscotti-field-plugin_language' ) }, this, function () {
				setTimeout( function () { window.location.reload(); }, 1200 );
			} );
		} );
	} );
} )( jQuery );
