/**
 * Biscotti CMP — White Label (local admin script)
 *
 * Persists branding (logo URL, brand colour, hide-powered-by, custom CSS) via
 * the save-branding proxy. On plans without white-label the proxy returns an
 * error which is shown to the user.
 *
 * @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 s = document.getElementById( 'bsc-wl-status' );
		if ( s ) { s.textContent = msg; s.style.color = isError ? '#dc2626' : '#16a34a'; }
	}

	$( function () {
		$( '#bsc-wl-save' ).on( 'click', function () {
			var $btn = $( this );
			$btn.prop( 'disabled', true );
			status( t( 'saving', 'Saving…' ) );
			$.ajax( {
				url: cfg.ajaxUrl,
				method: 'POST',
				data: {
					action: 'biscotti_proxy',
					nonce: cfg.nonce,
					proxy_action: 'save-branding',
					payload: JSON.stringify( {
						logoUrl: $( '#bsc-wl-logo' ).val().trim(),
						brandColor: $( '#bsc-wl-color' ).val(),
						hidePoweredBy: $( '#bsc-wl-hide-powered' ).is( ':checked' ),
						customCss: $( '#bsc-wl-css' ).val().trim()
					} )
				}
			} )
				.done( function ( res ) {
					$btn.prop( 'disabled', false );
					if ( res && res.success ) { status( '✅ ' + t( 'saved', 'Saved!' ) ); }
					else { status( '❌ ' + ( ( res && res.data ) || t( 'error', 'Error' ) ), true ); }
				} )
				.fail( function () { $btn.prop( 'disabled', false ); status( '❌ ' + t( 'connectionError', 'Connection error' ), true ); } );
		} );
	} );
} )( jQuery );
