jQuery( function ( $ ) {
	
	// Utility to lock a field if it exists
	const lockField = ( $el ) => {
		if ( $el.length && !$el.data( 'wpo-locked' ) ) {
			const val  = $el.val();
			const name = $el.attr( 'name' );

			$el.prop( 'disabled', true ).data( 'wpo-locked', true );

			$( '<input>', {
				type : 'hidden',
				name : name,
				value: val
			} ).insertAfter( $el );

			$el.after( '<p class="wpo-disabled">' + wcpdf_pro_cloud_storage_scripts.unlink_required_message + '</p>' );
		}
	};

	// Lock if already linked
	if ( parseInt( wcpdf_pro_cloud_storage_scripts.are_account_credentials_set, 10 ) === 1 ) {
		const $serviceField   = $( '#cloud_service' );
		const selectedService = $serviceField.val();

		lockField( $serviceField );

		// Lock the access type field based on selected service
		const $accessTypeField = $( '#' + selectedService + '_access_type' );
		lockField( $accessTypeField );

		// Lock destination folder (try to find the visible one)
		const $destinationFolderField = $( '#' + selectedService + '_access_type' )
			.closest( 'td' )
			.find( '#' + selectedService + '_destination_folder' )
			.first();

		lockField( $destinationFolderField );
	}

	// Show / hide service specific settings
	const $selectService = $( '#cloud_service' );

	function toggleServiceSettings() {
		const selected = $selectService.val();

		// Loop through all rows that have inputs with IDs
		$( 'tr' ).each( function() {
			const $row  = $( this );
			const input = $row.find( '[id]' ).first(); // Only check the first ID

			if ( input.length ) {
				const id = input.attr( 'id' );

				// If it starts with a known prefix, show/hide accordingly
				if ( id.startsWith( 'ftp_' ) || id.startsWith( 'dropbox_' ) || id.startsWith( 'gdrive_' ) ) {
					if ( id.startsWith( selected + '_' ) ) {
						$row.show();
					} else {
						$row.hide();
					}
				}
			}
		} );
	}

	$selectService.on( 'change', toggleServiceSettings );
	toggleServiceSettings(); // Run on page load
	
} );
