window.W2PShopProduct = new function () {
	this.get_add_to_cart_button = function () {
		return jQuery( '#w2pshop_product' ).closest('form').find( 'button[type="submit"], button.single_add_to_cart_button' ).first();
	}

	this.get_quantity_input_field = function() {
		return jQuery('form.cart input[name="quantity"]');
	}

	this.get_product_data_element = function () {
		return jQuery( '#w2pshop_product' );
	}

	this.get_design_now_button = function () {
		return jQuery( '.w2pshop-design-now-btn' );
	}

	this.add_design_now_button = function (label) {
		label = label || 'Design Now';
		this.get_add_to_cart_button().before(
			jQuery( '<button type="button" class="w2pshop-design-now-btn" style="margin-bottom: 5px;">' + label + '</button>' )
		);
		// Hide Add to Cart if bypass is not explicitly enabled
		if (typeof window.W2PShopProductPageData !== 'undefined' && window.W2PShopProductPageData.bypass_design_upload !== 'yes') {
			this.get_add_to_cart_button().hide();
		}
	}

	this.get_product_data = function (key) {
		let w2pshop_product_data = JSON.parse( this.get_product_data_element().attr( 'value' ) );
		if (typeof key !== 'undefined' && Array.isArray(w2pshop_product_data)) {
			let filtered_dat = w2pshop_product_data.filter( d => d.key === key );
			if (filtered_dat.length > 0) {
				return filtered_dat[0].value;
			} else {
				return null;
			}
		} else if (w2pshop_product_data === '[]') {
			return null;
		}
		return w2pshop_product_data;
	}

	this.set_product_data = function (key, value) {
		let w2pshop_product_data = JSON.parse( this.get_product_data_element().attr( 'value' ) );
		if (w2pshop_product_data === '[]')
		{
			w2pshop_product_data = [];
		}
		if (Array.isArray(w2pshop_product_data) && w2pshop_product_data.filter( d => d.key === key ).length > 0) {
			let w2pshop_product_data_item      = w2pshop_product_data.filter( d => d.key === key );
			w2pshop_product_data_item[0].value = value;
		} else {
			w2pshop_product_data.push( {key: key, value: value} );
		}
		this.get_product_data_element().val( JSON.stringify( w2pshop_product_data ) );
		return w2pshop_product_data;
	}

	this.add_cart_item_key_to_form = function (cart_item_key) {
		let currentURL  = new URL( window.location.href );
		let urlParams   = new URLSearchParams( currentURL.search );
		let cartItemKey = urlParams.get( 'cart_item_key' );

		if (cartItemKey !== null && typeof jQuery !== 'undefined') {
			let form       = jQuery( this.get_add_to_cart_button().parent( 'form' ) );
			let formAction = form.attr( 'action' ) || "";  // Fallback to an empty string if no action
			let formURL    = new URL( formAction, window.location.href );  // Use the current URL as a base
			let formParams = new URLSearchParams( formURL.search );
			formParams.set( 'cart_item_key', cartItemKey );  // Use set() to ensure we don't have duplicates
			formURL.search = formParams;
			form.attr( 'action', formURL.toString() );
		}
	}
};