<?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\Customer\LoginButton;
use Hyva\Theme\ViewModel\HyvaCsp;
use Hyva\Theme\ViewModel\LucideIcons;
use Hyva\Theme\ViewModel\ReCaptcha;
use Hyva\Theme\ViewModel\StoreConfig;
use Magento\Customer\Block\Account\Customer;
use Magento\Framework\Escaper;

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

// Do not replace this with $viewModels->require(ReCaptcha::class); that might break the dependency
// on the Magento_ReCaptchaCustomer module
$recaptcha = $block->getData('viewModelRecaptcha');

/** @var LoginButton $loginButtonViewModel */
$loginButtonViewModel = $viewModels->require(LoginButton::class);

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

/** @var StoreConfig $storeConfig */
$storeConfig = $viewModels->require(StoreConfig::class);
$isAutocompleteEnabled = $storeConfig->getStoreConfig('customer/password/autocomplete_on_storefront');

?>
<script>
    function initAuthentication() {
        return {
            open: false,
            close() {
                this.open = false;
            },
            forceAuthentication: false,
            checkoutUrl: '<?= $escaper->escapeUrl($block->getUrl('checkout/index')) ?>',
            errors: 0,
            hasCaptchaToken: 0,
            displayErrorMessage: false,
            errorMessages: [],
            setErrorMessages(message) {
                this.errorMessages = [message];
                this.displayErrorMessage = true;
            },
            submitForm() {
                // Do not rename $form, the variable is expected to be declared in the recaptcha output
                const $form = document.querySelector('#login-form');
                <?= $recaptcha ? $recaptcha->getValidationJsHtml('customer_login', 'auth-popup') : '' ?>

                if (this.errors === 0) {
                    this.dispatchLoginRequest($form);
                }
            },
            onPrivateContentLoaded() {
                const data = this.$event.detail.data;
                const isLoggedIn = data.customer && data.customer.firstname;
                if (data.cart && !isLoggedIn) {
                    this.forceAuthentication = !data.cart.isGuestCheckoutAllowed;
                }
            },
            redirectIfAuthenticated() {
                const event = this.$event;
                this.open = this.forceAuthentication;

                if (event.detail && event.detail.url) {
                    this.checkoutUrl = event.detail.url;
                }
                if (!this.forceAuthentication) {
                    window.location.href = this.checkoutUrl;
                }
            },
            resetErrors() {
                this.errors = 0;
            },
            dispatchLoginRequest(form) {
                this.isLoading = true;
                const username = this.$refs['customer-email'].value;
                const password = this.$refs['customer-password'].value;
                const formKey = hyva.getFormKey();
                const bodyFields = {
                    'username': username,
                    'password': password,
                    'formKey': formKey
                };
                <?php // All recaptcha variants set a input field g-recaptcha-response value ?>
                const fieldName = '<?= $recaptcha
                    ? $escaper->escapeJs($recaptcha->getResultTokenFieldName('customer_login'))
                    : '' ?>';
                const recaptchaField = fieldName && form[fieldName];
                if (recaptchaField) {
                    bodyFields[fieldName] = recaptchaField.value;
                }
                fetch('<?= $escaper->escapeUrl($block->getUrl('customer/ajax/login')) ?>', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: JSON.stringify(bodyFields)
                    }
                ).then(response => {
                        return response.json()
                    }
                ).then(data => {
                    this.isLoading = false;
                    if (data.errors) {
                        this.setErrorMessages(data.message);
                        this.errors = 1;
                        this.hasCaptchaToken = 0;
                    } else {
                        window.location.href = this.checkoutUrl;
                    }
                });
            },
            eventListeners: {
                ['@private-content-loaded.window']() {
                    this.onPrivateContentLoaded();
                },
                ['@toggle-authentication.window']() {
                    this.redirectIfAuthenticated();
                },
                ['@pageshow.window'](event) {
                    if (event.persisted) {
                        this.close();
                    };
                }
            }
        }
    }

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

<dialog
    id="authentication-popup"
    aria-labelledby="authentication-popup-title"
    class="open:flex flex-col transition ease-out duration-300 motion-reduce:duration-0 p-0"
    x-data="initAuthentication"
    x-bind="eventListeners"
    x-show="open"
    x-htmldialog="close"
    closeby="any"
    x-transition
