{% set periods = guest.system_periods %}
{% set pricing = product.pricing %}
{% set transfer_tlds = guest.serviceDomain_tlds({ "allow_transfer": 1 }) %}
{% set tlds = guest.serviceDomain_tlds({"allow_register":1}) %}
<div class="d-flex mb-3">
    <nav class="nav nav-pills flex-column border-end me-3 gap-2">
        {% if tlds is not empty %}
            <a class="nav-link me-3 py-1 px-2 fs-7 active" href="#" id="register-tab" data-bs-toggle="tab" data-bs-target="#register-tab-pane"
                role="tab" aria-controls="register-tab-pane">{{ 'Register'|trans }}</a>
        {% endif %}
        {% if transfer_tlds is not empty %}
        <a class="nav-link me-3 py-1 px-2 fs-7 {% if tlds is empty %} active {% endif %}" href="#" id="transfer-tab" data-bs-toggle="tab" data-bs-target="#transfer-tab-pane"
               role="tab" aria-controls="transfer-tab-pane">{{ 'Transfer'|trans }}</a>
        {% endif %}
    </nav>
    <div class="tab-content">
        {% if tlds is not empty %}
            <div class="tab-pane show active" id="register-tab-pane" role="tabpanel" aria-labelledby="register-tab" tabindex="0">
                <div class="row">
                    <div class="col-sm-12">
                        <label class="form-label">{{ 'Register a new domain'|trans }}</label>
                        <div class="d-flex gap-2">
                            <div class="input-group" style="max-width: 500px;">
                                <input class="form-control form-control-sm" type="text" name="register_sld"
                                    value="{{ request.register_sld }}"
                                    placeholder="{{ 'Enter new domain name to register'|trans }}">
                                <select class="form-select form-select-sm" name="register_tld" style="width: 30%; max-width: 120px;">
                                    {% for tld in tlds %}
                                        <option value="{{ tld.tld }}" label="{{ tld.tld }}">{{ tld.tld }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <button class="btn btn-sm btn-dark" type="button" id="domain-check">{{ 'Check'|trans }}</button>
                        </div>
                    </div>
                    <div class="c">
                        <div class="onAfterDomainCheck" style="display:none;">
                            <label class="mt-2">
                                <select class="form-select form-select-sm" name="register_years" id="registration-years"></select>
                            </label>
                            <br/>
                            <div class="form-check form-switch my-3">
                                <input class="form-check-input" type="checkbox" role="switch" id="nameserversCb">
                                <label class="form-check-label text-sm" for="nameserversCb">
                                    {{ 'I want to use my nameservers'|trans }}
                                </label>
                            </div>
                            <div id="nameservers" class="flex-column row" style="display:none;">
                                <div class="mb-2 col-md-6">
                                    <input class="form-control form-control-sm" type="text" name="ns1" value="" placeholder="{{ 'Nameserver 1'|trans }}"/>
                                </div>
                                <div class="mb-2 col-md-6">
                                    <input class="form-control form-control-sm" type="text" name="ns2" value="" placeholder="{{ 'Nameserver 2'|trans }}"/>
                                </div>
                                <div class="mb-2 col-md-6">
                                    <input class="form-control form-control-sm" type="text" name="ns3" value="" placeholder="{{ 'Nameserver 3'|trans }}"/>
                                </div>
                                <div class="mb-2 col-md-6">
                                    <input class="form-control form-control-sm" type="text" name="ns4" value="" placeholder="{{ 'Nameserver 4'|trans }}"/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        {% endif %}
        {% if transfer_tlds is not empty %}
            <div class="tab-pane {% if tlds is empty %} show active {% endif %}" id="transfer-tab-pane" role="tabpanel" aria-labelledby="transfer-tab" tabindex="0">
                <div class="row">
                    <div class="col-sm-12">
                        <label class="form-label">{{ 'Transfer a new domain'|trans }}</label>
                        <div class="d-flex gap-2">
                            <div class="input-group" style="max-width: 500px;">
                                <input class="form-control form-control-sm" type="text" name="transfer_sld"
                                       value="{{ request.transfer_sld }}"
                                       placeholder="{{ 'Enter your domain name to transfer'|trans }}">
                                <select class="form-select form-select-sm" name="transfer_tld" style="width: 30%; max-width: 120px;">
                                    {% for tld in transfer_tlds %}
                                        <option value="{{ tld.tld }}" label="{{ tld.tld }}">{{ tld.tld }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <button class="btn btn-sm btn-dark" type="button" id="transfer-check">{{ 'Check'|trans }}</button>
                        </div>
                    </div>
                    <div id="domain-transfer-config" style="display:none;">
                        <p class="fs-7 mt-2">{{ 'Transfer price is'|trans }}&nbsp;<span class="fw-bold" id="transfer-price"></span></p>
                        <input class="form-control form-control-sm" type="text" name="transfer_code" value="{{ request.transfer_code }}"
                               style="width: 200px" placeholder="{{ 'Enter domain transfer code'|trans }}">
                    </div>
                </div>
            </div>
        {% endif %}
    </div>
</div>

<input type="hidden" name="id" value="{{ product.id }}"/>
<input type="hidden" name="action" value="register" id="domain-action"/>

{% set currency = guest.cart_get_currency %}
<script type="text/javascript">
    function fadeIn(el) {
        el.style.removeProperty('display');
        el.style.opacity = '0';
        el.style.transition = 'opacity 0.15s ease-in';
        requestAnimationFrame(() => el.style.opacity = '1');
    }

    function slideDown(el) {
        el.style.removeProperty('display');
        el.style.overflow = 'hidden';
        el.style.height = '0';
        el.style.transition = 'height 0.2s ease-out';
        requestAnimationFrame(() => el.style.height = el.scrollHeight + 'px');
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('ul.nav.nav-tabs > li.domain-tab a').forEach(a => {
            a.addEventListener('click', function () {
                document.getElementById('domain-action').value = this.getAttribute('rel');
            });
        });

        const configNext = document.getElementById('config-next');
        configNext.style.display = 'none';
        configNext.disabled = true;

        const addons = document.querySelector('.addons');
        if (addons) {
            const orderButton = document.querySelector('.order-button');
            if (orderButton) {
                orderButton.addEventListener('click', function () {
                    this.style.display = 'none';
                    slideDown(addons);
                    return false;
                });
            }
        }

        document.querySelectorAll('.addon-period-selector').forEach(el => {
            el.addEventListener('change', function () {
                const r = this.getAttribute('rel');
                const spans = document.querySelectorAll('#' + r + ' span');
                spans.forEach(span => span.style.display = 'none');
                const visibleSpan = document.querySelector('#' + r + ' span.' + this.value);
                if (visibleSpan) {
                    fadeIn(visibleSpan);
                }
            });
            el.dispatchEvent(new Event('change'));
        });

        const formatCurrency = (price, rate, code, multiply) => {
            let total = parseFloat(price) * parseFloat(rate);
            if (typeof multiply !== 'undefined') {
                total *= multiply;
            }
            return new Intl.NumberFormat(undefined, {
                style: 'currency',
                currency: code,
                currencyDisplay: 'narrowSymbol',
            }).format(total);
        };

        const transferCheck = document.getElementById('transfer-check');
        if (transferCheck) {
            transferCheck.addEventListener('click', function (event) {
                const sld = document.querySelector('input[name="transfer_sld"]').value.toLowerCase();
                const tld = document.querySelector('select[name="transfer_tld"]').value.toLowerCase();
                document.getElementById('domain-action').value = 'transfer';
                const domain = sld + tld;

                FOSSBilling.api.guest.post(
                    'servicedomain/can_be_transferred',
                    {sld: sld, tld: tld},
                    function (result) {
                        setTransferPricing(tld);
                        const domainNameEl = document.getElementById('domain-name');
                        if (domainNameEl) domainNameEl.textContent = domain;
                        const transferConfig = document.getElementById('domain-transfer-config');
                        if (transferConfig) fadeIn(transferConfig);
                        const onAfterDomainCheck = document.querySelector('.onAfterDomainCheck');
                        if (onAfterDomainCheck) fadeIn(onAfterDomainCheck);

                        const transferOrderButton = document.querySelector('#transfer .order-button');
                        if (transferOrderButton) transferOrderButton.style.display = '';
                    },
                );

                return false;
            });
        }

        const domainCheck = document.getElementById('domain-check');
        if (domainCheck) {
            domainCheck.addEventListener('click', function (event) {
                const sld = document.querySelector('input[name="register_sld"]').value.toLowerCase();
                const tld = document.querySelector('select[name="register_tld"]').value.toLowerCase();
                const domain = sld + tld;
                document.getElementById('domain-action').value = 'register';
                FOSSBilling.api.guest.post(
                    'servicedomain/check',
                    {sld: sld, tld: tld},
                    function (result) {
                        setPricing(tld);
                        const domainNameEl = document.getElementById('domain-name');
                        if (domainNameEl) domainNameEl.textContent = domain;
                        const onAfterDomainCheck = document.querySelector('.onAfterDomainCheck');
                        if (onAfterDomainCheck) fadeIn(onAfterDomainCheck);

                        const registerOrderButton = document.querySelector('#register .order-button');
                        if (registerOrderButton) registerOrderButton.style.display = '';
                    },
                );

                return false;
            });
        }

        function setPricing(tld) {
            FOSSBilling.api.guest.post(
                'servicedomain/pricing',
                {tld: tld},
                function (result) {
                    const yearsSelect = document.getElementById('registration-years');
                    if (!yearsSelect) return;
                    yearsSelect.innerHTML = '';

                    const regPrice = Number(result.price_registration);
                    let renewPrice = Number(result.price_renew);

                    if (result.price_renew === null || typeof result.price_renew === 'undefined' || isNaN(renewPrice)) {
                        renewPrice = regPrice;
                    }

                    const yearLabel = "{{ ' Year @ '|trans }}";
                    const yearsLabel = "{{ ' Years @ '|trans }}";

                    for (let i = 1; i <= 5; i++) {
                        const totalPrice = (i === 1) ? regPrice : regPrice + (i - 1) * renewPrice;
                        const priceFormatted = formatCurrency(
                            totalPrice,
                            {{ currency.conversion_rate }},
                            "{{ currency.code }}",
                            1
                        );

                        yearsSelect.append(
                            new Option(i + (i === 1 ? yearLabel : yearsLabel) + priceFormatted, i)
                        );
                    }

                    configNext.style.display = '';
                    configNext.disabled = false;
                },
            );
        }

        function setTransferPricing(tld) {
            FOSSBilling.api.guest.post(
                'servicedomain/pricing',
                {tld: tld},
                function (result) {
                    const price = formatCurrency(result.price_transfer, {{ currency.conversion_rate }}, "{{ currency.code }}");
                    const transferPriceEl = document.getElementById('transfer-price');
                    if (transferPriceEl) transferPriceEl.textContent = price;
                    configNext.style.display = '';
                    configNext.disabled = false;
                },
            );
        }

        // Handle URL parameters for pre-filling domain form
        const urlParams = new URLSearchParams(window.location.search);

        const tldParam = urlParams.get('tld');
        if (tldParam) {
            const registerTldSelect = document.querySelector('select[name="register_tld"]');
            if (registerTldSelect) {
                for (let i = 0; i < registerTldSelect.options.length; i++) {
                    if (registerTldSelect.options[i].value === tldParam) {
                        registerTldSelect.selectedIndex = i;
                        break;
                    }
                }
            }
            const transferTldSelect = document.querySelector('select[name="transfer_tld"]');
            if (transferTldSelect) {
                for (let i = 0; i < transferTldSelect.options.length; i++) {
                    if (transferTldSelect.options[i].value === tldParam) {
                        transferTldSelect.selectedIndex = i;
                        break;
                    }
                }
            }
        }

        const nameParam = urlParams.get('name');
        if (nameParam) {
            const registerSldInput = document.querySelector('input[name="register_sld"]');
            if (registerSldInput) {
                registerSldInput.value = nameParam;
            }
            const transferSldInput = document.querySelector('input[name="transfer_sld"]');
            if (transferSldInput) {
                transferSldInput.value = nameParam;
            }
        }
    });
</script>
