<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\StoreConfig;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;

/** @var Escaper $escaper */
/** @var Template $block */
/** @var ViewModelRegistry $viewModels */

$storeConfig = $viewModels->require(StoreConfig::class);
$maxItemsToDisplay = $storeConfig->getStoreConfig('checkout/sidebar/max_items_display_count');

/** @var HeroiconsOutline $heroicons */
$heroicons = $viewModels->require(HeroiconsOutline::class);
?>
<script>
    function initCartDrawer() {
        return {
            open: false,
            isLoading: false,
            cart: {},
            maxItemsToDisplay: <?= (int) $maxItemsToDisplay ?>,
            itemsCount: 0,
            init() {
                // Check if open_cart parameter is in the URL
                const urlParams = new URLSearchParams(window.location.search);
                if (urlParams.has('open_cart')) {
                    // Remove only the open_cart parameter while preserving all other parameters
                    urlParams.delete('open_cart');
                    const newSearch = urlParams.toString();
                    const newUrl = window.location.pathname + (newSearch ? '?' + newSearch : '');
                    window.history.replaceState({}, document.title, newUrl);

                    // Wait for the cart data to be loaded before opening the drawer
                    window.addEventListener('private-content-loaded', () => {
                        setTimeout(() => {
                            this.openCartDrawer();
                        }, 500); // Small delay to ensure cart data is processed
                    }, { once: true });
                }
            },
            getData(data) {
                if (data.cart) {
                    this.cart = data.cart;
                    this.itemsCount = data.cart.items && data.cart.items.length || 0;
                    this.setCartItems();
                }
                this.isLoading = false;
            },
            cartItems: [],
            getItemCountTitle() {
                return hyva.strf('<?= $escaper->escapeJs(__('%0 of %1 products in cart displayed')) ?>', this.maxItemsToDisplay, this.itemsCount)
            },
            setCartItems() {
                this.cartItems = this.cart.items && this.cart.items.sort((a, b) => b.item_id - a.item_id) || [];

                if (this.maxItemsToDisplay > 0) {
                    this.cartItems = this.cartItems.slice(0, parseInt(this.maxItemsToDisplay, 10));
                }
            },
            deleteItemFromCart(itemId) {
                this.isLoading = true;

                const itemData = this.cart.items.filter((item) => item['item_id'] === itemId);
                const formKey = hyva.getFormKey();
                const postUrl = BASE_URL + 'checkout/sidebar/removeItem/';

                fetch(postUrl, {
                    "headers": {
                        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
                    },
                    "body": "form_key=" + formKey + "&item_id=" + itemId,
                    "method": "POST",
                    "mode": "cors",
                    "credentials": "include"
                }).then(response => {
                    if (response.redirected) {
                        window.location.href = response.url;
                    } else if (response.ok) {
                        return response.json();
                    } else {
                        window.dispatchMessages && window.dispatchMessages([{
                            type: 'warning',
                            text: '<?= $escaper->escapeJs(__('Could not remove item from quote.')) ?>'
                        }]);
                        this.isLoading = false;
                    }
                }).then(result => {
                    window.dispatchMessages && window.dispatchMessages([{
                        type: result.success ? 'success' : 'error',
                        text: result.success
                            ? '<?= $escaper->escapeJs(__('You removed the item.')) ?>'
                            : result.error_message
                    }], result.success ? 5000 : 0);

                    if (result.success && itemData) {
                        window.dispatchEvent(new CustomEvent('cart-item-removed', { detail: itemData }));
                    }

                    window.dispatchEvent(new CustomEvent('reload-customer-section-data'));
                });
            },
            scrollLock(use = true) {
                document.body.style.overflow = use ? "hidden" : "";
            },
            toggleCartDrawer(event) {
                if (event.detail && event.detail.isOpen !== undefined) {
                    if (event.detail.isOpen) {
                        this.openCartDrawer();
                    } else {
                        this.open = false;
                        this.scrollLock(false);
                        this.$refs && this.$refs.cartDialogContent && hyva.releaseFocus(this.$refs.cartDialogContent);
                    }
                } else {
                    <?php
                    /*
                     * The toggle-cart event was previously dispatched without parameter to open the drawer (not toggle).
                     * Keeping this in here for backwards compatibility.
                     */
                    ?>
                    this.openCartDrawer()
                }
            },
            openCartDrawer() {
                this.open = true;
                this.scrollLock(true);
                this.$nextTick(() => {
                    this.$refs && this.$refs.cartDialogContent && hyva.trapFocus(this.$refs.cartDialogContent)
                })
            },
            closeCartDrawer() {
                this.$dispatch('toggle-cart', { isOpen: false })
            },
            getSectionDataExtraActions() {
                if (!this.cart.extra_actions) {
                    return '';
                }

                const contentNode = document.createElement('div');
                contentNode.innerHTML = this.cart.extra_actions;

                hyva.activateScripts(contentNode);

                return contentNode.innerHTML;
            }
        }
    }
