<?php
// Copyright 1999-2024. Plesk International GmbH. All rights reserved.
?>
<div class='form-row'>
    <div class='field-name'>
        <?php echo $this->elementPart($this->element->getElement($this->subdomainElementName))->label(); ?>
    </div>
    <div class='field-value'>
        <span>
            <?php echo $this->elementPart($this->element->getElement($this->subdomainElementName))->content(); ?>
            <b>.</b>
            <?php if ($this->domainName): ?>
                <b><?php echo $this->domainName; ?> </b>
            <?php else: ?>
                <?php echo $this->elementPart($this->element->getElement($this->domainElementName))->content(); ?>
            <?php endif; ?>
        </span>
        <span class="field-errors" style="display: none;"></span>
        <span class="hint"><?php echo $this->elementPart($this->element->getElement($this->subdomainElementName))->description(); ?></span>
    </div>
</div>
<script>
    (() => {
        const subdomainEl = document.getElementById('<?= $this->element->getElement($this->subdomainElementName)->getId() ?>');
        const domainLookup = <?= $this->domainName ? 'null' : "Jsw.getComponent('" . $this->element->getElement($this->domainElementName)->getId() . "')" ?>;
        const formEl = subdomainEl.closest('form');

        const handleDomainNameChange = () => {
            const domainPrefix = subdomainEl.value;
            const domainSuffix = domainLookup ? domainLookup.getDisplayValue() : <?= $this->jsEscape($this->domainName) ?>;
            const domainName = domainPrefix === '*' ? 'httpdocs' : (domainPrefix && domainSuffix ? domainPrefix + '.' + domainSuffix : '');

            formEl.dispatchEvent(new CustomEvent('domainNameChange', { detail: domainName }));
        };

        ['change', 'keyup'].forEach(eventName => {
            subdomainEl.addEventListener(eventName, handleDomainNameChange);
        });
        if (domainLookup) {
            // Temporary workaround for custom prototype's event 'component:change'
            domainLookup.addEventObserver('dataavailable', handleDomainNameChange);
        }
    })();
</script>
