/**
 * Biscotti CMP — Services / Provider Editor (local admin script)
 *
 * Loads merged provider data for a service (get-provider), lets the user edit
 * vendor/location/privacy/legal-basis/duration/category/description, save the
 * overrides (save-provider), reset to defaults (delete-provider) or pre-fill
 * with the website operator data (returned inline by get-provider). All writes
 * go through the authenticated admin-ajax proxy. 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; }

	var DESC_LANG = 'de';
	var operatorData = { operatorName: '', operatorAddress: '', operatorPrivacyUrl: '' };

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

	function proxy( proxyAction, payload ) {
		return $.ajax( {
			url: cfg.ajaxUrl,
			method: 'POST',
			data: {
				action: 'biscotti_proxy',
				nonce: cfg.nonce,
				proxy_action: proxyAction,
				payload: JSON.stringify( payload || {} )
			}
		} );
	}

	function val( id ) { var e = document.getElementById( id ); return e ? e.value.trim() : ''; }
	function setVal( id, v ) { var e = document.getElementById( id ); if ( e ) { e.value = v || ''; } }

	$( function () {
		var $modal = $( '#biscotti-svc-modal' );
		function open() { $modal.addClass( 'is-open' ); }
		function close() { $modal.removeClass( 'is-open' ); }

		// Open editor → load merged provider data.
		$( document ).on( 'click', '.biscotti-svc-edit', function () {
			var wsId = String( $( this ).data( 'wsId' ) );
			setStatus( '', false );
			document.getElementById( 'biscotti-svc-ws-id' ).value = wsId;
			open();
			proxy( 'get-provider', { websiteServiceId: wsId } )
				.done( function ( res ) {
					if ( ! ( res && res.success && res.data && res.data.provider ) ) {
						setStatus( '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true );
						return;
					}
					var p = res.data.provider;
					operatorData = p.operatorData || operatorData;
					setVal( 'biscotti-svc-vendor', p.vendor );
					setVal( 'biscotti-svc-location', p.vendorLocation );
					setVal( 'biscotti-svc-privacy', p.privacyPolicyUrl );
					setVal( 'biscotti-svc-legal', p.legalBasis );
					setVal( 'biscotti-svc-duration', p.storageDuration );
					setVal( 'biscotti-svc-category', p.category || '' );
					var desc = '';
					if ( p.description && typeof p.description === 'object' ) {
						desc = p.description[ DESC_LANG ] || p.description[ Object.keys( p.description )[ 0 ] ] || '';
					}
					setVal( 'biscotti-svc-desc', desc );
					// Hint for first-party / self-hosted that has not been edited.
					if ( p.providerType !== 'THIRD_PARTY' && ! p.isManuallyEdited ) {
						$( '#biscotti-svc-hint' ).show();
					} else {
						$( '#biscotti-svc-hint' ).hide();
					}
					$( '#biscotti-svc-reset' ).toggle( !! p.isManuallyEdited );
				} )
				.fail( function () { setStatus( '❌ ' + t( 'connectionError', 'Connection error' ), true ); } );
		} );

		// Close handlers.
		$( '#biscotti-svc-close' ).on( 'click', close );
		$modal.on( 'click', function ( e ) { if ( e.target === this ) { close(); } } );
		$( document ).on( 'keydown', function ( e ) { if ( e.key === 'Escape' ) { close(); } } );

		// Use operator data.
		$( '#biscotti-svc-use-operator' ).on( 'click', function () {
			setVal( 'biscotti-svc-vendor', operatorData.operatorName );
			setVal( 'biscotti-svc-location', operatorData.operatorAddress );
			setVal( 'biscotti-svc-privacy', operatorData.operatorPrivacyUrl );
		} );

		// Save provider overrides.
		$( '#biscotti-svc-save' ).on( 'click', function () {
			var $btn = $( this );
			var desc = val( 'biscotti-svc-desc' );
			var descObj = null;
			if ( desc ) { descObj = {}; descObj[ DESC_LANG ] = desc; }
			$btn.prop( 'disabled', true );
			setStatus( t( 'saving', 'Saving…' ), false );
			proxy( 'save-provider', {
				websiteServiceId: val( 'biscotti-svc-ws-id' ),
				overrideVendor: val( 'biscotti-svc-vendor' ) || null,
				overrideVendorLocation: val( 'biscotti-svc-location' ) || null,
				overridePrivacyPolicyUrl: val( 'biscotti-svc-privacy' ) || null,
				overrideLegalBasis: val( 'biscotti-svc-legal' ) || null,
				overrideStorageDuration: val( 'biscotti-svc-duration' ) || null,
				overrideCategory: val( 'biscotti-svc-category' ) || null,
				overrideDescription: descObj
			} )
				.done( function ( res ) {
					if ( res && res.success ) {
						setStatus( '✅ ' + t( 'saved', 'Saved!' ), false );
						setTimeout( function () { window.location.reload(); }, 1200 );
					} else {
						$btn.prop( 'disabled', false );
						setStatus( '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true );
					}
				} )
				.fail( function () { $btn.prop( 'disabled', false ); setStatus( '❌ ' + t( 'connectionError', 'Connection error' ), true ); } );
		} );

		// Reset overrides.
		$( '#biscotti-svc-reset' ).on( 'click', function () {
			if ( ! window.confirm( t( 'resetConfirm', 'Reset this provider to its detected defaults?' ) ) ) { return; }
			var $btn = $( this );
			$btn.prop( 'disabled', true );
			setStatus( t( 'saving', 'Saving…' ), false );
			proxy( 'delete-provider', { websiteServiceId: val( 'biscotti-svc-ws-id' ) } )
				.done( function ( res ) {
					if ( res && res.success ) {
						setStatus( '✅ ' + t( 'saved', 'Reset!' ), false );
						setTimeout( function () { window.location.reload(); }, 1200 );
					} else {
						$btn.prop( 'disabled', false );
						setStatus( '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true );
					}
				} )
				.fail( function () { $btn.prop( 'disabled', false ); setStatus( '❌ ' + t( 'connectionError', 'Connection error' ), true ); } );
		} );
	} );
} )( jQuery );