>
    <div class="pt-8 px-8">
        <div class="flex gap-2 justify-between items-center">
            <p id="authentication-popup-title" class="text-xl">
                <strong><?= $escaper->escapeHtml(__('Customer Login')) ?></strong>
            </p>
            <button
                type="button"
                class="btn bg-transparent border-transparent p-2"
                @click="close"
                aria-label="<?= $escaper->escapeHtmlAttr(__('Close panel')) ?>"
            >
                <?= $lucideIcons->xHtml('', 20, 20, ['aria-hidden' => 'true']); ?>
            </button>
        </div>

        <div class="message error" x-show="errors" x-cloak>
            <template x-for="(message, index) in errorMessages" :key="index">
                <div>
                    <template x-if="message">
                        <span x-html="message"></span>
                    </template>
                </div>
            </template>
        </div>
    </div>

    <div class="block-customer-login p-8">
        <p id="authenticate-customer-login" class="text-lg mb-2">
            <strong><?= $escaper->escapeHtml(__('Checkout using your account')) ?></strong>
        </p>

        <form
            id="login-form"
            class="form form-login"
            method="post"
            @submit.prevent="submitForm"
        >
            <?= $recaptcha ? $recaptcha->getInputHtml('customer_login', 'auth-popup') : '' ?>
            <input name="context" type="hidden" value="checkout">

            <div class="flex flex-col gap-4">
                <div class="field email required">
                    <label for="form-login-username">
                        <span><?= $escaper->escapeHtml(__('Email Address')) ?></span>
                    </label>
                    <div class="control">
                        <input
                            id="form-login-username"
                            name="username"
                            type="email"
                            class="form-input w-full"
                            required
                            autocomplete="<?= $isAutocompleteEnabled ? 'email' : 'off' ?>"
                            x-ref="customer-email"
                            @change="resetErrors"
                        >
                    </div>
                </div>
                <div class="field password required">
                    <label for="form-login-password">
                        <span><?= $escaper->escapeHtml(__('Password')) ?></span>
                    </label>
                    <div class="control">
                        <input
                            id="form-login-password"
                            name="password"
                            type="password"
                            class="form-input w-full"
                            required
                            autocomplete="<?= $isAutocompleteEnabled ? 'current-password' : 'off' ?>"
                            x-ref="customer-password"
                            @change="resetErrors"
                        >
                    </div>
                </div>
            </div>

            <div class="actions-toolbar">
                <button
                    type="submit"
                    <?php if ($loginButtonViewModel->disabled()): ?>
                        disabled
                        data-recaptcha-btn
                    <?php endif; ?>
                    class="btn btn-primary"
                >
                    <?= $escaper->escapeHtml(__('Sign In')) ?>
                </button>
                <a
                    href="<?= $escaper->escapeUrl($block->getUrl('customer/account/forgotpassword')) ?>"
                    class="underline hover:no-underline"
                >
                    <?= $escaper->escapeHtml(__('Forgot Your Password?')) ?>
                </a>
            </div>
        </form>
        <?= $recaptcha ? $recaptcha->getLegalNoticeHtml('customer_login') : '' ?>
    </div>
    <div class="block-new-customer p-8 border-t border-gray-300">
        <p id="authenticate-new-customer" class="text-lg mb-2">
            <strong><?= $escaper->escapeHtml(__('Checkout as a new customer')) ?></strong>
        </p>

        <div class="block-content">
            <p class="mb-1">
                <?= $escaper->escapeHtml(__('Creating an account has many benefits:')) ?>
            </p>
            <ul class="list-disc pl-5">
                <li> <?= $escaper->escapeHtml(__('See order and shipping status')) ?></li>
                <li> <?= $escaper->escapeHtml(__('Track order history')) ?></li>
                <li> <?= $escaper->escapeHtml(__('Check out faster')) ?></li>
            </ul>
            <div class="actions-toolbar mt-6 mb-2">
                <a href="<?= $escaper->escapeUrl($block->getUrl('customer/account/create')) ?>"
                    class="inline-flex btn btn-primary">
                    <?= $escaper->escapeHtml(__('Create an Account')) ?>
                </a>
            </div>
        </div>
    </div>
</dialog>
