<?php
/**
 * Copyright © MageWorx. All rights reserved.
 * See https://www.mageworx.com/terms-and-conditions for license details.
 */

use Hyva\Theme\ViewModel\CurrentProduct;

?>
<?php
/** @var \MageWorx\ShippingCalculatorBase\Block\Product\View\Calculator\Container $block */
/** @var \Magento\Framework\Escaper $escaper */
/** @var \Hyva\Theme\ViewModel\HeroiconsOutline $heroicons */
/** @var \Hyva\Theme\ViewModel\CurrentProduct $currentproduct */

$heroicons = $viewModels->require(\Hyva\Theme\ViewModel\HeroiconsOutline::class);
$currentProduct = $viewModels->require(CurrentProduct::class);
$product = $block->hasData('product');
?>
<?php
$product = $block->hasData('product')
    ? $block->getData('product')
    : $currentProduct->get();

if (!$product || !$product->getId()) {
    return;
}
// Get attribute value (replace 'deliverycost' with your actual attribute code)
$deliveryLabel = $product->getData('deliverytimelabel');

/*Get Delivery details*/
$gDetailspopup = $product->hasData('proratedeliv')
    ? $product->getData('proratedeliv')
    : '';

$gDetailspopup = is_string($gDetailspopup) ? html_entity_decode($gDetailspopup) : '';

