<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_FrequentlyBought
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\SwatchRenderer;

use Magento\Swatches\ViewModel\Product\Renderer\Configurable as ConfigurableViewModel;

// phpcs:disable Generic.Files.LineLength.TooLong

/** @var Magento\Swatches\Block\Product\Renderer\Configurable $block */
/** @var Magento\Framework\Escaper $escaper */
/** @var ViewModelRegistry $viewModels */

/** @var ConfigurableViewModel $configurableViewModel */
$configurableViewModel = $viewModels->require(ConfigurableViewModel::class);

/** @var SwatchRenderer $swatchRendererViewModel */
$swatchRendererViewModel = $viewModels->require(SwatchRenderer::class);

$product = $block->getProduct();
$productId = $product->getId();

$attributes = $block->decorateArray($block->getAllowAttributes());

$layout = $block->getLayout();
$swatchItemBlock = $layout->getBlock('mageplaza.frequently.bought.product.swatch.item');
$swatchItemBlock->setData('product_id', $productId);

$tooltipBlockHtml = $block->getBlockHtml('product.swatch.tooltip');
?>
<?php if ($product->isSaleable() && count($attributes)): ?>
    <script>
        function initConfigurableSwatchOptions_<?= (int) $productId ?>() {
            const configurableOptionsComponent = initConfigurableOptions(
                '<?= (int) $productId ?>',
                <?= /* @noEscape */ $block->getJsonConfig() ?>
            );
            const swatchOptionsComponent = initSwatchOptions(
                <?= /* @noEscape */ $block->getJsonSwatchConfig() ?>
            );
            function changeOption(attributeId, value) {
                if (value === '') {
                    this.selectedValues = this.removeAttrFromSelection(this.selectedValues, attributeId)
                } else if (value && this.getAllowedAttributeOptions(attributeId).find(option => option.id === value)) {
                    <?php /* Only set as selected value if it is valid */ ?>
                    this.selectedValues[attributeId] = value;
                }
                this.findSimpleIndex();
                this.findAllowedAttributeOptions();
                this.updatePrices();
                window.dispatchEvent(
                    new CustomEvent(
                        'configurable-selection-changed',
                        {
                            detail: {
                                productId: this.productId,
                                optionId: attributeId,
                                value: value,
                                productIndex: this.productIndex,
                                selectedValues: this.selectedValues,
                                candidates: this.findProductIdsForPartialSelection(this.selectedValues),
                            }
                        }
                    )
                );
            };
            return Object.assign(
                configurableOptionsComponent,
                swatchOptionsComponent,
                {
                    changeOption: changeOption
                }
            );
        }
    </script>

    <div x-data="initConfigurableSwatchOptions_<?= (int) $productId ?>()"
         x-init="init(); initShowSwatchesIntersect();"
         @private-content-loaded.window="onGetCartData($event.detail.data)"
         class="relative mb-6"
    >
        <div>
            <?php foreach ($attributes as $attribute): ?>
                <?php $attributeId = $attribute->getAttributeId(); ?>
                <?php $productAttribute = $attribute->getProductAttribute();  ?>
                <?php if ($swatchRendererViewModel->isSwatchAttribute($productAttribute)): ?>
                    <div class="swatch-attribute border-t last:border-b w-full border-container min-h-14
                            <?= $escaper->escapeHtmlAttr($productAttribute->getAttributeCode()) ?>">
                        <template x-if="showSwatches">
                            <div class="flex flex-col sm:flex-row items-center py-4 sm:py-1 w-full border-gray-300">

                                <label
                                    class="w-full sm:w-1/2 text-left text-gray-700 label product-option-label"
                                    id="attribute-label-<?= $escaper->escapeHtmlAttr($productId . '-' . $attributeId) ?>"
                                    aria-hidden="true"
                                >
                                    <span><?= $escaper->escapeHtml($productAttribute->getStoreLabel()) ?></span>
                                    <span
                                        class="text-gray-900 ml-2 font-bold"
                                        x-text="getSwatchText(<?= (int)$attributeId ?>, selectedValues[<?= (int)$attributeId ?>])"
                                    ></span>
                                </label>
                                <div class="w-full sm:ml-2 sm:w-1/2 text-left text-gray-900 product-option-values field field-reserved ">
                                    <div
                                        class="flexitems-center -mx-4 space-x-4 swatch-attribute-options"
                                        role="radiogroup"
                                        aria-label="<?= $escaper->escapeHtmlAttr($productAttribute->getStoreLabel()) ?>"
                                    >
                                        <template
                                            x-for="(item, index) in optionConfig.attributes[<?= (int) $attributeId ?>].options"
                                            :key="item.id"
                                        >
                                            <?= /* @noEscape */ $swatchItemBlock->setData('attribute_id', $attributeId)->toHtml(); ?>
                                        </template>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                <?php else: ?>
                    <div class="flex flex-col sm:flex-row items-center py-2 w-full border-t border-gray-300 last:border-b">
                        <label class="w-full sm:w-1/2 text-left text-gray-700 label"
                               for="attribute<?= $escaper->escapeHtmlAttr($attribute->getAttributeId()) ?>"
                        >
                            <span>
                                <?= $escaper->escapeHtml($attribute->getProductAttribute()->getStoreLabel()) ?>
                            </span>
                        </label>
                        <div class="w-full sm:ml-2 sm:w-1/2 text-left text-gray-900">
                            <select name="super_attribute[<?= (int) $productId ?>][<?= $escaper->escapeHtmlAttr($attribute->getAttributeId()) ?>]"
                                    id="attribute<?= $escaper->escapeHtmlAttr($attribute->getAttributeId()) ?>"
                                    class="form-select super-attribute-select max-w-full"
                                    x-on:change="changeOption(<?= (int) $attribute->getAttributeId() ?>, event.target.value)"
                                    required>
                                <option value="">
                                    <?= $escaper->escapeHtml(__('Choose an Option...')) ?>
                                </option>
                                <template
                                    x-for="(item, index) in getAllowedAttributeOptions(<?= (int) $attribute->getAttributeId() ?>)"
                                    :key="item.id"
                                >
                                    <option
                                        :value="item.id"
                                        x-html="item.label"
                                        :selected="selectedValues[<?= $escaper->escapeHtmlAttr($attribute->getAttributeId()) ?>] ===
                                item.id">
                                    </option>
                                </template>
                            </select>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
        <?= /* @noEscape */ $tooltipBlockHtml ?>
    </div>

<?php endif;?>

