/**
 * Biscotti CMP — Banner Designer (local admin script)
 *
 * Runs only on the Banner Designer admin page. All logic is local (no remote
 * code). Reads/writes banner data through the authenticated admin-ajax proxy
 * (biscotti_proxy -> save-banner) and mirrors a couple of flags into local WP
 * options (biscotti_save_settings) so class-banner.php can decide whether to
 * load the frontend script without depending on the API.
 *
 * @package Biscotti_CMP
 */
( function ( $ ) {
	'use strict';

	var cfg = window.biscottiAdmin || {};
	var i18n = cfg.i18n || {};

	function t( key, fallback ) {
		return i18n[ key ] || fallback;
	}

	function val( id ) {
		var el = document.getElementById( 'biscotti-field-' + id );
		return el ? el.value : '';
	}

	function checked( id ) {
		var el = document.getElementById( 'biscotti-field-' + id );
		return !! ( el && el.checked );
	}

	// ----------------------------------------------------------------------
	// Live preview
	// ----------------------------------------------------------------------
	function buildPreview() {
		var box = document.getElementById( 'biscotti-banner-preview' );
		if ( ! box ) {
			return;
		}

		var primary = val( 'banner_primary_color' ) || '#9B6B3C';
		var bg = val( 'banner_bg_color' ) || '#FFFFFF';
		var fg = val( 'banner_text_color' ) || '#333333';
		var style = val( 'banner_button_style' );
		var fontFamily = val( 'banner_font_family' );
		var fontSize = val( 'banner_font_size' );
		var ethical = checked( 'banner_ethical_ui' );
		var tcf = checked( 'banner_tcf_enabled' );

		var radius = style === 'pill' ? '999px' : ( style === 'square' ? '0' : '8px' );

		var title = val( 'banner_title' ) || t( 'previewTitle', 'We value your privacy' );
		var text = val( 'banner_text' ) || t( 'previewText', 'We use cookies to improve your experience.' );
		var accept = val( 'banner_accept' ) || t( 'previewAccept', 'Accept All' );
		var reject = val( 'banner_reject' ) || t( 'previewReject', 'Reject All' );
		var settings = val( 'banner_settings' ) || t( 'previewSettings', 'Settings' );

		// Reject button: equal weight in ethical mode, outline otherwise.
		var acceptBtn = '<button type="button" style="background:' + primary + ';color:#fff;border:none;border-radius:' + radius + ';padding:8px 16px;font-weight:600;cursor:default;">' + escapeHtml( accept ) + '</button>';
		var rejectStyle = ethical
			? 'background:' + primary + ';color:#fff;border:none;'
			: 'background:transparent;color:' + primary + ';border:1.5px solid ' + primary + ';';
		var rejectBtn = '<button type="button" style="' + rejectStyle + 'border-radius:' + radius + ';padding:8px 16px;font-weight:600;cursor:default;">' + escapeHtml( reject ) + '</button>';
		var settingsBtn = '<button type="button" style="background:transparent;color:' + fg + ';border:none;text-decoration:underline;padding:8px 12px;cursor:default;">' + escapeHtml( settings ) + '</button>';

		var fontCss = '';
		if ( fontFamily ) {
			fontCss += 'font-family:' + fontFamily + ';';
		}
		if ( fontSize ) {
			fontCss += 'font-size:' + fontSize + 'px;';
		}

		if ( tcf ) {
			// TCF 2.3: forced modal, IAB purposes + full vendor list, equal-prominence
			// Accept/Reject, and a "Manage options" entry. The admin preview shows a
			// faithful representation; the live banner renders the full IAB CMP UI and
			// uses the IAB-standard texts for the protected keys.
			var manage = t( 'previewManage', 'Manage options' );
			var manageBtn = '<button type="button" style="background:transparent;color:' + primary + ';border:1.5px solid ' + primary + ';border-radius:' + radius + ';padding:8px 16px;font-weight:600;cursor:default;">' + escapeHtml( manage ) + '</button>';
			// Under TCF, Reject must have equal prominence to Accept.
			var tcfRejectBtn = '<button type="button" style="background:' + primary + ';color:#fff;border:none;border-radius:' + radius + ';padding:8px 16px;font-weight:600;cursor:default;">' + escapeHtml( reject ) + '</button>';
			var notice = t( 'previewTcfNotice', 'TCF 2.3 active — visitors also see the IAB purposes and the full vendor list; Accept and Reject get equal prominence and certain texts follow the IAB standard.' );
			box.innerHTML =
				'<div style="background:rgba(15,23,42,.45);border-radius:10px;padding:24px;display:flex;justify-content:center;">' +
				'<div style="background:' + bg + ';color:' + fg + ';border:1px solid #e2e8f0;border-radius:10px;padding:20px;max-width:480px;width:100%;' + fontCss + '">' +
				'<div style="display:inline-block;font-size:10px;font-weight:700;letter-spacing:.04em;color:#fff;background:' + primary + ';border-radius:4px;padding:2px 8px;margin-bottom:10px;">IAB TCF 2.3</div>' +
				'<div style="font-weight:700;font-size:16px;margin-bottom:6px;">' + escapeHtml( title ) + '</div>' +
				'<div style="font-size:13px;margin-bottom:10px;opacity:.9;">' + escapeHtml( text ) + '</div>' +
				'<div style="font-size:12px;margin-bottom:14px;opacity:.75;border-left:3px solid ' + primary + ';padding-left:8px;">' + escapeHtml( notice ) + '</div>' +
				'<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">' + acceptBtn + tcfRejectBtn + manageBtn + '</div>' +
				'</div>' +
				'</div>';
		} else {
			box.innerHTML =
				'<div style="background:' + bg + ';color:' + fg + ';border:1px solid #e2e8f0;border-radius:10px;padding:18px;max-width:520px;' + fontCss + '">' +
				'<div style="font-weight:700;font-size:16px;margin-bottom:6px;">' + escapeHtml( title ) + '</div>' +
				'<div style="font-size:13px;margin-bottom:14px;opacity:.9;">' + escapeHtml( text ) + '</div>' +
				'<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">' + acceptBtn + rejectBtn + settingsBtn + '</div>' +
				'</div>';
		}
	}

	function escapeHtml( str ) {
		return String( str )
			.replace( /&/g, '&amp;' )
			.replace( /</g, '&lt;' )
			.replace( />/g, '&gt;' )
			.replace( /"/g, '&quot;' );
	}

	// ----------------------------------------------------------------------
	// Save
	// ----------------------------------------------------------------------
	function collectPayload() {
		var bannerId = val( 'banner_id' );
		var form = document.getElementById( 'biscotti-banner-form' );
		var lang = ( form && form.getAttribute( 'data-lang' ) ) || 'de';
		var localized = !! ( form && form.getAttribute( 'data-texts-localized' ) === '1' );

		var textFields = {
			title: val( 'banner_title' ),
			text: val( 'banner_text' ),
			accept: val( 'banner_accept' ),
			reject: val( 'banner_reject' ),
			settings: val( 'banner_settings' ),
			privacyLink: val( 'banner_privacy_link' )
		};

		// Preserve the stored shape: localized banners keep texts nested under the
		// active language (the API merges shallowly, so other languages survive);
		// flat banners stay flat. Prevents shadow top-level keys that the reader ignores.
		var texts = localized ? ( function () { var o = {}; o[ lang ] = textFields; return o; } )() : textFields;

		return {
			bannerId: bannerId || undefined,
			type: val( 'banner_type' ) || 'OPT_IN',
			isActive: checked( 'banner_active' ),
			consentDuration: parseInt( val( 'banner_consent_duration' ), 10 ) || 180,
			forceConsent: checked( 'banner_force_consent' ),
			theme: {
				position: val( 'banner_position' ),
				layout: val( 'banner_layout' ),
				primaryColor: val( 'banner_primary_color' ),
				backgroundColor: val( 'banner_bg_color' ),
				textColor: val( 'banner_text_color' ),
				buttonStyle: val( 'banner_button_style' ),
				fontFamily: val( 'banner_font_family' ) || null,
				fontSize: val( 'banner_font_size' ) || null,
				showLogo: checked( 'banner_show_logo' ),
				showFloatingButton: checked( 'banner_floating_button' ),
				showGranularView: checked( 'banner_granular_view' ),
				ethicalUiMode: checked( 'banner_ethical_ui' ),
				customCss: val( 'banner_custom_css' ) || ''
			},
			texts: texts
		};
	}

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

	function saveBanner() {
		var $btn = $( '#biscotti-save-banner' );
		var original = $btn.text();
		var payload = collectPayload();

		$btn.prop( 'disabled', true ).text( t( 'saving', 'Saving…' ) );
		setStatus( '', false );

		$.ajax( {
			url: cfg.ajaxUrl,
			method: 'POST',
			data: {
				action: 'biscotti_proxy',
				nonce: cfg.nonce,
				proxy_action: 'save-banner',
				payload: JSON.stringify( payload )
			}
		} )
			.done( function ( res ) {
				if ( res && res.success ) {
					setStatus( '✅ ' + t( 'saved', 'Saved!' ), false );
					// Mirror flags into local WP options so the frontend loader
					// knows whether to enqueue the banner script.
					$.post( cfg.ajaxUrl, {
						action: 'biscotti_save_settings',
						nonce: cfg.nonce,
						banner_enabled: payload.isActive ? '1' : '0',
						show_floating_button: payload.theme.showFloatingButton ? '1' : '0',
						tcf_enabled: checked( 'banner_tcf_enabled' ) ? '1' : '0'
					} );
					// Persist the website-level TCF flag to the cloud. TCF is per-website
					// (not per-banner) and the live engine reads tcfEnabled from the
					// server API, so this is the source of truth the banner honors.
					$.post( cfg.ajaxUrl, {
						action: 'biscotti_proxy',
						nonce: cfg.nonce,
						proxy_action: 'save-settings',
						payload: JSON.stringify( { tcfEnabled: checked( 'banner_tcf_enabled' ) } )
					} );
				} else {
					var m = ( res && res.data ) ? res.data : t( 'error', 'Error' );
					setStatus( '❌ ' + m, true );
				}
			} )
			.fail( function () {
				setStatus( '❌ ' + t( 'connectionError', 'Connection error' ), true );
			} )
			.always( function () {
				$btn.prop( 'disabled', false ).text( original );
			} );
	}

	// ----------------------------------------------------------------------
	// Init
	// ----------------------------------------------------------------------
	$( function () {
		// WordPress native color picker (local asset, enqueued by class-admin).
		if ( $.fn.wpColorPicker ) {
			$( '.biscotti-color-picker' ).wpColorPicker( {
				change: function () {
					// wpColorPicker updates the input slightly after this fires.
					setTimeout( buildPreview, 50 );
				},
				clear: buildPreview
			} );
		}

		// Re-render preview on any field change.
		$( '#biscotti-banner-form' ).on( 'input change', 'input, select, textarea', buildPreview );

		$( '#biscotti-save-banner' ).on( 'click', saveBanner );

		buildPreview();
	} );
} )( jQuery );