?>
<?php if ($block->isAvailable()): ?>
    <script>
        "use strict";

        const MW_REGION_MODES = {
            select: "select",
            text: "text"
        }
        const MW_BLOCK_MODES = {
            form: "form",
            shipping_info: "info"
        }

        function initMwShippingCalculator() {
            const config = <?= $block->getConfigJson(); ?>;

            const {
                isCalculateByCountry,
                isCalculateByRegion,
                isCalculateByZip,
                isRegionRequired,
                isZipRequired,
                requestUrl,
                isCheapestMethodHighlightNeeded,
            } = config;

            const countries = <?= $block->getCountryOptionsJson(); ?>;
            const regions = <?= $block->getRegionsOptionsJson(); ?>;
            const postCodesObj = <?= $block->getSerializedCheckoutConfig(); ?>;
            const postCodes = postCodesObj.postCodes;

            const invalidZip = "<?= $escaper->escapeJs(__('Zip Code invalid. Valid Zip Code Examples:')); ?>";

            const $form = document.querySelector("#product_addtocart_form");

            return {
                init() {
                    this.isShowCountry = isCalculateByCountry;
                    this.countries = countries;
                    this.isShowRegion = isCalculateByRegion;
                    this.isRegionRequired = isRegionRequired;
                    this.isShowZip = isCalculateByZip;
                    this.isZipRequired = isZipRequired;
                    this.listenProductFormChanges();

                    const defaultCountry = this.countries.find(elem => elem.is_default);
                    const defaultCountryValue = defaultCountry.value;
                    if (defaultCountryValue) this.selectedCountryValue = defaultCountryValue;
                    else this.selectedCountryValue = this.countries[0].value;
                    this.onChangeCountry();
                },

                showPopup: false,


                onSubmit() {
                    if (this.validate()) {
                        // this.isLoading = true;

                        this.showPopup = true;
                        this.proceedWithCalculation(); // Start calculation immediately

                    }
                },

                // Add this new method
                proceedWithCalculation() {
                    this.isLoading = true;
                    this.shipping_list = null; // Clear previous results

                    const isSelectMode = this.regionMode === MW_REGION_MODES.select;
                    const url = new URL(requestUrl);
                    const params = url.searchParams;

                    params.append("address[country_id]", this.selectedCountry["value"]);

                    if (this.isShowRegion) {
                        if (isSelectMode) {
                            params.append("address[region]", this.selectedRegion["title"]);
                            params.append("address[region_id]", isSelectMode ? this.selectedRegion["value"] : "");
                        } else params.append("address[region]", this.textRegion);
                    }

                    if (this.isShowZip) params.append("address[postcode]", this.zipValue);

                    const formParams = new FormData($form);
                    let n = 0;
                    for (const prop of formParams) {
                        params.append(`item[${n}][name]`, prop[0]);
                        params.append(`item[${n}][value]`, prop[1]);
                        n++;
                    }

                    fetch(url)
                        .then(response => response.json())
                        .then(data => {
                            if (data.error) {
                                dispatchMessages([{
                                    type: 'error',
                                    text: data.error_message || "<?= $escaper->escapeJs(__('Shipping calculation failed')); ?>"
                                }], 5000);
                                this.showPopup = false;
                            } else {
                                this.shipping_list = data.shipping_methods;
                                if (isCheapestMethodHighlightNeeded) this.findCheapestShip();
                                // Keep popup open to show results
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            dispatchMessages([{
                                type: 'error',
                                text: "<?= $escaper->escapeJs(__('Network error. Please try again.')); ?>"
                            }], 5000);
                            this.showPopup = false;
                        })
                        .finally(() => {
                            this.isLoading = false;
                        });
                },

                findCheapestShip() {
                    if (this.shipping_list) {
                        let cheapestShip = this.shipping_list[0].price;
                        let cheapestShipIndex = 0;
                        this.shipping_list.forEach((ship, index) => {
                            if (ship.price < cheapestShip) {
                                cheapestShip = ship.price;
                                cheapestShipIndex = index;
                            }
                        })
                        this.cheapestShippingIndex = cheapestShipIndex;
                    }
                },
                checkProductFormValid() {
                    return $form.reportValidity();
                },
                validate() {
                    if (!this.isZipValid) {
                        return false;
                    }

                    if (!this.checkProductFormValid()) {
                        dispatchMessages([{
                            type: 'error',
                            text: "<?= $escaper->escapeJs(__('Fill out all required product fields')); ?>"
                        }], 5000)
                        return false;
                    }

                    return true;
                },
                isLoading: false,
                mode: MW_BLOCK_MODES.form,
                shipping_list: null,
                cheapestShippingIndex: null,
                isShowRefresh: false,
                listenProductFormChanges() {
                    const onChange = () => {
                        if (this.mode === MW_BLOCK_MODES.shipping_info) {
                            this.isShowRefresh = true;
                        }
                    }

                    const formElems = document.querySelectorAll(
                        "input[form='product_addtocart_form']",
                        "select[form='product_addtocart_form']"
                    );

                    $form.addEventListener("change", onChange);
                    formElems.forEach($root => $root.addEventListener("change", onChange))
                },

                isShowCountry: false,
                countries: [],
                selectedCountry: null,
                selectedCountryValue: null,
                onChangeCountry() {
                    this.selectedCountry = this.countries.find(country => country.value === this.selectedCountryValue);

                    const countryRegions = regions.filter(region => {
                        return region.country_id === this.selectedCountry.value;
                    })

                    const {
                        is_region_visible,
                        is_region_required,
                        is_zipcode_optional,
                    } = this.selectedCountry;

                    if (is_region_visible) {
                        this.regions = countryRegions;
                        this.initRegion();
                        this.isShowRegion = true;
                        this.isRegionRequired = false;
                    } else if (is_region_required) {
                        this.regions = countryRegions;
                        this.initRegion();
                        this.isShowRegion = true;
                        this.isRegionRequired = true;
                    } else this.isShowRegion = false;

                    if (is_zipcode_optional) this.isZipRequired = false;
                    else this.isZipRequired = true;

                    this.initZip();
                    const examples = [];
                    const postCode = postCodes[this.selectedCountry.value];
                    for (const key in postCode) {
                        this.zipPatterns.push({
                            pattern: postCode[key].pattern,
                            example: postCode[key].example,
                        })
                        examples.push(postCode[key].example);
                    }
                    this.zipExample = examples.join("; ");
                },

                isShowRegion: false,
                isRegionRequired: false,
                regions: [],
                textRegion: "",
                selectedRegion: null,
                selectedRegionIndex: null,
                regionMode: null,
                isSelectMode() {
                    return this.regionMode === MW_REGION_MODES.select;
                },
                isTextMode() {
                    return this.regionMode === MW_REGION_MODES.text;
                },
                initRegion() {
                    if (this.regions.length > 0) {
                        this.regionMode = MW_REGION_MODES.select;
                        this.selectedRegionIndex = 0;
                        this.onChangeRegion();
                    } else {
                        this.regionMode = MW_REGION_MODES.text;
                        this.textRegion = "";
                    }
                },
                onChangeRegion() {
                    this.selectedRegion = this.regions[this.selectedRegionIndex];
                },

                isShowZip: false,
                isZipRequired: false,
                invalidZipText: null,
                zipValue: "",
                zipPatterns: [],
                zipExample: "",
                isZipValid: true,
                initZip() {
                    this.invalidZipText = invalidZip;
                    this.zipValue = "";
                    this.zipPatterns = [];
                    this.zipExample = "";
                    this.isZipValid = true; // by default is valid because input has required html param (can't send empty)
                },
                onChangeZip() {
                    if (this.zipPatterns.length > 0) this.validateZip();
                },
                validateZip() {
                    let isValid = false

                    this.zipPatterns.forEach(el => {
                        const regExp = new RegExp(el["pattern"])
                        if (regExp.test(this.zipValue)) {
                            isValid = true;
                        }
                    })

                    this.isZipValid = isValid;
                },
            }
        }
    </script>
    <div x-cloak class="  border-b border-gray-300 pb-2 shipping-calculator" x-data="initMwShippingCalculator()">

        <!--Loading indicator-->
        <?= $block->getChildHtml('mw-calc-loading') ?>

        <template x-if="mode === MW_BLOCK_MODES.form">
            <div class="mw-devliery-calc-form">
                <div class="border-b border-gray-300 pb-4" style="display: none;">
                    <h3 class="mb-4 text-xl font-medium text-gray-900 title-font">
                        <?= $escaper->escapeHtml($block->getTitle()); ?>
                    </h3>

                    <div class="sc-short-description">
                        <?= $escaper->escapeHtml($block->getDescription()); ?>
                    </div>
                </div>

                <form class="mt-4" method="post"
                      @submit.prevent="onSubmit()" id="estimate-shipping-form">
                    <fieldset class="flex flex-col flex-wrap">

                        <!-- select country -->
                        <template x-if="isShowCountry">
                            <div class="p-2">
                                <label for="mw-shipping-country">
                                    <?= $escaper->escapeHtml(__('Country')); ?>
                                </label>
                                <select class="form-input mt-3 block w-full" id="mw-shipping-country"
                                        x-model="selectedCountryValue" @change="onChangeCountry()" required>
                                    <template x-for="(country, index) in countries" :key="country.value">
                                        <option x-text="country.label"
                                                :selected="country.value === selectedCountryValue"
                                                :value="country.value">
                                        </option>
                                    </template>
                                </select>
                            </div>
                        </template>
                        <!-- select country -->

                        <!-- Region (disabled for now) -->
                        <template x-if="false">
                            <div class="p-2">
                                <label for="mw-shipping-region">
                                    <?= $escaper->escapeHtml(__('Region/State')); ?>
                                    <span x-show="isRegionRequired" class="text-red-500">*</span>
                                </label>

                                <div x-show="isSelectMode()">
                                    <select class="form-input mt-3 block w-full" id="mw-shipping-region"
                                            x-model="selectedRegionIndex"
                                            :required="isSelectMode() && isRegionRequired"
                                            @change="onChangeRegion()">
                                        <template x-for="(region, index) in regions" :key="region.value">
                                            <option x-text="region.label" :selected="index === selectedRegionIndex"
                                                    :value="index"></option>
                                        </template>
                                    </select>
                                </div>

                                <div x-show="isTextMode()">
                                    <input type="text" class="form-input mt-3 block w-full" id="mw-shipping-region"
                                           :required="isTextMode() && isRegionRequired" x-model="textRegion"
                                           placeholder="<?= $escaper->escapeHtmlAttr(__('Please select a region, state or province.')); ?>"/>
                                </div>
                            </div>
                        </template>
                        <!-- Region -->

                        <!-- Postcode & Button aligned in one line -->
                        <template x-if="isShowZip">
                            <div class="flex items-end gap-1 md:gap-4" style="margin-top: -6px !important;">
                                <!-- Label + Input -->
                                <div class="flex items-center gap-1 md:gap-4">
                                    <svg version="1.1" width="24" height="24" viewBox="0 0 32 32" style="min-width: 24px; min-height: 24px;">
                                        <g
                                            id="SVGRepo_bgCarrier" stroke-width="0"></g>
                                        <g id="SVGRepo_tracerCarrier" stroke-linecap="round"
                                           stroke-linejoin="round"></g>
                                        <g id="SVGRepo_iconCarrier">
                                            <style type="text/css"> .st0 {
                                                    fill: none;
                                                    stroke: #000000;
                                                    stroke-width: 2;
                                                    stroke-linecap: round;
                                                    stroke-linejoin: round;
                                                    stroke-miterlimit: 10;
                                                }

                                                .st1 {
                                                    fill: none;
                                                    stroke: #000000;
                                                    stroke-width: 2;
                                                    stroke-linecap: round;
                                                    stroke-linejoin: round;
                                                    stroke-miterlimit: 10;
                                                    stroke-dasharray: 3;
                                                }

                                                .st2 {
                                                    fill: none;
                                                    stroke: #000000;
                                                    stroke-width: 2;
                                                    stroke-linejoin: round;
                                                    stroke-miterlimit: 10;
                                                }

                                                .st3 {
                                                    fill: none;
                                                } </style>
                                            <polyline class="st0" points="10,24 19,24 19,9 3,9 3,24 6,24 "></polyline>
                                            <circle class="st0" cx="24" cy="24" r="2"></circle>
                                            <circle class="st0" cx="8" cy="24" r="2"></circle>
                                            <polyline class="st0"
                                                      points="19,24 19,13 25,13 29,18 29,24 26,24 "></polyline>
                                            <rect x="-216" y="-432" class="st3" width="536" height="680"></rect>
                                        </g>
                                    </svg>
                                    <!-- Label -->
                                    <label for="mw-shipping-zip"
                                           class=" pt-2 flex nowflaxwrap font-semibold">
                                        Delivery
<!--                                        <span x-show="isZipRequired" class="text-red-500">*</span>
-->                                    </label>

                                    <div class="font-semibold" style="color: #e61c1c;">
                                        <?php if (!empty($deliveryLabel) && strtolower($deliveryLabel) !== 'no'):
                                            ?>
                                            <?php echo $deliveryLabel;
                                        endif;
                                        ?>
                                    </div>
                                    <!-- Input + Error Message -->
                                    <div class="">
                                        <input type="text"
                                               class="form-input block w-full text-sm md:text-base"
                                               id="mw-shipping-zip"
                                               placeholder="Add your postcode"
                                               x-model="zipValue"
                                               @input="onChangeZip()"
                                               :required="isZipRequired" required/>

                                        <p class=" hidden pt-2 text-red-500 text-sm"

                                           x-show="!isZipValid && (zipValue !== '')"
                                           x-text="invalidZipText + ' ' + zipExample">
                                        </p>
                                    </div>
                                </div>


                                <!-- Submit Button -->
                                <div class="flex items-center gap-4">
                                    <button type="submit"
                                            class="btn btn-primary w-24"
                                            form="estimate-shipping-form">
                                        <?= $escaper->escapeHtml(__("Check")) ?>
                                    </button>
                                </div>
                            </div>
                        </template>
                    </fieldset>
                </form>


            </div>
        </template>

        <template x-if="showPopup">
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                <div class="relative bg-white p-8 rounded-lg w-full max-w-xl mx-4 max-h-[80vh] overflow-y-auto">

                    <!-- Close Button (top-right) -->
                    <div style="float:right">

                        <button @click="showPopup = false" type="button"
                                class="absolutes top-3 right-13 text-gray-400 hover:text-gray-500 border-none outline-none focus:outline-none p-1">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                      d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>


                    <!-- Loading State -->
                    <template x-if="isLoading">
                        <div class="text-center py-8">
                            <?= $heroicons->refreshHtml('animate-spin h-10 w-10 mx-auto text-blue-500') ?>
                            <p class="mt-4"><?= $escaper->escapeHtml(__('Calculating shipping rates...')) ?></p>
                        </div>
                    </template>

                    <!-- Results State -->
                    <template x-if="!isLoading && shipping_list && shipping_list.length > 0">
                        <div>
                            <h3 class=" text-xl font-semibold text-gray-900 dark:text-white text-center w-full mb-4">
                                <?= $escaper->escapeHtml(__('Shipping Options')) ?>
                            </h3>

                            <div class="space-y-3">
                                <template x-for="(method, index) in shipping_list" :key="method.code">
                                    <div class="border rounded p-3"
                                         :class="{'border-green-300 bg-green-50': index === cheapestShippingIndex}">
                                        <div class="flex justify-between items-center">
                                            <div class="flex items-center gap-2">
                                                <template x-if="method.image">
                                                    <img :src="method.image" class="h-8 w-8 object-contain">
                                                </template>
                                                <div>
                                                    <div class="font-bold text-lg" x-text="method.carrier_title"></div>
                                                    <!--                                                    <div class="text-sm text-gray-500 font-semibold" x-text="method.title"></div>
                                                    -->                                                </div>
                                            </div>
                                            <div class="font-bold text-lg" x-text="method.price_formatted"></div>
                                        </div>

                                        <template x-if="method.description || method.delivery_formatted">
                                            <div class="mt-2 pt-2 border-t border-gray-100 text-sm">
                                                <div x-text="method.description"></div>
                                                <div class="text-blue-600" x-text="method.delivery_formatted"></div>
                                            </div>
                                        </template>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </template>

                    <!-- No Results State -->
                    <template x-if="!isLoading && (!shipping_list || shipping_list.length === 0)">
                        <div class="text-center py-8">
                            <?= $heroicons->truckHtml('mx-auto h-10 w-10 text-gray-400') ?>
                            <p class="mt-4"><?= $escaper->escapeHtml(__('No shipping methods available for this location')) ?></p>
                        </div>
                    </template>

                    <!-- DYNAMIC NOTE SECTION -->
                    <div class="mt-6 p-4 bg-gray-50 rounded-md text-sm leading-relaxed">
                        <style>
                            .shipping-note ul {
                                list-style-type: disc;
                                padding-left: 1.25rem;
                                margin-top: 0.5rem;
                            }

                            .shipping-note li {
                                margin-bottom: 0.5rem;
                            }
                        </style>
                        <div class="shipping-note">
                            <?= $gDetailspopup ?>
                        </div>
                    </div>

                    <!-- Bottom Close Button -->
                    <div class="flex justify-end mt-4">
                        <button @click="showPopup = false" class="btn btn-primary">
                            <?= $escaper->escapeHtml(__('Close')) ?>
                        </button>
                    </div>
                </div>
            </div>
        </template>


    </div>
<?php endif; ?>