</script>
<section x-cloak
         x-show="cart"
         id="cart-drawer"
         x-data="initCartDrawer()"
         x-init="init()"
         @private-content-loaded.window="getData($event.detail.data)"
         @toggle-cart.window="toggleCartDrawer($event)"
         @keydown.escape="closeCartDrawer"
>
    <div role="dialog"
         aria-labelledby="cart-drawer-title"
         aria-modal="true"
         :aria-hidden="!open"
         class="fixed inset-y-0 right-0 z-30 flex max-w-full">
        <div class="backdrop"
             x-show="open"
             x-transition:enter="ease-in-out duration-500"
             x-transition:enter-start="opacity-0"
             x-transition:enter-end="opacity-100"
             x-transition:leave="ease-in-out duration-500"
             x-transition:leave-start="opacity-100"
             x-transition:leave-end="opacity-0"
             role="button"
             @click="closeCartDrawer"
             aria-label="<?= $escaper->escapeHtmlAttr(__('Close minicart')) ?>"></div>
        <div class="relative w-screen max-w-md shadow-2xl"
             x-show="open"
             x-transition:enter="transform transition ease-in-out duration-500 sm:duration-700"
             x-transition:enter-start="translate-x-full"
             x-transition:enter-end="translate-x-0"
             x-transition:leave="transform transition ease-in-out duration-500 sm:duration-700"
             x-transition:leave-start="translate-x-0"
             x-transition:leave-end="translate-x-full"
             x-ref="cartDialogContent"
             role="region"
             :tabindex="open ? 0 : -1"
             aria-label="<?= $escaper->escapeHtmlAttr(__('My Cart')) ?>"

        >
            <div class="flex flex-col h-full max-h-screen bg-white text-black shadow-xl">
                <?= $block->getChildHtml('cart-drawer.top'); ?>

                <header class="relative px-4 py-6 sm:px-6">
                    <p id="cart-drawer-title" class="text-lg font-medium leading-7 text-gray-900">
                        <strong><?= $escaper->escapeHtml(__('My Cart')) ?></strong>
                        <span class="items-total text-xs"
                              x-show="maxItemsToDisplay && maxItemsToDisplay < itemsCount"
                              x-text="getItemCountTitle()">
                        </span>
                    </p>
                </header>

                <?= $block->getChildHtml('cart-drawer.items.before'); ?>

                <template x-if="!itemsCount">
                    <div class="relative px-4 py-6 bg-white border-bs sm:px-6 border-container">
                        <?= $escaper->escapeHtml(__('Cart is empty')) ?>
                    </div>
                </template>

                <template x-if="itemsCount">
                    <div class="relative grid gap-4 px-1 py-3 sm:px-3 bg-white border-b border-container overflow-y-auto overscroll-y-contain">
                        <template x-for="item in cartItems">
                            <div class="flex items-start p-2 space-x-2 transition duration-150 ease-in-out rounded-lg border">
                                <template x-if="item.product_has_url && item.is_visible_in_site_visibility">
                                    <a :href="item.product_url"
                                       class="!ml-0"
                                       :aria-label="hyva.strf('<?= $escaper->escapeJs(__('Product "%0"')) ?>', item.product_name)"
                                    >
                                        <img
                                            :src="item.product_image.src"
                                            :width="item.product_image.width"
                                            :height="item.product_image.height"
                                            loading="lazy"
                                            :alt="item.product_name"
                                            class="w-[110px]"
                                        />
                                    </a>
                                </template>
                                <template x-if="!item.product_has_url || !item.is_visible_in_site_visibility">
                                    <div class="w-1/4 !ml-0">
                                        <img
                                            :src="item.product_image.src"
                                            :width="item.product_image.width"
                                            :height="item.product_image.height"
                                            loading="lazy"
                                            :alt="item.product_name"
                                        />
                                    </div>
                                </template>
                                <div class="w-3/4 space-y-2">
                                    <div>
                                        <p class="text-base font-medium line-clamp-2 text-black font-sen">
                                            <span x-html="item.qty"></span> x <span x-html="item.product_name"></span>
                                        </p>
                                        <p class="text-sm font-sen text-black"><span x-html="item.product_sku"></span></p>
                                    </div>
                                    <template x-for="option in item.options">
                                        <div class="pt-2 flex flex-wrap gap-1 items-center ">
                                            <p class="font-semibold" x-text="option.label + ':'"></p>
                                            <p class="font-sen font-medium text-black text-sm" x-html="option.value"></p>
                                        </div>
                                        inline-flex items-center w-full mt-3 md:text-sm text-secondary hover:text-secondary-darker                  </template>
                                    <div>
                                        <span x-html="item.product_price"></span>
                                        <div>
                                            <a :href="item.configure_url"
                                               x-show="item.product_type !== 'grouped' && item.is_visible_in_site_visibility"
                                               class="btn btn-secondary inline-flex mr-2 p-2 border-2 text-black border-primary-darker"
                                               :aria-label="hyva.strf('<?= $escaper->escapeJs(__('Edit product "%0"')) ?>', item.product_name)"
                                            >
                                                <?= $heroicons->pencilHtml('', 16, 16, ['aria-hidden' => 'true']); ?>
                                            </a>
                                            <button type="button"
                                                    class="btn-remove border-red-500 action delete btn btn-secondary inline-flex p-2"
                                                    @click="deleteItemFromCart(item.item_id)"
                                                    :aria-label="hyva.strf('<?= $escaper->escapeJs(__('Remove product "%0" from cart')) ?>', item.product_name)"
                                            >
                                                <svg xmlns="http://www.w3.org/2000/svg" width="18px" height="16" viewBox="0 0 16 20" fill="none" style="margin-left: -2px">
                                                    <path d="M1.38672 4.6H3.1645M3.1645 4.6H17.3867M3.1645 4.6V17.2C3.1645 17.6774 3.3518 18.1352 3.6852 18.4728C4.01859 18.8104 4.47078 19 4.94227 19H13.8312C14.3027 19 14.7548 18.8104 15.0882 18.4728C15.4216 18.1352 15.6089 17.6774 15.6089 17.2V4.6M5.83116 4.6V2.8C5.83116 2.32261 6.01846 1.86477 6.35186 1.52721C6.68526 1.18964 7.13745 1 7.60894 1H11.1645C11.636 1 12.0882 1.18964 12.4216 1.52721C12.755 1.86477 12.9423 2.32261 12.9423 2.8V4.6M7.60894 9.1V14.5M11.1645 9.1V14.5" stroke="#B3261E" stroke-linecap="round" stroke-linejoin="round"/>
                                                </svg>
                                            </button>
                                        </div>
                                    </div>


                                </div>
                            </div>
                        </template>
                    </div>
                </template>

                <template x-if="itemsCount">
                    <div>
                        <?= $block->getChildHtml('cart-drawer.totals.before'); ?>

                        <div class="gap-4 py-3 px-1 sm:px-3 ">
                            <div class="w-full p-3 space-x-4 transition duration-150 ease-in-out bg-gray-200 rounded">
                                <div class="flex items-center justify-between text-base font-sen font-semibold px-2">
                                    <span > <?= $escaper->escapeHtml(__('Subtotal')) ?>:</span> <span x-html="cart.subtotal"></span>
                                </div>
                            </div>
                            <div class="flex justify-center items-center w-full py-3 space-x-4 transition duration-150 ease-in-out rounded-lg ">
                                <a
                                   href="<?= $escaper->escapeUrl($block->getUrl('checkout')) ?>"
                                   class="w-full inline-flex btn btn-primary rounded font-sen"
                                >
                                    <?= $escaper->escapeHtml(__('Checkout')) ?>
                                </a>
                                <a href="<?= $escaper->escapeUrl($block->getUrl('checkout/cart')) ?>"
                                   class="font-sen w-full btn btn-secondary border-2 border-primary-darker text-black py-2 px-4 text-base rounded"
                                >
                                    <?= $escaper->escapeHtml(__('View Cart')) ?>
                                </a>
                            </div>
                            <div x-html="getSectionDataExtraActions()"></div>
                            <?= $block->getChildHtml('extra_actions'); ?>
                        </div>
                    </div>
                </template>

                <?= $block->getChildHtml('cart-drawer.bottom'); ?>
            </div>

            <button
                type="button"
                @click="closeCartDrawer"
                aria-label="<?= $escaper->escapeHtmlAttr(__('Close minicart')) ?>"
                class="absolute top-4 bg-primary right-2 p-1 mt-2 rounded text-white"
            >
                <?= $heroicons->xHtml('w-5 h-5', 24, 24, ['aria-hidden' => 'true']); ?>
            </button>
        </div>
        <?= $block->getChildHtml('loading') ?>
    </div>

</section>
