<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var \Magento\Customer\Block\Form\Register $block */
?>

<?php

$emailActive = $block->getConfig('afd_email/enable/enable') == 1 && $block->getConfig('afd_email/forms/register') == 1;

?>

<?= $block->getChildHtml('form_fields_before') ?>
<?php /* Extensions placeholder */ ?>
<?= $block->getChildHtml('customer.form.register.extra') ?>
<form class="form create account form-create-account" action="<?= $block->escapeUrl($block->getPostActionUrl()) ?>"
      method="post" id="form-validate" enctype="multipart/form-notdata" autocomplete="off">
    <?= /* @noEscape */
    $block->getBlockHtml('formkey'); ?>
    <fieldset class="fieldset create info">
        <legend class="legend"><span><?= $block->escapeHtml(__('Personal Information')) ?></span></legend>
        <br>
        <input type="hidden" name="success_url" value="<?= $block->escapeUrl($block->getSuccessUrl()) ?>">
        <input type="hidden" name="error_url" value="<?= $block->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="<?= $block->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><?= $block->escapeHtml(__('Sign Up for Newsletter')) ?></span></label>
            </div>
            <?php /* Extensions placeholder */ ?>
            <?= $block->getChildHtml('customer.form.register.newsletter') ?>
        <?php endif ?>

        <?php $_dob = $block->getLayout()->createBlock(\Magento\Customer\Block\Widget\Dob::class) ?>
        <?php if ($_dob->isEnabled()) : ?>
            <?= $_dob->setDate($block->getFormData()->getDob())->toHtml() ?>
        <?php endif ?>

        <?php $_taxvat = $block->getLayout()->createBlock(\Magento\Customer\Block\Widget\Taxvat::class) ?>
        <?php if ($_taxvat->isEnabled()) : ?>
            <?= $_taxvat->setTaxvat($block->getFormData()->getTaxvat())->toHtml() ?>
        <?php endif ?>

        <?php $_gender = $block->getLayout()->createBlock(\Magento\Customer\Block\Widget\Gender::class) ?>
        <?php if ($_gender->isEnabled()) : ?>
            <?= $_gender->setGender($block->getFormData()->getGender())->toHtml() ?>
        <?php endif ?>
    </fieldset>
    <?php if ($block->getShowAddressFields()) : ?>
        <fieldset class="fieldset address">
            <legend class="legend"><span><?= $block->escapeHtml(__('Address Information')) ?></span></legend>
            <br>
            <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(\Magento\Customer\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="<?= $block->escapeHtmlAttr($block->getFormData()->getStreet(0)) ?>"
                           title="<?= /* @noEscape */
                           $block->getAttributeData()->getFrontendLabel('street') ?>" id="street_1"
                           class="input-text <?= $block->escapeHtmlAttr($_streetValidationClass) ?>">
                    <div class="nested">
                        <?php $_streetValidationClass = trim(str_replace('required-entry', '', $_streetValidationClass)); ?>
                        <?php for ($_i = 2, $_n = $this->helper(\Magento\Customer\Helper\Address::class)->getStreetLines(); $_i <= $_n; $_i++) : ?>
                            <div class="field additional">
                                <label class="label" for="street_<?= /* @noEscape */
                                $_i ?>">
                                    <span><?= $block->escapeHtml(__('Address')) ?></span>
                                </label>
                                <div class="control">
                                    <input type="text" name="street[]"
                                           value="<?= $block->escapeHtml($block->getFormData()->getStreetLine($_i - 1)) ?>"
                                           title="<?= $block->escapeHtmlAttr(__('Street Address %1', $_i)) ?>"
                                           id="street_<?= /* @noEscape */
                                           $_i ?>"
                                           class="input-text <?= $block->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="<?= $block->escapeHtmlAttr($block->getFormData()->getCity()) ?>"
                           title="<?= /* @noEscape */
                           $block->getAttributeData()->getFrontendLabel('city') ?>"
                           class="input-text <?= $block->escapeHtmlAttr($this->helper(\Magento\Customer\Helper\Address::class)->getAttributeValidationClass('city')) ?>"
                           id="city">
                </div>
            </div>

            <div class="field region required">
                <label for="region_id" class="label"><span><?= /* @noEscape */
                        $block->getAttributeData()->getFrontendLabel('region') ?></span></label>
                <div class="control">
                    <select id="region_id" name="region_id" title="<?= /* @noEscape */
                    $block->getAttributeData()->getFrontendLabel('region') ?>" class="validate-select region_id"
                            style="display:none;">
                        <option value=""><?= $block->escapeHtml(__('Please select a region, state or province.')) ?></option>
                    </select>
                    <input type="text" id="region" name="region" value="<?= $block->escapeHtml($block->getRegion()) ?>"
                           title="<?= /* @noEscape */
                           $block->getAttributeData()->getFrontendLabel('region') ?>"
                           class="input-text <?= $block->escapeHtmlAttr($this->helper(\Magento\Customer\Helper\Address::class)->getAttributeValidationClass('region')) ?>"
                           style="display:none;">
                </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="<?= $block->escapeHtmlAttr($block->getFormData()->getPostcode()) ?>"
                           title="<?= /* @noEscape */
                           $block->getAttributeData()->getFrontendLabel('postcode') ?>" id="zip"
                           class="input-text validate-zip-international <?= $block->escapeHtmlAttr($this->helper(\Magento\Customer\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">
                    <?= $block->getCountryHtmlSelect() ?>
                </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; ?>
    <fieldset class="fieldset create account" data-hasrequired="<?= $block->escapeHtmlAttr(__('* Required Fields')) ?>">
        <legend class="legend"><span><?= $block->escapeHtml(__('Sign-in Information')) ?></span></legend>
        <br>
        <div class="field required">
            <label for="email_address" class="label"><span><?= $block->escapeHtml(__('Email')) ?></span></label>
            <div class="control">
                <input type="email" name="email" autocomplete="email" id="email_address"
                       value="<?= $block->escapeHtmlAttr($block->getFormData()->getEmail()) ?>"
                       title="<?= $block->escapeHtmlAttr(__('Email')) ?>" class="input-text"
                       data-mage-init='{"mage/trim-input":{}}'
                       data-validate="{required:true, 'validate-email':true<?php echo $emailActive ? ", 'afdEmailCheck': true" : "" ?>} " <?php echo $emailActive ? 'data-afd-additional-options="afdEmailOptions"'  : "" ?>>
            </div>
        </div>

        <div class="field password required">
            <label for="password" class="label"><span><?= $block->escapeHtml(__('Password')) ?></span></label>
            <div class="control">
                <input type="password" name="password" id="password"
                       title="<?= $block->escapeHtmlAttr(__('Password')) ?>"
                       class="input-text"
                       data-password-min-length="<?= $block->escapeHtmlAttr($block->getMinimumPasswordLength()) ?>"
                       data-password-min-character-sets="<?= $block->escapeHtmlAttr($block->getRequiredCharacterClassesNumber()) ?>"
                       data-validate="{required:true, 'validate-customer-password':true}"
                       autocomplete="off">
                <div id="password-strength-meter-container" data-role="password-strength-meter" aria-live="polite">
                    <div id="password-strength-meter" class="password-strength-meter">
                        <?= $block->escapeHtml(__('Password Strength')) ?>:
                        <span id="password-strength-meter-label" data-role="password-strength-meter-label">
                            <?= $block->escapeHtml(__('No Password')) ?>
                        </span>
                    </div>
                </div>
            </div>

        </div>
        <div class="field confirmation required">
            <label for="password-confirmation"
                   class="label"><span><?= $block->escapeHtml(__('Confirm Password')) ?></span></label>
            <div class="control">
                <input type="password" name="password_confirmation"
                       title="<?= $block->escapeHtmlAttr(__('Confirm Password')) ?>" id="password-confirmation"
                       class="input-text" data-validate="{required:true, equalTo:'#password'}" autocomplete="off">
            </div>
        </div>
        <?= $block->getChildHtml('form_additional_info') ?>
    </fieldset>
    <div class="actions-toolbar">
        <div class="primary">
            <button type="submit" class="action submit primary"
                    title="<?= $block->escapeHtmlAttr(__('Create an Account')) ?>">
                <span><?= $block->escapeHtml(__('Create an Account')) ?></span></button>
        </div>
        <div class="secondary">
            <a class="action back"
               href="<?= $block->escapeUrl($block->getBackUrl()) ?>"><span><?= $block->escapeHtml(__('Back')) ?></span></a>
        </div>
    </div>
</form>
<script>
    require([
        'jquery',
        'mage/mage'
    ], function ($) {

        var dataForm = $('#form-validate');
        var ignore = <?= /* @noEscape */ $_dob->isEnabled() ? '\'input[id$="full"]\'' : 'null' ?>;

        dataForm.mage('validation', {
            <?php if ($_dob->isEnabled()) : ?>
            errorPlacement: function (error, element) {
                if (element.prop('id').search('full') !== -1) {
                    var dobElement = $(element).parents('.customer-dob'),
                        errorClass = error.prop('class');
                    error.insertAfter(element.parent());
                    dobElement.find('.validate-custom').addClass(errorClass)
                        .after('<div class="' + errorClass + '"></div>');
                } else {
                    error.insertAfter(element);
                }
            },
            ignore: ':hidden:not(' + ignore + ')'
            <?php else : ?>
            ignore: ignore ? ':hidden:not(' + ignore + ')' : ':hidden'
            <?php endif ?>
        }).find('input:text').attr('autocomplete', 'off');

    });
</script>
<?php if ($block->getShowAddressFields()) : ?>
    <script type="text/x-magento-init">
    {
        "#country": {
            "regionUpdater": {
                "optionalRegionAllowed": <?= /* @noEscape */
        $block->getConfig('general/region/display_all') ? 'true' : 'false' ?>,
                "regionListId": "#region_id",
                "regionInputId": "#region",
                "postcodeId": "#zip",
                "form": "#form-validate",
                "regionJson": <?= /* @noEscape */
        $this->helper(\Magento\Directory\Helper\Data::class)->getRegionJson() ?>,
                "defaultRegion": "<?= (int)$block->getFormData()->getRegionId() ?>",
                "countriesWithOptionalZip": <?= /* @noEscape */
        $this->helper(\Magento\Directory\Helper\Data::class)->getCountriesWithOptionalZip(true) ?>
            }
        }
    }

    </script>
<?php endif; ?>

<script type="text/x-magento-init">
    {
        ".field.password": {
            "passwordStrengthIndicator": {
                "formSelector": "form.form-create-account"
            }
        }
    }

</script>
<?php if($emailActive): ?>
<script type="text/javascript">
    require(['jquery', 'mage/validation', 'afdPce'], function ($) {
        window.afdEmailOptions = {};
        
        <?php if($block->getConfig('afd_email/account/useDefaultCredentials') == 0): ?>
            <?php if($block->getConfig('afd_email/account/authMethod') == "id"): ?>
                afdEmailOptions.pceUrl = '<?php echo $block->getConfig('afd_email/account/idPceUrl'); ?>';
                afdEmailOptions.id = '<?php echo $block->getConfig('afd_email/account/id'); ?>';
                afdEmailOptions.token = '<?php echo $block->getConfig('afd_email/account/token'); ?>';
                afdEmailOptions.serial = null;
                afdEmailOptions.password = null;
            <?php else: ?>
                afdEmailOptions.pceUrl = '<?php echo $block->getConfig('afd_email/account/serialPceUrl'); ?>';
                afdEmailOptions.serial = '<?php echo $block->getConfig('afd_email/account/serial'); ?>';
                afdEmailOptions.password = '<?php echo $block->getConfig('afd_email/account/password'); ?>';
                afdEmailOptions.id = null;
                afdEmailOptions.token = null;
            <?php endif; ?>
        <?php endif; ?>
        $('#email_address').afd('email')

        let validationTimeout;
        const VALIDATION_TIMEOUT_MS = 10000; // 10 seconds
        let emailValidationInProgress = false;
        
        $.validator.addMethod("afdEmailCheck", function(value, element) {
            const isValid = $(element).data('afd-email-valid');
            // Require explicit true - undefined or false both fail validation
            // This prevents form submission when validation hasn't completed
            return isValid === true;
        }, afdOptions.email.invalidEmailMessage);
        
        $('#email_address').on('afd:emailValidationUpdatedFocusOut',function(e, $el) {
            clearTimeout(validationTimeout);
            emailValidationInProgress = false;
            
            $el.data('afd-email-valid',
                $el.data('email-is-afd-valid')
                && $el.data('email-syntax-valid')
            ).valid();
        });
        
        // Add timeout handler to prevent indefinite blocking
        $(document).on('afd:emailValidationStarted', function(e, el) {
            const $el = $(el);
            emailValidationInProgress = true;
            
            clearTimeout(validationTimeout);
            validationTimeout = setTimeout(function() {
                // If validation hasn't completed after timeout, mark as timed out but allow submission
                console.warn('Email validation timed out after ' + VALIDATION_TIMEOUT_MS + 'ms');
                emailValidationInProgress = false;
                // Set to true on timeout to allow form submission (graceful degradation)
                $el.data('afd-email-valid', true);
                $el.closest('form').find('button').attr('disabled', false);
                $el.closest('.afd-loading').removeClass('afd-loading');
            }, VALIDATION_TIMEOUT_MS);
        });
        
        // Clear timeout on success
        $(document).on('afd:emailValidationSuccess', function() {
            clearTimeout(validationTimeout);
            emailValidationInProgress = false;
        });
        
        // Handle validation errors gracefully
        $(document).on('afd:emailValidationError', function(e, error) {
            clearTimeout(validationTimeout);
            emailValidationInProgress = false;
            console.error('Email validation error:', error);
            // Set to true on error to allow form submission (graceful degradation)
            $('#email_address').data('afd-email-valid', true);
            $('#email_address').closest('form').find('button').attr('disabled', false);
            $('#email_address').closest('.afd-loading').removeClass('afd-loading');
        });
        
        // Block form submission if email validation is in progress
        $('#form-validate').on('submit', function(e) {
            const $emailField = $('#email_address');
            const isValid = $emailField.data('afd-email-valid');
            
            // Block if validation is in progress
            if (emailValidationInProgress) {
                e.preventDefault();
                return false;
            }
            
            // Block if email has a value but hasn't been validated yet (isValid is undefined)
            if ($emailField.val() && isValid !== true) {
                e.preventDefault();
                // Trigger focus out to start validation
                $emailField.trigger('focusout');
                return false;
            }
            
            return true;
        });

    })
</script>
<?php endif; ?>
