<?php
declare(strict_types=1);

use Magento\Customer\Block\Form\Register;
use Magento\Customer\Block\Widget\Dob;
use Magento\Customer\Block\Widget\Gender;
use Magento\Customer\Block\Widget\Taxvat;
use Magento\Customer\Helper\Address;
use Magento\Framework\Escaper;
use Hyva\Theme\ViewModel\ReCaptcha;

// phpcs:disable Magento2.Templates.ThisInTemplate.FoundHelper
// phpcs:disable Generic.Files.LineLength.TooLong

/** @var Register $block */
/** @var Escaper $escaper */

$formId = 'accountcreate';

/** @var ReCaptcha $recaptchaViewModel */
//Do not replace this with $viewModels->require(ReCaptcha::class); that might break the dependency on
//Magento's Recaptcha module
$recaptchaViewModel = $block->getData('viewModelRecaptcha');
$recaptchaInputFieldBlock = '';
$recaptchaLegalNoticeBlock = '';
if ($recaptchaViewModel !== null && $recaptchaData = $recaptchaViewModel->getRecaptchaData('customer_create')) {
    $recaptchaInputFieldBlock = $recaptchaData[ReCaptcha::RECAPTCHA_INPUT_FIELD];
    $recaptchaLegalNoticeBlock = $recaptchaData[ReCaptcha::RECAPTCHA_LEGAL_NOTICE_BLOCK];
}
$region = $block->getAttributeData()->getFrontendLabel('region');
$selectRegion = 'Please select a region, state or province.';
$displayAll = $block->getConfig('general/region/display_all');
?>
<div class="mb-8">
    <?php /* Extensions placeholder */ ?>
    <?= $block->getChildHtml('customer.form.register.extra') ?>
    <form class="form create account form-create-account"
          action="<?= $escaper->escapeUrl($block->getPostActionUrl()) ?>"
          x-data="initForm()"
          <?php if ($block->getShowAddressFields()): ?>
          @private-content-loaded.window="onPrivateContentLoaded(event.detail.data)"
          <?php endif; ?>
          id="<?= $escaper->escapeHtmlAttr($formId) ?>"
          @submit.prevent="submitForm()"
          method="post" id="form-validate" enctype="multipart/form-data" autocomplete="off">
        <?= /* @noEscape */ $block->getBlockHtml('formkey'); ?>
        <?= $block->getChildHtml('form_fields_before') ?>
        <?= $block->getBlockHtml($recaptchaInputFieldBlock) ?>
        <div class="grid-cols-2 gap-4 md:grid">
            <fieldset class="my-8">
                <legend class="contents">
                    <span>
                        <?= $escaper->escapeHtml(__('Personal Information')) ?>
                    </span>
                </legend>
                <input type="hidden" name="success_url" value="<?= $escaper->escapeUrl($block->getSuccessUrl()) ?>">
                <input type="hidden" name="error_url" value="<?= $escaper->escapeUrl($block->getErrorUrl()) ?>">
                <?= $block->getLayout()->createBlock(\Magento\Customer\Block\Widget\Name::class)->setObject(
                    $block->getFormData()
                )->setForceUseCustomerAttributes(true)->toHtml() ?>
                <?php if ($block->isNewsletterEnabled()): ?>
                    <div class="field choice newsletter">
                        <input type="checkbox" name="is_subscribed"
                               title="<?= $escaper->escapeHtmlAttr(__('Sign Up for Newsletter')) ?>" value="1"
                               id="is_subscribed"
                                <?php if ($block->getFormData()->getIsSubscribed()): ?>
                                    checked="checked"
                                <?php endif; ?>
                               class="checkbox">
                        <label for="is_subscribed" class="label">
                            <span>
                                <?= $escaper->escapeHtml(__('Sign Up for Newsletter')) ?>
                            </span>
                        </label>
                    </div>
                    <?php /* Extensions placeholder */ ?>
                    <?= $block->getChildHtml('customer.form.register.newsletter') ?>
                <?php endif ?>

                <?php $dob = $block->getLayout()->createBlock(Dob::class) ?>
                <?php if ($dob->isEnabled()): ?>
                    <?= $dob->setDate($block->getFormData()->getDob())->toHtml() ?>
                <?php endif ?>

                <?php $taxvat = $block->getLayout()->createBlock(Taxvat::class) ?>
                <?php if ($taxvat->isEnabled()): ?>
                    <?= $taxvat->setTaxvat($block->getFormData()->getTaxvat())->toHtml() ?>
                <?php endif ?>

                <?php $gender = $block->getLayout()->createBlock(Gender::class) ?>
                <?php if ($gender->isEnabled()): ?>
                    <?= $gender->setGender($block->getFormData()->getGender())->toHtml() ?>
                <?php endif ?>
                <?= $block->getChildHtml('fieldset_create_info_additional') ?>
            </fieldset>
            <fieldset class="my-8">
                <legend class="contents">
                    <span>
                        <?= $escaper->escapeHtml(__('Sign-in Information')) ?></span>
                </legend>
                <div class="field required">
                    <label for="email_address" class="label">
                        <span>
                            <?= $escaper->escapeHtml(__('Email')) ?>
                        </span>
                    </label>
                    <div class="control">
                        <input type="email" name="email" autocomplete="email" id="email_address" required
                               value="<?= $escaper->escapeHtmlAttr($block->getFormData()->getEmail()) ?>"
                               title="<?= $escaper->escapeHtmlAttr(__('Email')) ?>" class="form-input" />
                    </div>
                </div>
                <div class="field required">
                    <label for="password" class="label"><span><?= $escaper->escapeHtml(__('Password')) ?></span></label>
                    <div class="control">
                        <?php $minimumPasswordLength = $block->getMinimumPasswordLength() ?>
                        <input type="password" name="password" id="password"
                               title="<?= $escaper->escapeHtmlAttr(__('Password')) ?>"
                               minlength="<?= $escaper->escapeHtmlAttr($minimumPasswordLength) ?>"
                               class="form-input"
                               required
                               x-on:change="checkPasswordsMatch()"
                               autocomplete="off">
                    </div>
                    <p class="mt-3 text-sm font-medium text-black">
                        <?= $escaper->escapeHtml(
                            __(
                                'Minimum of different classes of characters in password is %1.'
                                . ' Classes of characters: Lower Case, Upper Case, Digits, Special Characters.',
                                $block->getRequiredCharacterClassesNumber()
                            )
                        ) ?>
                    </p>
                </div>
                <div class="field required">
                    <label for="password-confirmation" class="label">
                        <span>
                            <?= $escaper->escapeHtml(__('Confirm Password')) ?>
                        </span>
                    </label>
                    <div class="control">
                        <input type="password" name="password_confirmation"
                               title="<?= $escaper->escapeHtmlAttr(__('Confirm Password')) ?>"
                               id="password-confirmation"
                               x-on:change="checkPasswordsMatch()"
                               x-on:keyup="checkPasswordsMatch()"
                               required
                               minlength="<?= $escaper->escapeHtmlAttr($minimumPasswordLength) ?>"
                               class="form-input"
                               autocomplete="off">
                    </div>
                </div>
                <div class="field">
                <p class="my-4 text-red" :class="passwordsMatching ? 'invisible' : 'visible'">
                    <?= $escaper->escapeHtml(__('Your password confirmation must match your password.')) ?>
                </p>
                </div>
                <?= $block->getChildHtml('form_additional_info') ?>
                <?= $block->getBlockHtml($recaptchaLegalNoticeBlock) ?>
            </fieldset>
        </div>

        <?php if ($block->getShowAddressFields()): ?>
            <fieldset class="my-8">
                <p class="mb-8 font-lg text-secondary-darker">
                    <span>
                        <?= $escaper->escapeHtml(__('Address Information')) ?>
                    </span>
                </p>
                <input type="hidden" name="create_address" value="1"/>

                <?php $company = $block->getLayout()->createBlock(\Magento\Customer\Block\Widget\Company::class) ?>
                <?php if ($company->isEnabled()): ?>
                    <?= $company->setCompany($block->getFormData()->getCompany())->toHtml() ?>
                <?php endif ?>

                <?php $telephone = $block->getLayout()->createBlock(\Magento\Customer\Block\Widget\Telephone::class) ?>
                <?php if ($telephone->isEnabled()): ?>
                    <?= $telephone->setTelephone($block->getFormData()->getTelephone())->toHtml() ?>
                <?php endif ?>

                <?php $fax = $block->getLayout()->createBlock(\Magento\Customer\Block\Widget\Fax::class) ?>
                <?php if ($fax->isEnabled()): ?>
                    <?= $fax->setFax($block->getFormData()->getFax())->toHtml() ?>
                <?php endif ?>
                <?php $streetValidationClass =
                    $this->helper(Address::class)->getAttributeValidationClass(
                        'street'
                    ); ?>
                <div class="field street required">
                    <label for="street_1" class="label"><span><?= /* @noEscape */
                            $block->getAttributeData()->getFrontendLabel('street') ?></span></label>
                    <div class="control">
                        <input type="text" name="street[]"
                               value="<?= $escaper->escapeHtmlAttr($block->getFormData()->getStreet(0)) ?>"
                               title="<?= /* @noEscape */ $block->getAttributeData()->getFrontendLabel('street') ?>"
                               id="street_1"
                               class="form-input <?= $escaper->escapeHtmlAttr($streetValidationClass) ?>">
                        <div class="nested">
                            <?php $streetValidationClass =
                                trim(str_replace('required-entry', '', $streetValidationClass)); ?>
                            <?php for ($i = 2, $n = $this->helper(Address::class)->getStreetLines(); $i <= $n; $i++): ?>
                                <div class="field additional">
                                    <label class="label" for="street_<?= /* @noEscape */ $i ?>">
                                        <span><?= $escaper->escapeHtml(__('Address')) ?></span>
                                    </label>
                                    <div class="control">
                                        <input type="text" name="street[]"
                                               value="<?= $escaper->escapeHtmlAttr($block
                                                   ->getFormData()
                                                   ->getStreetLine($i - 1)) ?>"
                                               title="<?= $escaper
                                                   ->escapeHtmlAttr(__('Street Address %1', $i)) ?>"
                                               id="street_<?= (int) $i ?>"
                                               class="form-input <?= $escaper
                                                   ->escapeHtmlAttr($streetValidationClass) ?>"
                                        >
                                    </div>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>

                <div class="field required">
                    <label for="city" class="label">
                        <span>
                            <?= /* @noEscape */ $block->getAttributeData()->getFrontendLabel('city') ?>
                        </span>
                    </label>
                    <div class="control">
                        <input type="text" name="city"
                               value="<?= $escaper->escapeHtmlAttr($block->getFormData()->getCity()) ?>"
                               title="<?= /* @noEscape */ $block->getAttributeData()->getFrontendLabel('city') ?>"
                               class="form-input <?= $escaper->escapeHtmlAttr($this
                                   ->helper(Address::class)
                                   ->getAttributeValidationClass('city')) ?>"
                               id="city">

                    </div>
                </div>

                <div class="w-full field region"
                     x-cloak
                     x-show="isRegionRequired || showOptionalRegion"
                >
                    <label class="label" for="region_id">
                        <span><?= /* @noEscape */ $region ?></span>
                    </label>
                    <div class="control">
                        <template x-if="hasAvailableRegions() && isRegionRequired">
                            <select id="region_id" name="region_id"
                                    title="<?= /* @noEscape */ $region ?>"
                                    class="form-select validate-select region_id"
                                    :required="isRegionRequired"
                                    x-ref="region_id"
                                    x-model="selectedRegion"
                            >
                                <option value=""><?= $escaper->escapeHtml(__($selectRegion)) ?></option>
                                <template x-for="regionId in Object.keys(availableRegions)">
                                    <option :value="regionId"
                                            :name="availableRegions[regionId].name"
                                            x-text="availableRegions[regionId].name"
                                            :selected="selectedRegion === regionId"
                                    >
                                    </option>
                                </template>
                            </select>
                        </template>
                        <template x-if="!hasAvailableRegions()">
                            <input type="text"
                                   id="region"
                                   name="region"
                                   x-ref="region"
                                   value="<?= $escaper->escapeHtmlAttr($block->getRegion()) ?>"
                                   title="<?= /* @noEscape */ $region ?>"
                                   class="form-input"
                                   :required="isRegionRequired"
                            />
                        </template>
                    </div>
                </div>

                <div class="field zip required">
                    <label for="zip" class="label"><span><?= /* @noEscape */
                            $block->getAttributeData()->getFrontendLabel('postcode') ?></span></label>
                    <div class="control">
                        <input type="text"
                               name="postcode"
                               value="<?= $escaper->escapeHtmlAttr($block->getFormData()->getPostcode()) ?>"
                               title="<?= /* @noEscape */ $block->getAttributeData()->getFrontendLabel('postcode') ?>"
                               id="zip"
                               class="form-input validate-zip-international
                                    <?= $escaper->escapeHtmlAttr(
                                        $this->helper(Address::class)->getAttributeValidationClass(
                                            'postcode'
                                        )
                                    ) ?>">
                    </div>
                </div>

                <div class="field country required">
                    <label for="country" class="label"><span><?= /* @noEscape */
                            $block->getAttributeData()->getFrontendLabel('country_id') ?></span></label>
                    <div class="control">
                        <?php $countries = $block
                            ->getCountryCollection()
                            ->setForegroundCountries($block->getTopDestinations())
                            ->toOptionArray();
                        ?>
                        <select name="country_id"
                                id="country"
                                title="Country"
                                required="required"
                                class="form-select"
                                x-ref="country_id"
                                @change="changeCountry($event.target)"
                        >
                            <?php foreach ($countries as $country): ?>
                                <option name="<?= /** @noEscape */ $country['label'] ?>"
                                        value="<?= /** @noEscape */ $country['value'] ?>"
                                        data-is-zip-required="<?= (isset($country['is_zipcode_optional'])) ? '0' : '1' ?>"
                                        data-is-region-required="<?= (isset($country['is_region_required'])) ? '1' : '0' ?>"
                                    <?= ($block->getCountryId() ===  $country['value']) ? 'selected="selected"' : '' ?>
                                >
                                    <?= /** @noEscape */ $country['label'] ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <?php $addressAttributes = $block->getChildBlock('customer_form_address_user_attributes'); ?>
                <?php if ($addressAttributes): ?>
                    <?php $addressAttributes->setEntityType('customer_address'); ?>
                    <?php $addressAttributes->setFieldIdFormat('address:%1$s')->setFieldNameFormat(
                        'address[%1$s]'
                    ); ?>
                    <?php $block->restoreSessionData($addressAttributes->getMetadataForm(), 'address'); ?>
                    <?= $addressAttributes->setShowContainer(false)->toHtml() ?>
                <?php endif; ?>
                <input type="hidden" name="default_billing" value="1">
                <input type="hidden" name="default_shipping" value="1">
            </fieldset>
        <?php endif; ?>
        <div class="flex actions-toolbar">
            <div class="primary">
                <button type="submit" class="action submit primary btn btn-primary"
                        title="<?= $escaper->escapeHtmlAttr(__('Create an Account')) ?>"><span><?= $escaper->escapeHtml(
                            __('Create an Account')
                        ) ?></span></button>
            </div>
            <div class="self-center ml-4 secondary">
                <a class="action back"
                   href="<?= $escaper->escapeUrl($block->getBackUrl()) ?>">
                    <span>
                        <?= $escaper->escapeHtml(__('Back')) ?>
                    </span>
                </a>
            </div>
        </div>
    </form>

    <script>
        function initForm() {
            return {
                passwordsMatching: true,
                errors: 0,
                hasCaptchaToken: 0,
                checkPasswordsMatch() {
                    if (document.getElementById('password').value ===
                        document.getElementById('password-confirmation').value) {
                            this.passwordsMatching = true;
                            return true;
                        }
                    this.passwordsMatching = false;
                    return false;
                },
                submitForm() {
                    if (this.checkPasswordsMatch()) {
                        // Do not rename $form, it is expected to be declared in the child block output
                        const $form = document.querySelector('#<?= $escaper->escapeJs($formId) ?>');
                        <?= $block->getChildHtml('recaptcha_validation'); ?>

                        if (this.errors === 0) {
                            $form.submit();
                        }
                    }
                },
                <?php if ($block->getShowAddressFields()): ?>
                directoryData: {},
                availableRegions: {},
                selectedRegion: <?= $escaper->escapeJs($block->getRegion() ?: 0) ?>,
                isZipRequired: true,
                isRegionRequired: true,
                showOptionalRegion: <?= $displayAll ? 'true': 'false' ?>,
                onPrivateContentLoaded(data) {
                    this.directoryData = data['directory-data'] || {};

                    <?php if ($block->getCountryId()): ?>
                    this.changeCountry(this.$refs['country_id']);
                    <?php endif; ?>

                    this.setInitialRegionSelectValue();
                    this.setRegionInputValue('<?= $escaper->escapeHtmlAttr($block->getRegion()) ?>');

                },
                setInitialRegionSelectValue(value) {
                    this.$nextTick(() => {
                        const regionSelectorElement = this.$refs['region_id'];
                        if (regionSelectorElement) {

                            const regionOptionByValue = regionSelectorElement
                                .querySelector("[name='<?= /** @noEscape */ $block->getRegion() ?>']");

                            if (regionOptionByValue) {
                                this.$refs['region_id'].value = regionOptionByValue.value;
                            }
                        }
                    })
                },
                setRegionInputValue(value) {
                    this.$nextTick(() => {
                        const regionInputElement = this.$refs['region'];
                        if (regionInputElement) {
                            regionInputElement.value = value;
                        }
                    })
                },
                changeCountry(countrySelectElement) {
                    const selectedOption = countrySelectElement.options[countrySelectElement.selectedIndex];
                    const countryCode = countrySelectElement.value;
                    const countryData = this.directoryData[countryCode] || false;

                    this.setRegionInputValue('');

                    if (!countryData) {
                        return;
                    }

                    this.isZipRequired = selectedOption.dataset.isZipRequired === "1";
                    this.isRegionRequired = selectedOption.dataset.isRegionRequired === "1";

                    this.availableRegions = countryData.regions || {};
                },
                hasAvailableRegions() {
                    return Object.keys(this.availableRegions).length > 0;
                }
                <?php endif; ?>
            }
        }
    </script>
</div>
