(function () {
    const { __ } = window.wp.i18n || {};
    const { registerPlugin } = window.wp.plugins || {};
    const { ExperimentalDiscountsMeta } = window.wc.blocksCheckout || {};
    const apiUrl = ajax_object.ajax_url; // Localized via `wp_localize_script`

    if (!registerPlugin) {
        console.warn('registerPlugin is not available. Ensure WordPress dependencies are loaded properly.');
        return;
    }

    if (!ExperimentalDiscountsMeta) {
        console.warn('ExperimentalDiscountsMeta is not available. Ensure WooCommerce Blocks is active.');
        return;
    }

    // custom-coupon-blocks.js - Updated UI Handling
	async function applyGiftCard(giftCardCode, setMessage, setError, setGiftCardApplied) {
	    try {
	        const response = await fetch(apiUrl, {
	            method: 'POST',
	            headers: {
	                'Content-Type': 'application/x-www-form-urlencoded',
	            },
	            body: new URLSearchParams({
	                action: 'apply_gift_card',
	                giftCardCode: giftCardCode
	            })
	        });

	        if (!response.ok) {
	            throw new Error(`HTTP error! Status: ${response.status}`);
	        }
	        const result = await response.json();
	        
	        //console.log('data '+ result.data);
	        console.log('data ' + JSON.stringify(result.data));


	        if (result.success && result.data) {
	            const currencyParts = new Intl.NumberFormat("en-US", { 
				    style: 'currency', 
				    currency: result.data.gift_currency 
				}).formatToParts();

				const currencySymbol = currencyParts.find(part => part.type === 'currency')?.value.replace(/[A-Z]/g, '') || '';

				const subtotalCart = document.querySelector('.wp-block-woocommerce-checkout-order-summary-totals-block .wc-block-components-totals-item__value');
	            let subtotalValue = subtotalCart ? parseFloat(subtotalCart.textContent.replace(/[^0-9.-]+/g, '')) : 0;
	            let rawValue = result.data.gift_card_value.replace(/,/g, '');
				let discountValue = parseFloat(rawValue);
	            let updatedTotalValue = subtotalValue - discountValue;
	            
	            if (updatedTotalValue <= 0) {
	                setMessage(`Gift card value must be less than the total cart amount. A minimum ${currencySymbol}1 payment is required when applying gift cards. To fix this, add more items to your cart.`);
	                setError(true);
	                return;
	            }
	            
	            //setMessage(`${result.data.message} - ${currencySymbol}${result.data.gift_card_value} applied!`);
	            setMessage(`
				    <span><div id="gift-price">${currencySymbol}${result.data.gift_card_value} Gift card applied</div></span>
				    <div class="bottom-msg">${result.data.message}</div>
				`);
	            setError(false);
	            setGiftCardApplied(true);

	            let discountRow = document.querySelector('.gift-card-discount-row');
	            if (!discountRow) {
	                discountRow = createDiscountRow();
	            }

	            let discountValueElement = discountRow.querySelector('.discount-value');
	            if (!discountValueElement) {
	                discountValueElement = document.createElement('span');
	                discountValueElement.className = 'discount-value';
	                discountRow.appendChild(discountValueElement);
	            }
	            discountValueElement.textContent = `-${currencySymbol}${result.data.gift_card_value}`;

	            // Update the total amount after applying the gift card discount
	            const totalElement = document.querySelector('.wc-block-components-totals-footer-item .wc-block-components-totals-item__value');
	            const subtotalElement = document.querySelector('.wp-block-woocommerce-checkout-order-summary-totals-block .wc-block-components-totals-item__value');

	            let subtotal = subtotalElement ? parseFloat(subtotalElement.textContent.replace(/[^0-9.-]+/g, '')) : 0;
	            let rawdiscountValue = result.data.gift_card_value.replace(/,/g, '');


				let discount = parseFloat(rawdiscountValue);
                let updatedTotal = Math.max(0, subtotal - discount).toFixed(2); // Ensure total doesn't go negative

                console.log('discount:', discount);
	            console.log(updatedTotal); // This comes from the PHP response


	            if (totalElement) {
	                totalElement.textContent = `${currencySymbol}${updatedTotal}`;
	            }

	            const redeemGiftCardButton = document.querySelector('.gift-card-header');
	            if (redeemGiftCardButton) {
	                redeemGiftCardButton.style.display = 'none';
	            }

	            const minimumText = document.querySelector('.minimum-text');
			    const cartTotal = document.querySelector('.cart-total');

			    if (minimumText) minimumText.style.display = 'none';
			    if (cartTotal) cartTotal.style.display = 'none';

	        } else {
	            console.warn("Unexpected API Response Format:", result);
	            setMessage(result.data?.message || __('Invalid gift card', 'custom-coupon-plugin'));
	            setError(true);
	        }
	    } catch (error) {
	        setMessage(__('A network issue occurred. Please try again.', 'custom-coupon-plugin'));
	        setError(true);
	    }
	}

	function createDiscountRow() {
	    const row = document.createElement('div');
	    row.className = 'wc-block-components-totals-item gift-card-discount-row';
	    row.innerHTML = `
	        <span class="wc-block-components-totals-item__label">${__('Cardivo gift card:', 'custom-coupon-plugin')}</span>
	        <span class="wc-block-components-totals-item__value discount-value"></span>
	    `;
	    document.querySelector('.wp-block-woocommerce-checkout-order-summary-subtotal-block')
	            .insertAdjacentElement('afterend', row);
	    return row;
	}

    async function removeGiftCard(setMessage, setError, setGiftCardApplied) {
	    try {
	        const response = await fetch(apiUrl, {
	            method: 'POST',
	            headers: {
	                'Content-Type': 'application/x-www-form-urlencoded',
	            },
	            body: new URLSearchParams({
	                action: 'remove_cardivo_gift_card',
	            }),
	        });

	        if (!response.ok) {
	            throw new Error(`HTTP error! Status: ${response.status}`);
	        }

	        const result = await response.json();

	        if (result.success && result.data) {
	            const { message, original_total, gift_currency } = result.data;

	            setMessage('');
	            setError(false);
	            setGiftCardApplied(false);

	            // Use the same currency formatting method as applyGiftCard
	            const currencyParts = new Intl.NumberFormat("en-US", { 
				    style: 'currency', 
				    currency: result.data.gift_currency 
				}).formatToParts();
				const currencySymbol = currencyParts.find(part => part.type === 'currency')?.value.replace(/[A-Z]/g, '') || '';

	            const subtotalElement = document.querySelector('.wp-block-woocommerce-checkout-order-summary-totals-block .wc-block-components-totals-item__value');
	            let subtotal = subtotalElement ? parseFloat(subtotalElement.textContent.replace(/[^0-9.-]+/g, '')) : 0;

	            // Update the total amount correctly
	            const totalElement = document.querySelector('.wc-block-components-totals-footer-item .wc-block-components-totals-item__value');
	            if (totalElement) {
	                totalElement.textContent = `${currencySymbol}${subtotal.toFixed(2)}`;
	            } else {
	                console.warn("Total element not found. Check the selector.");
	            }

	            // Remove the discount row
	            const discountRow = document.querySelector('.gift-card-discount-row');
	            if (discountRow) {
	                discountRow.remove();
	            }

	            const redeemGiftCardButton = document.querySelector('.gift-card-header');
	            if (redeemGiftCardButton) {
	                redeemGiftCardButton.style.display = 'flex';
	            }

	            const minimumText = document.querySelector('.minimum-text');
			    const cartTotal = document.querySelector('.cart-total');

			    if (minimumText) minimumText.style.display = '';
			    if (cartTotal) cartTotal.style.display = '';

	        } else {
	            console.warn("Unexpected API Response:", result);
	            setMessage(result.data?.message || __('Unable to remove gift card.', 'custom-coupon-plugin'));
	            setError(true);
	        }
	    } catch (error) {
	        console.error("Gift Card Removal Error:", error);
	        setMessage(__('Failed to remove gift card. Please try again.', 'custom-coupon-plugin'));
	        setError(true);
	    }
	}

    const RenderGiftCard = () => {
        const [giftCardCode, setGiftCardCode] = React.useState('');
        const [message, setMessage] = React.useState('');
        const [isError, setIsError] = React.useState(false);
        const [isGiftCardApplied, setIsGiftCardApplied] = React.useState(false);

        return (
            <ExperimentalDiscountsMeta>
                <div className="wc-block-components-totals-wrapper custom-gift-card-wrapper">
                    <div className="gift-card-header">
                        <img
                            src="https://pub-7103d88a43754ed6a73fcfa6ebce51bf.r2.dev/Plugin/Images/np_gift-card_4917673_000000.svg"
                            alt="Gift Card Icon"
                        />
                        <a
                            href="javascript:void(0);"
                            onClick={() => {
                                document.querySelector('.gift-card-input-container').style.display = 'block';
                            }}
                        >
                            {__('Redeem a gift card', 'custom-coupon-plugin')}
                        </a>
                    </div>

                    <div className="gift-card-input-container" style={{ display: 'none' }}>
                        {!isGiftCardApplied && (
                            <>
                                <input
                                    type="text"
                                    placeholder={__('Enter your gift card', 'custom-coupon-plugin')}
                                    value={giftCardCode}
                                    onChange={(event) => setGiftCardCode(event.target.value)}
                                />
                                <button
                                    className="button alt"
                                    onClick={() =>
                                        applyGiftCard(
                                            giftCardCode,
                                            setMessage,
                                            setIsError,
                                            setIsGiftCardApplied
                                        )
                                    }
                                >
                                    {__('Apply', 'custom-coupon-plugin')}
                                </button>
                            </>
                        )}
                        {isGiftCardApplied && (
                            <button
                                className="remove-cardivo-gift-card"
                                onClick={() =>
                                    removeGiftCard(setMessage, setIsError, setIsGiftCardApplied)
                                }
                            >
                                {__('Remove', 'custom-coupon-plugin')}
                            </button>
                        )}
                    </div>

                    {message && (
					    <div
					        className={`bottom-msg gift-card-message ${isError ? 'error' : 'success'}`}
					        dangerouslySetInnerHTML={{ __html: message }}
					    />
					)}
                </div>
            </ExperimentalDiscountsMeta>
        );
    };

    registerPlugin('custom-gift-card-plugin', {
        render: RenderGiftCard,
        scope: 'woocommerce-checkout',
    });
})();

const btn = document.querySelector('#applyGiftCard');
if (btn) {
    btn.addEventListener('click', () => {
        const giftCardCode = document.querySelector('input[name="giftCardCode"]').value;
        applyGiftCard(giftCardCode);
    });
}
