<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes. All rights reserved.
 * See COPYING.txt for license details.
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\LucideIcons;
use Hyva\Theme\ViewModel\HyvaCsp;
use Hyva\Theme\ViewModel\ReCaptcha;
use Magento\Checkout\Block\Cart\Coupon;
use Magento\Framework\Escaper;

/** @var Coupon $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */
/** @var HyvaCsp $hyvaCsp */
/** @var ReCaptcha $recaptcha */

/** @var LucideIcons $lucideIcons */
$lucideIcons = $viewModels->require(LucideIcons::class);

$showIcon = $block->getShowIcon() ?? true;

// We should use strlen function because coupon code could be "0", converted to bool will lead to false
$hasCouponCode = (bool) strlen($block->getCouponCode() ?: "");
$recaptcha = $block->getData('viewModelRecaptcha');
?>
<script>
    function initCouponForm() {
        return {
            errors: 0,
            hasCaptchaToken: 0,
            showCouponForm: <?= $hasCouponCode ? 1 : 0 ?>,
            formData: {
                coupon_code: '<?= $escaper->escapeJs($block->getCouponCode()) ?>',
                remove: '<?= (int) $hasCouponCode ?>'
            },
            init(){
                const browserStorageShowCouponForm = hyva.getBrowserStorage().getItem('hyva.showCouponForm');
                this.showCouponForm = browserStorageShowCouponForm === 'true' ? true : false;
            },
            toggleShowCoupon() {
                this.showCouponForm = !this.showCouponForm;

                hyva.getBrowserStorage().setItem('hyva.showCouponForm', this.showCouponForm);

                this.$nextTick(() => this.$refs.couponInput.select());
            },
            submitForm() {
                const $form = document.querySelector('#discount-coupon-form');
                <?= $recaptcha ? $recaptcha->getValidationJsHtml(ReCaptcha::RECAPTCHA_FORM_ID_COUPON_CODE) : '' ?>

                if (this.errors === 0) {
                    hyva.postCart($form);
                }
            }
        };
    };

    window.addEventListener('alpine:init', () => {
        Alpine.data('initCouponForm', initCouponForm)
    }, { once: true });
</script>
<?php $hyvaCsp->registerInlineScript() ?>

<details
    class="coupon-form group"
    x-data="initCouponForm()"
    :open="showCouponForm"
>
    <summary
        @click.prevent="toggleShowCoupon"
        class="list-none flex justify-between items-center gap-2 py-2 font-semibold"
    >
        <span class="inline-flex items-center gap-2">
            <?= $showIcon ? $lucideIcons->sparklesHtml('text-primary', 20, 20, ['aria-hidden' => 'true']) : ''; ?>
            <span><?= $escaper->escapeHtml(__('Apply Discount Code')) ?></span>
        </span>
        <?= $lucideIcons->chevronDownHtml('transform group-open:rotate-180', 20, 20, ['aria-hidden' => 'true']); ?>
    </summary>
    <form
        id="discount-coupon-form"
        class="mt-2 mb-4"
        action="<?= $escaper->escapeUrl($block->getUrl('checkout/cart/couponPost')) ?>"
        method="post"
        @submit.prevent="submitForm()"
    >
        <?= $block->getBlockHtml('formkey') ?>
        <label for="coupon_code" class="label sr-only">
            <?= $escaper->escapeHtml(__('Enter discount code')) ?>
        </label>
        <div class="fieldset coupon space-y-2">
            <div class="control">
                <input
                    type="text"
                    id="coupon_code"
                    name="coupon_code"
                    class="form-input w-full"
                    value="<?= $escaper->escapeHtmlAttr($block->getCouponCode()) ?>"
                    x-model="formData.coupon_code"
                    x-ref="couponInput"
                    placeholder="<?= $escaper->escapeHtmlAttr(__('Enter discount code')) ?>"
                    <?php if ($hasCouponCode): ?>
                        disabled
                    <?php else: ?>
                        required
                    <?php endif; ?>
                >
            </div>
            <?php if (!$hasCouponCode): ?>
                <button type="submit" class="btn btn-secondary w-full" value="<?= $escaper->escapeHtmlAttr(__('Apply Discount')) ?>">
                    <?= $escaper->escapeHtml(__('Apply Discount')) ?>
                </button>
            <?php else: ?>
                <input type="hidden" name="remove" id="remove-coupon" value="1">
                <button type="submit" class="btn btn-secondary w-full" value="<?= $escaper->escapeHtmlAttr(__('Cancel Coupon')) ?>">
                    <?= $escaper->escapeHtml(__('Cancel Coupon')) ?>
                </button>
            <?php endif; ?>
            <?= $recaptcha ? $recaptcha->getInputHtml(ReCaptcha::RECAPTCHA_FORM_ID_COUPON_CODE) : '' ?>
            <?php if ($recaptcha && $legalNoticeHtml = $recaptcha->getLegalNoticeHtml(ReCaptcha::RECAPTCHA_FORM_ID_COUPON_CODE)): ?>
                <?= $recaptcha->getLegalNoticeHtml(ReCaptcha::RECAPTCHA_FORM_ID_COUPON_CODE) ?>
            <?php endif; ?>
        </div>
    </form>
</details>