/* Tinyplugs Gift Wrapping for WooCommerce – Cart & Checkout — admin settings: show/hide fields by mode */
( function ( $ ) {
	'use strict';

	// Field groups (by setting id).
	var perItemOnly  = [ 'cgwfw_enable_product_page', 'cgwfw_fee_per', 'cgwfw_item_style', 'cgwfw_button_label', 'cgwfw_button_label_added', 'cgwfw_button_size' ];
	var perOrderOnly = [ 'cgwfw_order_style', 'cgwfw_order_label' ];
	var cardOnly     = [ 'cgwfw_order_subtitle', 'cgwfw_card_add_label', 'cgwfw_card_added_label' ];
	// Design-picker labels only matter once at least one wrap design exists.
	var designsOnly  = [ 'cgwfw_designs_label', 'cgwfw_designs_none_label' ];

	function rowOf( id ) {
		return $( '#' + id ).closest( 'tr' );
	}

	// Whether any wrap design rows are present (the JS template in a <script>
	// tag is not live DOM, so it is not counted).
	function hasDesignRows() {
		return $( '.cgwfw-designs-rows .cgwfw-design-row' ).length > 0;
	}

	function setRows( ids, show ) {
		$.each( ids, function ( _, id ) {
			rowOf( id ).toggle( show );
		} );
	}

	function refresh() {
		var mode  = $( '#cgwfw_mode' ).val();
		var style = $( '#cgwfw_order_style' ).val();

		if ( 'per_item' === mode ) {
			setRows( perItemOnly, true );
			setRows( perOrderOnly, false );
			setRows( cardOnly, false );

			// Product-page display style only when the product-page option is on.
			var ppOn = 'yes' === $( '#cgwfw_enable_product_page' ).val();
			rowOf( 'cgwfw_pp_style' ).toggle( ppOn );

			// The "wrapped" label applies to the cart per-item button styles, or
			// the product-page "Gift icon + text" style (the checkbox and switch
			// styles show no separate wrapped label). Button size is cart-only.
			var itemButtonStyle = 'switch' !== $( '#cgwfw_item_style' ).val();
			var ppIconStyle     = ppOn && 'icon' === $( '#cgwfw_pp_style' ).val();
			rowOf( 'cgwfw_button_label_added' ).toggle( itemButtonStyle || ppIconStyle );
			rowOf( 'cgwfw_button_size' ).toggle( itemButtonStyle );
		} else {
			setRows( perItemOnly, false );
			setRows( perOrderOnly, true );
			setRows( cardOnly, 'card' === style );
			rowOf( 'cgwfw_pp_style' ).hide();
		}

		// Designs repeater + label fields only when a "multiple designs" display
		// is selected. Labels additionally require at least one design row.
		var designsOn = 'flat' !== $( '#cgwfw_designs_display' ).val();
		$( '.cgwfw-designs-field-row' ).toggle( designsOn );
		setRows( designsOnly, designsOn && hasDesignRows() );

		// Fee tax class only matters when tax is charged on the fee.
		rowOf( 'cgwfw_tax_class' ).toggle( 'yes' === $( '#cgwfw_taxable' ).val() );

		// Message character limit only matters when gift messages are enabled.
		rowOf( 'cgwfw_message_limit' ).toggle( $( '#cgwfw_enable_message' ).is( ':checked' ) );

		// Tooltip text only matters when the tooltip is enabled.
		rowOf( 'cgwfw_tooltip_text' ).toggle( $( '#cgwfw_enable_tooltip' ).is( ':checked' ) );

		// Categories field only for the category-based targeting modes.
		rowOf( 'cgwfw_categories' ).toggle( 'all' !== $( '#cgwfw_targeting' ).val() );

		// Product exclusion list only when exclusions are enabled.
		rowOf( 'cgwfw_exclude_products' ).toggle( $( '#cgwfw_enable_product_exclusions' ).is( ':checked' ) );

		// "Included" fields only when the feature is enabled.
		var includedOn = $( '#cgwfw_enable_included' ).is( ':checked' );
		rowOf( 'cgwfw_included_categories' ).toggle( includedOn );
		rowOf( 'cgwfw_included_products' ).toggle( includedOn );
		rowOf( 'cgwfw_included_text' ).toggle( includedOn );

		// Inline warning: per-item mode on a block-based cart page.
		var usesBlock = 'undefined' !== typeof cgwfwAdmin && cgwfwAdmin.cartUsesBlock;
		var showBlockWarning = 'per_item' === mode && usesBlock;
		ensureBlockWarning().toggle( !! showBlockWarning );

		// Inline warning: product-page wrapping while the cart uses the block —
		// the wrap is still charged/saved, but not shown or editable in the block cart.
		var showProductWarning = 'per_item' === mode &&
			'yes' === $( '#cgwfw_enable_product_page' ).val() && usesBlock;
		ensureProductWarning().toggle( !! showProductWarning );
	}

	// Re-run the show/hide pass, but only on the settings tab (where the mode
	// field — and thus the field rows refresh() touches — is present).
	function maybeRefresh() {
		if ( $( '#cgwfw_mode' ).length ) {
			refresh();
		}
	}

	// Lazily build the inline warning element under the Wrapping mode field.
	var $blockWarning;
	function ensureBlockWarning() {
		if ( $blockWarning ) {
			return $blockWarning;
		}
		var text = ( 'undefined' !== typeof cgwfwAdmin && cgwfwAdmin.blockWarning ) ? cgwfwAdmin.blockWarning : '';
		$blockWarning = $( '<div class="notice notice-warning inline" style="margin:8px 0 0;padding:8px 12px;"></div>' )
			.append( $( '<p style="margin:0;"></p>' ).text( text ) )
			.hide();
		$( '#cgwfw_mode' ).closest( 'td' ).append( $blockWarning );
		return $blockWarning;
	}

	// Lazily build the inline warning under the product-page option.
	var $productWarning;
	function ensureProductWarning() {
		if ( $productWarning ) {
			return $productWarning;
		}
		var text = ( 'undefined' !== typeof cgwfwAdmin && cgwfwAdmin.productBlockWarning ) ? cgwfwAdmin.productBlockWarning : '';
		$productWarning = $( '<div class="notice notice-warning inline" style="margin:8px 0 0;padding:8px 12px;"></div>' )
			.append( $( '<p style="margin:0;"></p>' ).text( text ) )
			.hide();
		$( '#cgwfw_enable_product_page' ).closest( 'td' ).append( $productWarning );
		return $productWarning;
	}

	// --- Wrap designs repeater -------------------------------------------
	function initDesigns() {
		var $rows = $( '.cgwfw-designs-rows' );
		if ( ! $rows.length ) {
			return;
		}

		// Add a new row from the template, giving it a unique index.
		$( document ).on( 'click', '.cgwfw-add-design', function ( e ) {
			e.preventDefault();
			var tmpl = $( '#tmpl-cgwfw-design-row' ).html() || '';
			var html = tmpl.replace( /__INDEX__/g, 'new' + Date.now() );
			$rows.append( html );
			maybeRefresh();
		} );

		// Remove a row.
		$( document ).on( 'click', '.cgwfw-remove-design', function ( e ) {
			e.preventDefault();
			$( this ).closest( 'tr.cgwfw-design-row' ).remove();
			maybeRefresh();
		} );

		// Image picker (WordPress media library).
		$( document ).on( 'click', '.cgwfw-select-img', function ( e ) {
			e.preventDefault();
			var $cell = $( this ).closest( 'td' );
			var admin = ( 'undefined' !== typeof cgwfwAdmin ) ? cgwfwAdmin : {};
			var frame = wp.media( {
				title: admin.mediaTitle || 'Select wrap image',
				button: { text: admin.mediaButton || 'Use image' },
				multiple: false
			} );
			frame.on( 'select', function () {
				var att = frame.state().get( 'selection' ).first().toJSON();
				var url = ( att.sizes && att.sizes.thumbnail ) ? att.sizes.thumbnail.url : att.url;
				$cell.find( '.cgwfw-img-id' ).val( att.id );
				$cell.find( '.cgwfw-img-preview' ).css( 'background-image', "url('" + url + "')" );
			} );
			frame.open();
		} );
	}

	$( function () {
		initDesigns();

		if ( ! $( '#cgwfw_mode' ).length ) {
			return;
		}
		refresh();
		$( '#cgwfw_mode, #cgwfw_order_style, #cgwfw_item_style, #cgwfw_pp_style, #cgwfw_enable_message, #cgwfw_enable_tooltip, #cgwfw_targeting, #cgwfw_enable_product_exclusions, #cgwfw_taxable, #cgwfw_enable_product_page, #cgwfw_enable_included, #cgwfw_designs_display' ).on( 'change', refresh );
		// Re-evaluate when designs are added/removed (affects the label fields).
		$( document ).on( 'click', '.cgwfw-add-design, .cgwfw-remove-design', function () { setTimeout( refresh, 0 ); } );
	} );
} )( jQuery );
