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

	// -------------------------------------------------------------------------
	// Checkout: payment sub-method selector
	// Show/hide the UPI destination block and per-gateway hint blocks.
	// -------------------------------------------------------------------------
	$( document ).on( 'change', '[name="wcp_payment_method"]', function () {
		var method = $( this ).val();

		// Highlight selected label.
		$( '.wcp-pm-option' ).removeClass( 'wcp-pm-active' );
		$( this ).closest( '.wcp-pm-option' ).addClass( 'wcp-pm-active' );

		// Show the UPI VPA block only when UPI is selected.
		var $upiBlock = $( '.wcp-checkout-vpa[data-for-method="upi"]' );
		if ( method === 'upi' ) {
			$upiBlock.show();
		} else {
			$upiBlock.hide();
		}

		// Show / hide per-gateway detail panels.
		$( '.wcp-pm-detail[data-for-method]' ).each( function () {
			if ( $( this ).data( 'for-method' ) === method ) {
				$( this ).show();
			} else {
				$( this ).hide();
			}
		} );
	} );

	// -------------------------------------------------------------------------
	// Balance page: payment sub-method selector
	// -------------------------------------------------------------------------
	$( document ).on( 'change', '[name="wcp_balance_method"]', function () {
		var method = $( this ).val();

		$( '.wcp-pm-option' ).removeClass( 'wcp-pm-active' );
		$( this ).closest( '.wcp-pm-option' ).addClass( 'wcp-pm-active' );

		// Toggle sections.
		if ( method === 'upi' ) {
			$( '.wcp-balance-section-upi' ).show();
			$( '.wcp-balance-section-api' ).hide();
		} else {
			$( '.wcp-balance-section-upi' ).hide();
			$( '.wcp-balance-section-api' ).hide();
			$( '.wcp-balance-section-api[data-gateway="' + method + '"]' ).show();
		}
	} );

	// -------------------------------------------------------------------------
	// Balance page: "Pay via [Gateway]" button — creates a payment link via AJAX
	// -------------------------------------------------------------------------
	$( document ).on( 'click', '.wcp-api-pay-btn', function () {
		var $btn     = $( this );
		var gateway  = $btn.data( 'gateway' );
		var orderId  = $btn.data( 'order' );
		var nonce    = $btn.data( 'nonce' );
		var $msg     = $( '#wcp-api-msg-' + gateway );

		$btn.prop( 'disabled', true ).text( 'Please wait…' );
		$msg.text( '' ).removeClass( 'wcp-error' );

		$.post(
			wcpData.ajaxUrl,
			{
				action:   'wcp_create_balance_link',
				nonce:    nonce,
				gateway:  gateway,
				order_id: orderId,
			},
			function ( response ) {
				if ( response.success && response.data.redirect_url ) {
					window.location.href = response.data.redirect_url;
				} else {
					var msg = ( response.data && response.data.message )
						? response.data.message
						: 'Something went wrong. Please try again.';
					$msg.text( msg ).addClass( 'wcp-error' );
					$btn.prop( 'disabled', false ).text(
						$btn.data( 'original-label' ) || 'Pay Balance'
					);
				}
			}
		).fail( function () {
			$msg.text( 'Network error. Please try again.' ).addClass( 'wcp-error' );
			$btn.prop( 'disabled', false );
		} );
	} );

	// Store original button labels before any click changes them.
	$( '.wcp-api-pay-btn' ).each( function () {
		$( this ).data( 'original-label', $( this ).text().trim() );
	} );

	// -------------------------------------------------------------------------
	// UPI Pay button — reads URL from data-upi-url to bypass WordPress esc_url
	// filtering which strips the upi:// scheme.
	// -------------------------------------------------------------------------
	$( document ).on( 'click', '#wcp-mobile-pay-btn', function () {
		var upiUrl = $( this ).data( 'upi-url' );
		if ( ! upiUrl ) {
			return;
		}

		window.location.href = upiUrl;

		// After 3 seconds assume the user has paid and returned.
		setTimeout( function () {
			var $notice = $( '#wcp-return-notice' );
			var $form   = $( '#wcp-confirmation-form' );
			if ( $notice.length ) {
				$notice.show();
			}
			if ( $form.length ) {
				$( 'html, body' ).animate( { scrollTop: $form.offset().top - 20 }, 500 );
			}
		}, 3000 );
	} );

	// -------------------------------------------------------------------------
	// Copy UPI ID button
	// -------------------------------------------------------------------------
	$( document ).on( 'click', '.wcp-copy-btn', function () {
		var $btn = $( this );
		var text = $btn.data( 'copy' );
		if ( ! text ) return;

		var original = $btn.text().trim();

		function onCopied() {
			$btn.text( '✓ Copied!' ).prop( 'disabled', true );
			setTimeout( function () {
				$btn.text( original ).prop( 'disabled', false );
			}, 2000 );
		}

		if ( navigator.clipboard && navigator.clipboard.writeText ) {
			navigator.clipboard.writeText( text ).then( onCopied ).catch( function () {
				fallbackCopy( text, onCopied );
			} );
		} else {
			fallbackCopy( text, onCopied );
		}
	} );

	function fallbackCopy( text, cb ) {
		var el = document.createElement( 'textarea' );
		el.value = text;
		el.setAttribute( 'readonly', '' );
		el.style.cssText = 'position:fixed;top:-9999px;left:-9999px;';
		document.body.appendChild( el );
		el.select();
		try {
			document.execCommand( 'copy' );
			if ( cb ) cb();
		} catch ( e ) {
			// Copy failed silently.
		}
		document.body.removeChild( el );
	}

	// -------------------------------------------------------------------------
	// Payment / Balance UPI submission form
	// -------------------------------------------------------------------------
	$( '#wcp-submit-form' ).on( 'submit', function ( e ) {
		e.preventDefault();

		var $form  = $( this );
		var $btn   = $( '#wcp-submit-btn' );
		var $msg   = $( '#wcp-form-message' );
		var action = ( wcpData && wcpData.action ) ? wcpData.action : 'wcp_submit_transaction';

		$btn.prop( 'disabled', true ).text( 'Submitting…' );
		$msg.hide().removeClass( 'wcp-message-error wcp-message-success' );

		var fd = new FormData( this );
		fd.append( 'action',   action );
		fd.append( 'nonce',    wcpData.nonce );
		fd.append( 'order_id', wcpData.orderId );

		$.ajax( {
			url:         wcpData.ajaxUrl,
			type:        'POST',
			data:        fd,
			processData: false,
			contentType: false,
			success: function ( response ) {
				if ( response.success ) {
					$form.closest( '.wcp-confirmation-section' ).slideUp( 300 );
					$( '#wcp-success-state' ).show();
					$( 'html, body' ).animate( { scrollTop: $( '#wcp-success-state' ).offset().top - 20 }, 400 );
					if ( response.data && response.data.redirect ) {
						setTimeout( function () {
							window.location.href = response.data.redirect;
						}, 2800 );
					}
				} else {
					var msg = ( response.data && response.data.message )
						? response.data.message
						: 'An error occurred. Please try again.';
					$msg.text( msg ).addClass( 'wcp-message-error' ).show();
					$btn.prop( 'disabled', false ).text( 'Submit Payment Details' );
				}
			},
			error: function () {
				$msg.text( 'Network error. Please check your connection and try again.' )
					.addClass( 'wcp-message-error' ).show();
				$btn.prop( 'disabled', false ).text( 'Submit Payment Details' );
			}
		} );
	} );

	// -------------------------------------------------------------------------
	// Screenshot preview
	// -------------------------------------------------------------------------
	$( '#wcp-screenshot' ).on( 'change', function () {
		var file = this.files[ 0 ];
		if ( ! file ) return;

		var reader = new FileReader();
		reader.onload = function ( ev ) {
			var $prev = $( '#wcp-screenshot-preview' );
			if ( $prev.length === 0 ) {
				$prev = $( '<img id="wcp-screenshot-preview" class="wcp-screenshot-preview" alt="Preview">' );
				$( '#wcp-screenshot' ).after( $prev );
			}
			$prev.attr( 'src', ev.target.result );
		};
		reader.readAsDataURL( file );
	} );

} )( jQuery );
