{* Vanity setup splash — shown when a vanity service has no name/domain yet.
   The customer picks a NAME (one DNS label) and, when the group sells more
   than one parent domain, which domain. We then provision name.<domain> +
   name@<domain>. All input is re-validated server-side. *}
<style>
.puq-domain-card { max-width: 760px; margin: 16px auto; }
.puq-domain-card .panel-heading { background: #f7f9fc; border-bottom: 1px solid #e0e6ee; padding: 14px 18px; }
.puq-domain-card .panel-heading h4 { margin: 0; font-weight: 500; color: #333; }
.puq-domain-card .panel-body { padding: 22px; }
.puq-domain-lead { color: #666; margin-bottom: 18px; }
.puq-vanity-row { display: flex; gap: 8px; align-items: stretch; margin-bottom: 6px; flex-wrap: wrap; }
.puq-vanity-row input.form-control, .puq-vanity-row select.form-control { font-size: 16px; height: auto; padding: 10px 12px; }
/* Name field: a framed input-group so the name + "." + domain read as one
   unit, with a state ring that turns green/red as the customer types. */
.puq-vanity-name-wrap { position: relative; flex: 1 1 240px; min-width: 200px; }
.puq-vanity-name { width: 100%; text-align: right; padding-right: 34px !important; transition: border-color .15s, box-shadow .15s; }
.puq-vanity-name-wrap.is-ok    input.puq-vanity-name { border-color: #3c763d; box-shadow: 0 0 0 2px rgba(60,118,61,.15); }
.puq-vanity-name-wrap.is-bad   input.puq-vanity-name { border-color: #a94442; box-shadow: 0 0 0 2px rgba(169,68,66,.12); }
.puq-vanity-name-wrap.is-check input.puq-vanity-name { border-color: #999; }
.puq-vanity-name-state { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); font-size: 15px; pointer-events: none; }
.puq-vanity-name-state .text-success { color: #3c763d; }
.puq-vanity-name-state .text-danger  { color: #a94442; }
.puq-vanity-name-state .text-muted   { color: #999; }
.puq-vanity-at { display: flex; align-items: center; color: #999; font-size: 18px; }
.puq-vanity-dot { display: flex; align-items: center; color: #999; font-size: 18px; padding: 0 2px; }
.puq-vanity-domain { min-width: 220px; }
.puq-domain-help { color: #888; font-size: 12px; margin-bottom: 14px; }
.puq-vanity-preview { background: #eaf4ff; border-left: 3px solid #337ab7; padding: 10px 14px; font-size: 14px; margin: 14px 0; border-radius: 0 3px 3px 0; }
.puq-vanity-preview code { background: #fff; padding: 1px 6px; border-radius: 2px; }
.puq-msg { display: inline-block; margin-left: 10px; font-size: 13px; }
.puq-spin { display: inline-block; animation: puq-spin 0.8s linear infinite; }
@keyframes puq-spin { to { transform: rotate(360deg); } }
</style>

<div class="panel panel-default puq-domain-card">
    <div class="panel-heading">
        <h4><i class="fa fa-at text-primary"></i> &nbsp;{$L.vn_choose_your_name}</h4>
    </div>
    <div class="panel-body">
        <p class="puq-domain-lead">
            {$L.vn_setup_lead}
        </p>

        <div class="puq-vanity-row">
            <div class="puq-vanity-name-wrap" id="puq-vanity-name-wrap">
                <input type="text" class="form-control puq-vanity-name" id="puq-vanity-name" placeholder="{$L.vn_your_name}" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" autofocus>
                <span class="puq-vanity-name-state" id="puq-vanity-name-state"></span>
            </div>
            <div class="puq-vanity-dot" id="puq-vanity-sep">.</div>
            <select class="form-control puq-vanity-domain" id="puq-vanity-domain" style="display:none;"></select>
            <span class="form-control puq-vanity-domain" id="puq-vanity-domain-fixed" style="display:none;background:#f5f5f5;border:1px solid #ddd;line-height:1.8;"></span>
            <button type="button" class="btn btn-primary" id="puq-vanity-go">
                <i class="fa fa-rocket"></i> {$L.vn_start}
            </button>
        </div>
        <div class="puq-domain-help">
            {$L.vn_name_rule}
        </div>

        <div class="puq-vanity-preview" id="puq-vanity-preview" style="display:none;">
            <i class="fa fa-eye"></i> {$L.vn_youll_get}:
            <strong>{$L.vn_site}</strong> <code id="puq-prev-site"></code>
            &nbsp;·&nbsp; <strong>{$L.vn_email}</strong> <code id="puq-prev-mail"></code>
        </div>

        <div style="margin-top:6px;">
            <span id="puq-vanity-msg" class="puq-msg"></span>
        </div>
    </div>
</div>

{literal}
<script>
(function(){
    var sid = {/literal}{$service_id|default:0|intval}{literal};
    if (!sid) { var m = window.location.search.match(/[?&]id=(\d+)/); if (m) sid = parseInt(m[1], 10); }
    // This splash renders WITHOUT header.tpl — provide self-contained puqT (from
    // the injected {$L_json} map) and a puqClientAjax fallback so the page never
    // depends on header-only globals.
    var PUQ_T = (window.PUQ_T) || {/literal}{$L_json|default:'{}' nofilter}{literal};
    var puqT = (typeof window.puqT === 'function') ? window.puqT : function(k){ return (PUQ_T && PUQ_T[k] != null) ? PUQ_T[k] : k; };
    var puqClientAjax = (typeof window.puqClientAjax === 'function') ? window.puqClientAjax : function(action, data, cb, method){
        jQuery.ajax({ url: 'clientarea.php?action=productdetails&id=' + sid + '&ajax=' + action,
            method: method || 'POST', contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(data || {}), processData: false, dataType: 'json',
            success: function(r){ cb(r); }, error: function(){ cb({status:'error', msg: puqT('ms_network_error')}); } });
    };
    var nameRe = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
    var domains = [];
    var nameMax = 0;
    // Availability state: '' (empty) | 'invalid' | 'checking' | 'available' | 'taken'
    var state = '';
    var checkTimer = null, checkSeq = 0;

    function esc(s){ return String(s == null ? '' : s).replace(/[&<>"']/g, function(c){
        return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
    }); }
    function url(action){ return 'clientarea.php?action=productdetails&id=' + sid + '&ajax=' + action; }
    function showMsg(html, kind){
        var $m = $('#puq-vanity-msg');
        $m.removeClass('text-success text-danger text-muted')
          .addClass(kind === 'success' ? 'text-success' : (kind === 'error' ? 'text-danger' : 'text-muted'))
          .html(html);
    }
    // Drive the input ring + inline icon + message + Start button from `state`.
    function applyState(msgHtml){
        var $wrap = $('#puq-vanity-name-wrap').removeClass('is-ok is-bad is-check');
        var $icon = $('#puq-vanity-name-state');
        if (state === 'available') {
            $wrap.addClass('is-ok'); $icon.html('<i class="fa fa-check text-success"></i>');
            showMsg('<i class="fa fa-check"></i> ' + esc(puqT('vn_name_available')), 'success');
        } else if (state === 'taken' || state === 'invalid') {
            $wrap.addClass('is-bad'); $icon.html('<i class="fa fa-times text-danger"></i>');
            showMsg(msgHtml || esc(puqT(state === 'taken' ? 'vn_name_taken' : 'vn_name_invalid')), 'error');
        } else if (state === 'checking') {
            $wrap.addClass('is-check'); $icon.html('<i class="fa fa-circle-notch puq-spin text-muted"></i>');
            showMsg(esc(puqT('vn_checking')), 'muted');
        } else {
            $icon.html(''); showMsg('', '');
        }
        // Start is enabled ONLY when the name is confirmed available.
        $('#puq-vanity-go').prop('disabled', state !== 'available');
    }
    function currentDomain(){
        if (domains.length > 1) return $('#puq-vanity-domain').val() || '';
        return domains.length === 1 ? domains[0] : '';
    }
    function refreshPreview(){
        var n = ($('#puq-vanity-name').val() || '').trim().toLowerCase();
        var d = currentDomain();
        if (n && d && nameRe.test(n)) {
            $('#puq-prev-site').text(n + '.' + d);
            $('#puq-prev-mail').text(n + '@' + d);
            $('#puq-vanity-preview').show();
        } else {
            $('#puq-vanity-preview').hide();
        }
    }
    // Debounced server-side availability check (validates name + domain, and
    // whether the name is already taken on that domain). Authoritative — the
    // client-side regex is only a fast pre-filter.
    function runCheck(){
        var n = ($('#puq-vanity-name').val() || '').trim().toLowerCase();
        var d = currentDomain();
        refreshPreview();
        if (n === '') { state = ''; applyState(); return; }
        if (nameMax > 0 && n.length > nameMax) { state = 'invalid'; applyState(esc(puqT('vn_name_invalid'))); return; }
        if (!nameRe.test(n)) { state = 'invalid'; applyState(esc(puqT('vn_name_invalid'))); return; }
        if (!d) { state = ''; applyState(); return; }
        state = 'checking'; applyState();
        var my = ++checkSeq;
        $.ajax({ url: url('vanityCheckName') + '&name=' + encodeURIComponent(n) + '&domain=' + encodeURIComponent(d),
            dataType: 'json',
            success: function(r){
                if (my !== checkSeq) return; // stale response — newer keystroke won
                if (!r || r.status !== 'success') { state = ''; applyState(); $('#puq-vanity-go').prop('disabled', false); return; }
                if (r.available) { state = 'available'; applyState(); }
                else { state = (r.state === 'taken') ? 'taken' : 'invalid'; applyState(r.reason ? esc(r.reason) : null); }
            },
            error: function(){ if (my !== checkSeq) return; state = ''; applyState(); $('#puq-vanity-go').prop('disabled', false); }
        });
    }
    function debouncedCheck(){ clearTimeout(checkTimer); checkTimer = setTimeout(runCheck, 350); }

    // Load sellable parent domains.
    $.ajax({ url: url('vanityDomains'), dataType: 'json', success: function(r){
        if (!r || r.status !== 'success' || !r.domains || !r.domains.length) {
            showMsg(puqT('vn_no_domains_available'), 'error');
            $('#puq-vanity-go').prop('disabled', true);
            return;
        }
        domains = r.domains;
        nameMax = parseInt(r.max_len, 10) || 0;
        if (nameMax > 0) $('#puq-vanity-name').attr('maxlength', nameMax);
        if (domains.length === 1) {
            $('#puq-vanity-domain-fixed').text(domains[0]).show();
        } else {
            var opts = '';
            domains.forEach(function(d){ opts += '<option value="' + esc(d) + '">' + esc(d) + '</option>'; });
            $('#puq-vanity-domain').html(opts).show();
        }
        if (r.name) { $('#puq-vanity-name').val(r.name); }
        // Initial state: Start disabled until a name is confirmed available.
        $('#puq-vanity-go').prop('disabled', true);
        runCheck();
    }, error: function(){ showMsg(puqT('vn_could_not_load_domains'), 'error'); } });

    $('#puq-vanity-name').on('input', function(){
        // Normalize to lowercase live so the preview + check match what we send.
        var caret = this.selectionStart;
        var lowered = this.value.toLowerCase();
        if (lowered !== this.value) { this.value = lowered; try { this.setSelectionRange(caret, caret); } catch(e){} }
        debouncedCheck();
    });
    $('#puq-vanity-domain').on('change', runCheck);
    $('#puq-vanity-name').on('keypress', function(e){ if (e.which === 13){ e.preventDefault(); if (state === 'available') $('#puq-vanity-go').click(); } });

    $('#puq-vanity-go').on('click', function(){
        var $b = $(this);
        var name = ($('#puq-vanity-name').val() || '').trim().toLowerCase();
        var domain = currentDomain();
        // Guard: only proceed when the live check confirmed availability.
        if (state !== 'available') { runCheck(); $('#puq-vanity-name').focus(); return; }
        if (!nameRe.test(name)) { showMsg(puqT('vn_enter_valid_name'), 'error'); $('#puq-vanity-name').focus(); return; }
        if (!domain) { showMsg(puqT('vn_choose_domain'), 'error'); return; }
        $b.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> ' + puqT('vn_setting_up'));
        showMsg(puqT('vn_saving'), 'muted');
        puqClientAjax('vanitySetup', { name: name, domain: domain }, function(r){
            if (r && r.status === 'success') {
                showMsg(r.msg || puqT('vn_done_reloading'), 'success');
                setTimeout(function(){ window.location.reload(); }, 1200);
            } else {
                $b.prop('disabled', false).html('<i class="fa fa-rocket"></i> ' + puqT('vn_start'));
                showMsg((r && r.msg) || puqT('vn_failed'), 'error');
            }
        }, 'POST');
    });
})();
</script>
{/literal}
