/* global donaticoAdmin, jQuery */
( function ( $, cfg ) {
	'use strict';

	// -------------------------------------------------------------------------
	// Form Designer — live preview via AJAX
	// -------------------------------------------------------------------------

	var $previewBtn  = $( '#donatico-preview-btn' );
	var $preview     = $( '#donatico-designer-preview' );
	var $layoutRadio = $( '.donatico-layout-radio' );
	var $amounts     = $( '#donatico-designer-amounts' );
	var $goal        = $( '#donatico-designer-goal' );

	/**
	 * Update the layout-option active CSS class to match the selected radio.
	 */
	function syncLayoutPicker() {
		$( '.donatico-layout-option' ).removeClass( 'donatico-layout-option--active' );
		$layoutRadio.filter( ':checked' ).closest( '.donatico-layout-option' )
			.addClass( 'donatico-layout-option--active' );
	}

	$layoutRadio.on( 'change', syncLayoutPicker );

	/**
	 * Fetch a fresh preview fragment from the server.
	 */
	function fetchPreview() {
		var layout  = $layoutRadio.filter( ':checked' ).val() || 'stacked';
		var amounts = $amounts.val() || '5,10,25,50,100';
		var goal    = parseInt( $goal.val(), 10 ) || 0;

		$previewBtn.prop( 'disabled', true ).text( cfg.i18n ? cfg.i18n.loading : 'Loading…' );

		$.post(
			cfg.ajaxUrl,
			{
				action : 'donatico_designer_preview',
				nonce  : cfg.nonce,
				layout : layout,
				amounts: amounts,
				goal   : goal,
			},
			function ( response ) {
				if ( response.success ) {
					$preview.html( response.data.html );
				}
			}
		).always( function () {
			$previewBtn.prop( 'disabled', false ).text( cfg.i18n ? cfg.i18n.updatePreview : 'Update Preview' );
		} );
	}

	if ( $previewBtn.length ) {
		$previewBtn.on( 'click', fetchPreview );
		syncLayoutPicker();
	}

	// -------------------------------------------------------------------------
	// Settings page — copy-to-clipboard for API key fields
	// -------------------------------------------------------------------------

	$( '.donatico-key-field' ).each( function () {
		var $field = $( this );

		var $btn = $( '<button type="button" class="button button-small donatico-copy-btn">' )
			.text( cfg.i18n ? cfg.i18n.copy : 'Copy' )
			.css( { marginLeft: '6px', verticalAlign: 'middle' } );

		$field.after( $btn );

		$btn.on( 'click', function () {
			navigator.clipboard.writeText( $field.val() ).then( function () {
				$btn.text( cfg.i18n ? cfg.i18n.copied : 'Copied!' );
				setTimeout( function () {
					$btn.text( cfg.i18n ? cfg.i18n.copy : 'Copy' );
				}, 1800 );
			} );
		} );
	} );

	// -------------------------------------------------------------------------
	// Donations list — confirm row-action delete
	// -------------------------------------------------------------------------

	$( document ).on( 'click', '.donatico-delete-link', function ( e ) {
		var msg = cfg.i18n ? cfg.i18n.confirmDelete : 'Delete this donation? This cannot be undone.';
		if ( ! window.confirm( msg ) ) { // eslint-disable-line no-alert
			e.preventDefault();
		}
	} );

	// -------------------------------------------------------------------------
	// Settings — Stripe test connection
	// -------------------------------------------------------------------------

	var $testBtn    = $( '#donatico-test-connection' );
	var $testResult = $( '#donatico-connection-result' );

	if ( $testBtn.length ) {
		$testBtn.on( 'click', function () {
			var originalText = $testBtn.text();
			$testBtn.prop( 'disabled', true ).text( 'Testing…' );
			$testResult.text( '' ).css( 'color', '' );

			$.post(
				cfg.ajaxUrl,
				{
					action: 'donatico_test_stripe_connection',
					nonce:  cfg.nonce,
				},
				function ( response ) {
					if ( response.success ) {
						$testResult.text( '✅ ' + response.data.message ).css( 'color', '#059669' );
					} else {
						var msg = ( response.data && response.data.message ) ? response.data.message : 'Connection failed.';
						$testResult.text( '❌ ' + msg ).css( 'color', '#dc2626' );
					}
				}
			).fail( function () {
				$testResult.text( '❌ Request failed.' ).css( 'color', '#dc2626' );
			} ).always( function () {
				$testBtn.prop( 'disabled', false ).text( originalText );
			} );
		} );
	}

	// -------------------------------------------------------------------------
	// Settings — send test emails
	// -------------------------------------------------------------------------

	var $testEmailResult = $( '#donatico-test-email-result' );

	$( document ).on( 'click', '.donatico-send-test-email', function () {
		var $btn       = $( this );
		var type       = $btn.data( 'type' );
		var origText   = $btn.text();
		$btn.prop( 'disabled', true ).text( '…' );
		$testEmailResult.text( '' ).css( 'color', '' );

		$.post(
			cfg.ajaxUrl,
			{ action: 'donatico_send_test_email', nonce: cfg.nonce, type: type },
			function ( response ) {
				var msg = ( response.data && response.data.message ) ? response.data.message : '';
				if ( response.success ) {
					$testEmailResult.text( '✅ ' + msg ).css( 'color', '#059669' );
				} else {
					$testEmailResult.text( '❌ ' + msg ).css( 'color', '#dc2626' );
				}
			}
		).fail( function () {
			$testEmailResult.text( '❌ Request failed.' ).css( 'color', '#dc2626' );
		} ).always( function () {
			$btn.prop( 'disabled', false ).text( origText );
		} );
	} );

	// -------------------------------------------------------------------------
	// Settings — copy webhook URL button
	// -------------------------------------------------------------------------

	$( '.donatico-copy-webhook-url' ).on( 'click', function () {
		var url  = $( this ).data( 'clipboard-text' );
		var $btn = $( this );
		navigator.clipboard.writeText( url ).then( function () {
			$btn.text( '✓ Copied' );
			setTimeout( function () { $btn.text( 'Copy' ); }, 1800 );
		} );
	} );

} )( jQuery, typeof donaticoAdmin !== 'undefined' ? donaticoAdmin : {} );
