import jQuery from 'jquery';

( function ( $, window, document, wdceoAccount, navigator ) {
	'use strict';

	/**
	 * Handle copy to clipboard functionality
	 */
	function initCopyToClipboard() {
		$( document ).on( 'click', '.wc-copy-button', function ( e ) {
			e.preventDefault();

			const targetId = $( this ).data( 'target' );
			const input = $( targetId );
			const button = $( this );
			const originalText = button.text();

			if ( ! input.length ) {
				return;
			}

			const textToCopy = input.val();

			// Use modern Clipboard API
			if ( navigator.clipboard && window.isSecureContext ) {
				navigator.clipboard
					.writeText( textToCopy )
					.then( function () {
						showCopySuccess( button, originalText );
					} )
					.catch( function () {
						showCopyError( button, originalText );
					} );
			} else {
				fallbackCopy( input, button, originalText );
			}
		} );
	}

	/**
	 * Show copy success state
	 * @param button
	 * @param originalText
	 */
	function showCopySuccess( button, originalText ) {
		const message =
			( typeof wdceoAccount !== 'undefined' &&
				wdceoAccount.messages?.copied ) ||
			'Copied!';
		button.text( message );
		button.addClass( 'button-success' );

		setTimeout( function () {
			button.text( originalText );
			button.removeClass( 'button-success' );
		}, 2000 );
	}

	/**
	 * Fallback copy method for older browsers
	 * @param input
	 * @param button
	 * @param originalText
	 */
	function fallbackCopy( input, button, originalText ) {
		input.select();
		input[ 0 ].setSelectionRange( 0, 99999 );

		try {
			const successful = document.execCommand( 'copy' );
			if ( successful ) {
				showCopySuccess( button, originalText );
			} else {
				showCopyError( button, originalText );
			}
		} catch {
			showCopyError( button, originalText );
		}

		// Deselect
		if ( window.getSelection ) {
			input[ 0 ].ownerDocument.defaultView
				.getSelection()
				.removeAllRanges();
		}
	}

	/**
	 * Show copy error state
	 * @param button
	 * @param originalText
	 */
	function showCopyError( button, originalText ) {
		const message =
			( typeof wdceoAccount !== 'undefined' &&
				wdceoAccount.messages?.copy_failed ) ||
			'Failed';
		button.text( message );
		button.addClass( 'button-error' );
		setTimeout( function () {
			button.text( originalText );
			button.removeClass( 'button-error' );
		}, 2000 );
	}

	/**
	 * Handle confirmation dialogs
	 */
	function initConfirmActions() {
		$( document ).on( 'click', '.disconnect-google-drive', function ( e ) {
			const confirmMessage =
				( typeof wdceoAccount !== 'undefined' &&
					wdceoAccount.messages?.disconnect_confirm ) ||
				'Are you sure?';

			if ( ! window.confirm( confirmMessage ) ) {
				e.preventDefault();
				return false;
			}
		} );
	}

	/**
	 * Initialize when DOM is ready
	 */
	$( function () {
		initCopyToClipboard();
		initConfirmActions();
	} );
} )( jQuery, window, document, window.wdceoAccount, window.navigator );
