/**
 * ShippingGuard – Universal Cart/Checkout Integration
 *
 * Handles BOTH modes:
 *   A) WooCommerce Blocks (block cart / block checkout)
 *   B) Classic WooCommerce (shortcode cart / shortcode checkout)
 *
 * Total update strategy:
 *   - Block Cart/Checkout  → POST /wc/store/v1/cart/extensions → WC recalculates & re-renders
 *   - Classic Cart         → POST wc-ajax=update_shipping_method → WC recalculates fragments
 *   - Classic Checkout     → Trigger update_checkout (post_data mechanism handles session)
 */
(function () {
    'use strict';

    const params        = window.sg_block_params || {};
    const ajaxUrl       = params.ajax_url        || '/wp-admin/admin-ajax.php';
    const nonce         = params.nonce           || '';
    const storeApiUrl   = params.store_api_url   || '/wp-json/wc/store/v1/cart/extensions';
    const storeApiNonce = params.store_api_nonce || '';

    // -----------------------------------------------------------------------
    // Page-type detection
    // -----------------------------------------------------------------------
    function isBlockCart() {
        return !!(
            document.querySelector('.wp-block-woocommerce-cart') ||
            document.querySelector('.wc-block-cart')
        );
    }

    function isBlockCheckout() {
        return !!(
            document.querySelector('.wp-block-woocommerce-checkout') ||
            document.querySelector('.wc-block-checkout')
        );
    }

    function isClassicCart() {
        return !isBlockCart() && document.body.classList.contains('woocommerce-cart');
    }

    function isClassicCheckout() {
        return !isBlockCheckout() && document.body.classList.contains('woocommerce-checkout');
    }

    // -----------------------------------------------------------------------
    // Build the protection card HTML (for block injection)
    // -----------------------------------------------------------------------
    function buildCardHTML(isEnabled) {
        const defaultIcon = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#48bb78" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path><polyline points="9 11 12 14 20 6"></polyline></svg>`;
        const iconHtml = params.protection_icon
            ? `<img src="${params.protection_icon}" alt="Protection" style="width:30px;height:30px;object-fit:contain;">`
            : defaultIcon;
        const feeDisplay = isEnabled ? params.fee_amount || '' : `<span style="color:#a0aec0;text-decoration:line-through">${params.fee_amount || ''}</span>`;

        return `
        <div class="shippingguard-premium-card" id="sg-block-card">
            <div class="sg-icon-container">${iconHtml}</div>
            <div class="sg-content">
                <div class="sg-title">${params.protection_name || 'Shipping Protection'}</div>
                <div class="sg-price sg-block-price">${feeDisplay}</div>
                <div class="sg-subtext">${params.checkout_label || ''}</div>
                <div class="sg-powered">Powered by <a href="https://dominopress.com/plugin/shippingguard" target="_blank">ShippingGuard</a></div>
            </div>
            <div class="sg-action">
                <label class="sg-switch">
                    <input type="checkbox" id="shippingguard_protection_block" value="1" ${isEnabled ? 'checked' : ''}>
                    <span class="sg-slider"></span>
                </label>
            </div>
        </div>`;
    }

    // -----------------------------------------------------------------------
    // BLOCK pages: Update via WC Store API /cart/extensions
    // This is the official mechanism — WC recalculates fees server-side
    // and re-renders the entire totals section inside WC Blocks.
    // -----------------------------------------------------------------------
    function blockToggle(isEnabled) {
        // Optimistically update our card price display
        const priceEl = document.querySelector('.sg-block-price');
        if (priceEl) {
            priceEl.innerHTML = isEnabled
                ? (params.fee_amount || '')
                : `<span style="color:#a0aec0;text-decoration:line-through">${params.fee_amount || ''}</span>`;
        }

        // Get the nonce — WC Blocks may expose it on window
        const wcBlocksNonce = storeApiNonce
            || window.wcSettings?.storeApiNonce
            || window.wc?.wcSettings?.storeApiNonce
            || '';

        fetch(storeApiUrl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                'Nonce': wcBlocksNonce,
                'X-WC-Store-API-Nonce': wcBlocksNonce,
            },
            body: JSON.stringify({
                namespace: 'shippingguard',
                data: { enabled: isEnabled }
            })
        })
        .then(r => {
            if (!r.ok) throw new Error('Store API error: ' + r.status);
            return r.json();
        })
        .then(cartData => {
            // Dispatch updated cart data to WC Blocks store so it re-renders totals
            if (window.wp && window.wp.data) {
                try {
                    window.wp.data.dispatch('wc/store/cart').receiveCart(cartData);
                } catch (e) {
                    // Fallback: invalidate the cart resolution to force re-fetch
                    try {
                        window.wp.data.dispatch('wc/store/cart').invalidateResolutionForStoreSelector('getCartTotals');
                        window.wp.data.dispatch('wc/store/cart').invalidateResolutionForStoreSelector('getCart');
                    } catch (e2) {
                        console.warn('[ShippingGuard] Could not refresh WC Blocks store:', e2);
                    }
                }
            }
        })
        .catch(err => {
            console.warn('[ShippingGuard] Store API error:', err);
            // Fallback: set via basic AJAX then reload
            fallbackAjaxToggle(isEnabled, () => window.location.reload());
        });
    }

    // -----------------------------------------------------------------------
    // CLASSIC CART: Update via WC shipping AJAX
    // Posting to woocommerce_update_shipping_method triggers WC to
    // recalculate ALL fees and return updated cart total fragments.
    // -----------------------------------------------------------------------
    function classicCartToggle(isEnabled) {
        const $ = window.jQuery;
        if (!$) return fallbackAjaxToggle(isEnabled, () => window.location.reload());

        // Step 1: Set session via our AJAX
        $.post(ajaxUrl, {
            action:   'shippingguard_classic_toggle',
            enabled:  isEnabled ? 'true' : 'false',
            security: nonce,
        }, function() {
            // Step 2: Tell WooCommerce to recalculate cart by triggering shipping update
            // This causes WC to run calculate_totals() (which fires our add_fee hook)
            // and return updated HTML fragments for the entire cart totals section.
            const shippingForm = $('.shipping-calculator-form');
            const shippingMethods = [];

            // Collect currently selected shipping methods
            $('[name^="shipping_method"]').each(function() {
                shippingMethods.push($(this).val());
            });

            $.ajax({
                type:       'POST',
                url:        ajaxUrl,
                data:       {
                    action:           'woocommerce_update_shipping_method',
                    security:         params.update_ship_nonce || wc_cart_params?.update_shipping_method_nonce || '',
                    shipping_method:  shippingMethods,
                },
                success: function(response) {
                    // WooCommerce handles the fragment updates and replaces cart totals HTML
                    $( document.body ).trigger('updated_cart_totals');
                    $( document.body ).trigger('wc_fragments_refreshed');

                    // Force a fragment refresh for mini-cart + totals
                    $.post(ajaxUrl, { action: 'woocommerce_get_refreshed_fragments' }, function(fragData) {
                        if (fragData && fragData.fragments) {
                            $.each(fragData.fragments, function(key, value) {
                                $(key).replaceWith(value);
                            });
                        }
                    });
                },
                error: function() {
                    // Final fallback: reload the page
                    window.location.reload();
                }
            });
        });
    }

    // -----------------------------------------------------------------------
    // CLASSIC CHECKOUT: Let WC's built-in mechanism handle it
    // The checkbox state is sent via post_data when update_checkout fires.
    // We just need to fire the trigger.
    // -----------------------------------------------------------------------
    function classicCheckoutToggle(isChecked, checkbox) {
        // Ensure the checkbox state is correct before triggering
        if (window.jQuery) {
            window.jQuery(checkbox).prop('checked', isChecked);
            window.jQuery('body').trigger('update_checkout');
        }
    }

    // -----------------------------------------------------------------------
    // Fallback: Basic AJAX session set (no total refresh)
    // -----------------------------------------------------------------------
    function fallbackAjaxToggle(isEnabled, callback) {
        const formData = new FormData();
        formData.append('action', 'shippingguard_classic_toggle');
        formData.append('security', nonce);
        formData.append('enabled', isEnabled ? 'true' : 'false');

        fetch(ajaxUrl, { method: 'POST', body: formData })
            .then(() => callback && callback())
            .catch(() => callback && callback());
    }

    // -----------------------------------------------------------------------
    // Inject card into WC Block pages
    // -----------------------------------------------------------------------
    function injectBlockCard() {
        if (document.getElementById('sg-block-card')) return;

        const showOnCart     = params.show_on_cart !== 'no';
        const showOnCheckout = params.show_on_checkout !== 'no';

        if (isBlockCart() && !showOnCart) return;
        if (isBlockCheckout() && !showOnCheckout) return;

        // Try various WC Block order summary selectors
        const selectors = [
            '.wc-block-components-totals-shipping',
            '.wp-block-woocommerce-cart-order-summary-shipping-block',
            '.wp-block-woocommerce-checkout-order-summary-shipping-block',
            '.wc-block-components-order-summary',
            '.wc-block-cart__totals',
            '.wc-block-checkout__order-summary',
            '.wp-block-woocommerce-cart-order-summary-block',
            '.wp-block-woocommerce-checkout-order-summary-block',
            '.wc-block-cart-items',
        ];

        let target = null;
        for (const sel of selectors) {
            target = document.querySelector(sel);
            if (target) break;
        }

        if (!target) return;

        const isEnabled  = params.fee_enabled === 'yes';
        const wrapper    = document.createElement('div');
        wrapper.style.cssText = 'margin: 16px 0;';
        wrapper.innerHTML = buildCardHTML(isEnabled);
        target.parentNode.insertBefore(wrapper, target.nextSibling);

    }

    // Expose for use by the React component in Index.jsx
    window.sg_block_toggle = blockToggle;

    // -----------------------------------------------------------------------
    // Observe DOM for block rendering (async)
    // -----------------------------------------------------------------------
    function observeAndInjectBlock() {
        injectBlockCard();
        if (document.getElementById('sg-block-card')) return;

        const observer = new MutationObserver(function (_, obs) {
            injectBlockCard();
            if (document.getElementById('sg-block-card')) obs.disconnect();
        });
        observer.observe(document.body, { childList: true, subtree: true });

        setTimeout(function () {
            observer.disconnect();
            injectBlockCard();
        }, 8000);
    }

    // -----------------------------------------------------------------------
    // Init
    // -----------------------------------------------------------------------
    function init() {
        if (isBlockCart() || isBlockCheckout()) {
            observeAndInjectBlock();
        } else {
            // Observe until we know if blocks are rendered
            const obs = new MutationObserver(function (_, o) {
                if (isBlockCart() || isBlockCheckout()) {
                    o.disconnect();
                    observeAndInjectBlock();
                }
            });
            obs.observe(document.body, { childList: true, subtree: true });
            setTimeout(() => obs.disconnect(), 5000);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
