{include file='modules/servers/puqWebHosting/templates/header.tpl'}

{literal}
<style>
/* Row-hover popover — shows the FULL record content (type, name, value,
   priority, TTL) without truncation. Plain `title="..."` browser tooltips
   wrap weirdly on long TXT/CAA records and don't preserve monospace; this
   custom popover keeps everything readable. Positioned fixed via JS so it
   isn't clipped by table overflow. */
.puq-dns-row { cursor: default; }
.puq-dns-row:hover { background: #f8fafe !important; }
#puq-dns-tip {
    position: fixed; z-index: 10050; pointer-events: none;
    background: #2d3748; color: #f7fafc;
    padding: 10px 12px; border-radius: 6px; font-size: 12px;
    box-shadow: 0 8px 24px rgba(0,0,0,.25);
    max-width: 520px; min-width: 280px;
    display: none; line-height: 1.5;
}
#puq-dns-tip .puq-tip-row { display: flex; gap: 10px; align-items: baseline; }
#puq-dns-tip .puq-tip-key {
    color: #a0aec0; text-transform: uppercase; letter-spacing: .5px;
    font-size: 10px; min-width: 70px; text-align: right;
}
#puq-dns-tip .puq-tip-val {
    font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
    word-break: break-all; flex: 1; color: #fff;
}
#puq-dns-tip .puq-tip-val.puq-tip-type {
    color: #fbbf24; font-weight: 700; font-size: 11px;
}
</style>
<div id="puq-dns-tip"></div>
{/literal}

{assign var='page_icon'  value='globe'}
{assign var='page_title' value=$L.dz_dns_records}
{include file='modules/servers/puqWebHosting/templates/_page_header.tpl'}

<div class="puq-card">
    <div class="puq-card-header">
        <i class="fa fa-info-circle"></i> {$L.dz_zone_info}
        <span class="puq-header-spacer"></span>
        <small style="color:var(--puq-muted);">{$L.dz_click_zone_to_copy}</small>
    </div>
    <div class="puq-card-body" style="padding:8px 16px;">
        <div style="display:flex;align-items:baseline;gap:10px;margin-bottom:8px;">
            <div style="font-size:11px;color:var(--puq-muted);text-transform:uppercase;letter-spacing:.3px;min-width:60px;">{$L.dz_zone}</div>
            <code class="puq-copy" style="font-size:14px;">{$domain}</code>
        </div>
        <div class="puq-msg puq-msg-info" style="margin:8px 0 0;font-size:12px;">
            <i class="fa fa-lightbulb"></i> {$L.dz_apex_ttl_hint}
        </div>
        <div class="puq-msg puq-msg-warning" style="margin:8px 0 0;font-size:12px;">
            <i class="fa fa-exclamation-triangle"></i> <strong>{$L.dz_own_ns_q}</strong>
            {$L.dz_own_ns_body1}
            <br>{$L.dz_own_ns_body2}
        </div>
    </div>
</div>

{if $expected_ns && !$external_dns}
<div class="puq-card">
    <div class="puq-card-header">
        <i class="fa fa-server"></i> {$L.dz_nameservers}
        <span class="puq-header-spacer"></span>
        <small style="color:var(--puq-muted);">{$L.dz_ns_only_if_we_manage}</small>
    </div>
    <div class="puq-card-body" style="padding:8px 16px;">
        <div class="puq-msg puq-msg-info" style="margin:0 0 8px;font-size:12px;">
            <i class="fa fa-info-circle"></i> {$L.dz_ns_set_at_registrar}
        </div>
        <ul style="list-style:none;padding-left:0;margin:0;">
            {foreach $expected_ns as $ns}
            <li style="margin:2px 0;"><code class="puq-copy" style="font-size:14px;">{$ns}</code></li>
            {/foreach}
        </ul>
    </div>
</div>
{/if}

<div class="puq-card" data-puq-lock-zone="web">
    <div class="puq-card-header">
        <i class="fa fa-list"></i> {$L.dz_records}
        <i class="fas fa-circle-notch fa-spin" id="puq-dns-spinner" style="display:none;color:var(--puq-muted);margin-left:6px;font-size:12px;" title="{$L.dz_refreshing}"></i>
        <span class="puq-header-spacer"></span>
        <span id="puq-dns-usage" class="puq-badge puq-badge-muted" title="{$L.dz_used_limit}">… / {if isset($limits.dns_records) && $limits.dns_records > 0}{$limits.dns_records}{else}∞{/if}</span>
        <button type="button" class="puq-btn puq-btn-warning puq-btn-sm" id="puq-dns-reset" title="{$L.dz_restore_defaults_tip}">
            <i class="fa fa-magic"></i> {$L.dz_restore_defaults}
        </button>
        <button type="button" class="puq-btn puq-btn-primary puq-btn-sm" id="puq-dns-add"><i class="fa fa-plus"></i> {$L.dz_add_record}</button>
    </div>
    <div class="puq-card-body">

        <table class="table table-hover" id="puq-dns-table" style="width:100%;table-layout:fixed;">
            <colgroup>
                <col style="width:70px;">
                <col style="width:160px;">
                <col>{* Value — flex *}
                <col style="width:50px;">
                <col style="width:70px;">
                <col style="width:160px;">
                <col style="width:90px;">
            </colgroup>
            <thead>
                <tr style="background:var(--puq-bg);">
                    <th>{$L.dz_type}</th>
                    <th>{$L.dz_name}</th>
                    <th>{$L.dz_value}</th>
                    <th style="text-align:right;">{$L.dz_pri}</th>
                    <th style="text-align:right;">{$L.dz_ttl}</th>
                    <th>{$L.dz_status}</th>
                    <th style="text-align:right;">{$L.dz_actions}</th>
                </tr>
            </thead>
            <tbody><tr><td colspan="7" class="puq-loader"><i class="fas fa-circle-notch fa-spin"></i><span class="puq-loader-caption">{$L.dz_loading_dns_records}</span></td></tr></tbody>
        </table>
    </div>
</div>

{* Add / Edit modal — single form, opened in either mode. Type-aware:
   Priority field is shown only for MX / SRV; the priority cell on the
   record row maps to NULL for the other types. *}
<div id="puq-dns-edit-overlay" class="puq-confirm-overlay" style="display:none;">
    <div class="puq-confirm-box" style="max-width:560px;">
        <div class="puq-confirm-icon" style="color:var(--puq-primary);"><i class="fas fa-globe"></i></div>
        <div class="puq-confirm-title" id="puq-dns-edit-title">{$L.dz_dns_record}</div>
        <div style="padding:0 24px 8px;">
            <form id="puq-dns-edit-form" autocomplete="off">
                <input type="hidden" name="mode" id="puq-dns-mode" value="create">
                {* OLD tuple — only meaningful in update mode, identifies the row. *}
                <input type="hidden" name="old_record_type" id="puq-dns-old-type">
                <input type="hidden" name="old_name" id="puq-dns-old-name">
                <input type="hidden" name="old_value" id="puq-dns-old-value">
                <input type="hidden" name="old_priority" id="puq-dns-old-priority">

                <div class="puq-row" style="gap:8px;margin-bottom:10px;">
                    <div class="puq-col" style="min-width:120px;flex:0 0 140px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.dz_type}</label>
                        <select name="record_type" id="puq-dns-type" class="form-control">
                            <option value="A">A</option>
                            <option value="AAAA">AAAA</option>
                            <option value="CNAME">CNAME</option>
                            <option value="MX">MX</option>
                            <option value="TXT">TXT</option>
                            <option value="NS">NS</option>
                            <option value="SRV">SRV</option>
                            <option value="CAA">CAA</option>
                            <option value="PTR">PTR</option>
                            <option value="DNSKEY">DNSKEY</option>
                            <option value="DS">DS</option>
                            <option value="NAPTR">NAPTR</option>
                            <option value="TLSA">TLSA</option>
                        </select>
                    </div>
                    <div class="puq-col" style="min-width:200px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.dz_name} <small>{$L.dz_name_apex_hint}</small></label>
                        <input type="text" name="name" id="puq-dns-name" class="form-control" required placeholder="{$L.dz_name_placeholder}" style="font-family:monospace;">
                    </div>
                </div>

                <div style="margin-bottom:10px;">
                    <label style="font-size:11px;color:var(--puq-muted);" id="puq-dns-value-label">{$L.dz_value}</label>
                    <textarea name="value" id="puq-dns-value" class="form-control" rows="2" required placeholder="1.2.3.4" style="font-family:monospace;font-size:12px;"></textarea>
                    <small class="text-muted" id="puq-dns-value-hint">{$L.dz_hint_a}</small>
                </div>

                <div class="puq-row" style="gap:8px;margin-bottom:10px;">
                    <div class="puq-col" id="puq-dns-priority-wrap" style="min-width:120px;flex:0 0 140px;display:none;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.dz_priority} <small>(0–65535)</small></label>
                        <input type="number" name="priority" id="puq-dns-priority" class="form-control" min="0" max="65535" placeholder="10">
                    </div>
                    <div class="puq-col" style="min-width:120px;flex:0 0 140px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.dz_ttl} <small>{$L.dz_seconds}</small></label>
                        <input type="number" name="ttl" id="puq-dns-ttl" class="form-control" min="60" max="86400" value="3600">
                    </div>
                </div>

                <div class="puq-dns-edit-err text-danger" style="font-size:12px;min-height:14px;margin-top:4px;"></div>
            </form>
        </div>
        <div class="puq-confirm-btns">
            <button type="button" class="puq-confirm-btn-cancel" id="puq-dns-edit-cancel">{$L.dz_cancel}</button>
            <button type="button" class="puq-confirm-btn-ok" id="puq-dns-edit-save" style="background:var(--puq-success);">{$L.dz_save}</button>
        </div>
    </div>
</div>

<script>
window.puqServiceId = {$service_id};
window.puqPageRoles = ['web'];
window.puqDnsLimit  = {if isset($limits.dns_records)}{$limits.dns_records|intval}{else}0{/if};
window.puqDnsZone   = {literal}'{/literal}{$domain|escape:'javascript'}{literal}'{/literal};
</script>
{literal}
<script>
(function(){
    // ----- Type-specific UI hints + placeholders ----------------------------
    // For hostname-target types (CNAME/NS/MX/SRV): short labels like "www"
    // resolve inside the current zone — customer doesn't type the zone
    // domain twice. Full FQDNs (ending with a dot) are absolute, can
    // point anywhere.
    var TYPE_META = {
        A:     { hint: puqT('dz_hint_a'),     placeholder: '192.0.2.1',                  hasPrio: false },
        AAAA:  { hint: puqT('dz_hint_aaaa'),  placeholder: '2001:db8::1',                hasPrio: false },
        CNAME: { hint: puqT('dz_hint_cname'), placeholder: 'www',                        hasPrio: false },
        MX:    { hint: puqT('dz_hint_mx'),    placeholder: 'mail',                       hasPrio: true  },
        TXT:   { hint: puqT('dz_hint_txt'),   placeholder: '"v=spf1 mx -all"',           hasPrio: false },
        NS:    { hint: puqT('dz_hint_ns'),    placeholder: 'ns1',                        hasPrio: false },
        SRV:   { hint: puqT('dz_hint_srv'),   placeholder: '10 443 sip',                 hasPrio: true  },
        CAA:   { hint: puqT('dz_hint_caa'),   placeholder: '0 issue "letsencrypt.org"',  hasPrio: false }
    };
    function applyTypeMeta(type){
        var m = TYPE_META[type] || TYPE_META.A;
        $('#puq-dns-value-hint').text(m.hint);
        $('#puq-dns-value').attr('placeholder', m.placeholder);
        $('#puq-dns-priority-wrap').toggle(!!m.hasPrio);
        if (!m.hasPrio) $('#puq-dns-priority').val('');
    }

    // ----- Click-to-copy for info banner ------------------------------------
    $(document).on('click', '.puq-copy', function(){
        var $el = $(this), txt = $el.text();
        var copied = function(){ puqToast('success', puqT('dz_copied') + ' ' + txt); };
        var failed = function(){ puqToast('error', puqT('dz_clipboard_blocked')); };
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(txt).then(copied).catch(failed);
        } else {
            var $ta = $('<textarea>').val(txt).appendTo('body').select();
            try { document.execCommand('copy'); copied(); } catch (e) { failed(); }
            $ta.remove();
        }
    });
    $(document).on('mouseenter', '.puq-copy', function(){ $(this).css({'cursor':'copy','background':'#eef2ff'}); });
    $(document).on('mouseleave', '.puq-copy', function(){ $(this).css('background',''); });

    // ----- Hover popover ------------------------------------------------------
    // Shows the full record content (no truncation) on row hover. Positioned
    // fixed near the cursor; flipped to the left edge if it would overflow.
    var $tip = $('#puq-dns-tip');
    function tipHtml(type, name, value, priority, ttl){
        function row(k, v){
            return '<div class="puq-tip-row"><span class="puq-tip-key">' + k
                 + '</span><span class="puq-tip-val">' + puqEsc(v) + '</span></div>';
        }
        var typeRow = '<div class="puq-tip-row"><span class="puq-tip-key">' + puqT('dz_type') + '</span>'
                    + '<span class="puq-tip-val puq-tip-type">' + puqEsc(type) + '</span></div>';
        var prioRow = (priority === '' || priority == null)
            ? '' : row(puqT('dz_priority'), priority);
        return typeRow + row(puqT('dz_name'), name) + row(puqT('dz_value'), value) + prioRow + row(puqT('dz_ttl'), ttl + ' ' + puqT('dz_sec'));
    }
    $(document).on('mouseenter', '#puq-dns-table tbody tr.puq-dns-row', function(){
        var $tr = $(this);
        $tip.html(tipHtml(
            $tr.attr('data-type') || '',
            $tr.attr('data-name') || '',
            $tr.attr('data-value') || '',
            $tr.attr('data-priority') || '',
            $tr.attr('data-ttl') || ''
        )).show();
    });
    $(document).on('mouseleave', '#puq-dns-table tbody tr.puq-dns-row', function(){
        $tip.hide();
    });
    $(document).on('mousemove', '#puq-dns-table tbody tr.puq-dns-row', function(e){
        var pad = 14;
        var tipW = $tip.outerWidth(), tipH = $tip.outerHeight();
        var x = e.clientX + pad;
        var y = e.clientY + pad;
        // Flip left/up if overflow.
        if (x + tipW + pad > window.innerWidth)  x = e.clientX - tipW - pad;
        if (y + tipH + pad > window.innerHeight) y = e.clientY - tipH - pad;
        if (x < 4) x = 4;
        if (y < 4) y = 4;
        $tip.css({ left: x + 'px', top: y + 'px' });
    });

    // Stable per-row key for jQuery selectors (the tuple, hashed). Two rows
    // with the same tuple are forbidden by the backend, so this is unique.
    function rowKey(d){
        return btoa(unescape(encodeURIComponent(
            (d.record_type||'') + '|' + (d.name||'') + '|' + (d.value||'') + '|' + (d.priority==null?'':d.priority)
        ))).replace(/=+$/, '');
    }

    var TRANSIENT = ['queued','deploying','pending_delete','deleting'];
    var auto = puqAutoRefresh(load);

    function load(){
        puqInitialTableLoader('#puq-dns-table tbody', 'data-key', 7, puqT('dz_loading_dns_records'));
        puqSetSpinner('#puq-dns-spinner', true);
        puqClientAjax('dnsRecordsList', {}, function(r){
            puqSetSpinner('#puq-dns-spinner', false);
            var $t = $('#puq-dns-table tbody');
            if (r.status !== 'success') {
                if (!$t.children('tr[data-key]').length) {
                    $t.html('<tr><td colspan="7" class="text-danger text-center" style="padding:18px;">' + puqEsc(r.msg||puqT('dz_error')) + '</td></tr>');
                } else if (window.puqToast) puqToast('error', r.msg || puqT('dz_refresh_failed'));
                auto.schedule(false);
                return;
            }
            var rows = r.data || [];
            var aliveCount = rows.filter(function(d){ return d.deploy_status !== 'pending_delete' && d.deploy_status !== 'deleting'; }).length;
            puqUpdateQuotaBadge('#puq-dns-usage', '#puq-dns-add', aliveCount, window.puqDnsLimit || 0, puqT('dz_add_record'));

            var html = '';
            if (!rows.length) {
                html = '<tr><td colspan="7" class="text-muted text-center" style="padding:24px;">' + puqT('dz_no_records_yet') + '</td></tr>';
            } else {
                rows.forEach(function(d){
                    var ed = puqIsEditable(d.deploy_status);
                    var op = (d.remote_id_count > 0) ? 'update' : 'create';
                    var key = rowKey(d);
                    // Long values (TXT/CAA) are truncated visually; the
                    // puq-tip popover on row hover (CSS below) shows the
                    // FULL record — type, name, value, priority, TTL — so
                    // the customer can see exactly what's in the row
                    // without opening edit.
                    var fullValue = String(d.value || '');
                    var truncated = fullValue.length > 60 ? fullValue.substring(0, 60) + '…' : fullValue;
                    // puqEscAttr (NOT puqEsc) for attribute values — values
                    // containing `"` (CAA, TXT) would close the attribute
                    // early and drop the tail. puqEscAttr escapes `"`/`'`.
                    html += '<tr class="puq-dns-row" data-key="' + key + '"' +
                        ' data-type="'   + puqEscAttr(d.record_type) + '"' +
                        ' data-name="'   + puqEscAttr(d.name) + '"' +
                        ' data-value="'  + puqEscAttr(d.value) + '"' +
                        ' data-priority="' + (d.priority == null ? '' : puqEscAttr(d.priority)) + '"' +
                        ' data-ttl="'    + puqEscAttr(d.ttl) + '">' +
                        '<td><span class="puq-badge puq-badge-primary" style="font-family:monospace;">' + puqEsc(d.record_type) + '</span></td>' +
                        '<td style="font-family:monospace;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' + puqEsc(d.name) + '</td>' +
                        '<td style="font-family:monospace;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#333;">' + puqEsc(truncated) + '</td>' +
                        '<td style="text-align:right;font-variant-numeric:tabular-nums;">' + (d.priority == null ? '<span style="color:var(--puq-muted);">—</span>' : puqEsc(d.priority)) + '</td>' +
                        '<td style="text-align:right;font-variant-numeric:tabular-nums;">' + puqEsc(d.ttl) + '</td>' +
                        '<td>' + puqDeployBadge(d.deploy_status, d.deploy_error, op) + '</td>' +
                        '<td style="text-align:right;white-space:nowrap;">' +
                            (ed ? '<button type="button" class="puq-btn puq-btn-outline puq-btn-sm puq-edit" title="Edit"><i class="fa fa-edit"></i></button> ' : '') +
                            (ed ? '<button type="button" class="puq-btn puq-btn-danger puq-btn-sm puq-del" title="Delete"><i class="fa fa-trash"></i></button>' : '') +
                        '</td></tr>';
                });
            }
            $t.html(html);
            var anyPending = rows.some(function(d){ return TRANSIENT.indexOf(d.deploy_status) >= 0; });
            if (window.puqClientNotifyTransitions) puqClientNotifyTransitions('dns_records', rows, 'name', 'deploy_status', puqT('dz_dns_record'), 'name');
            auto.schedule(anyPending);
        });
    }

    function atLimit(){
        var lim = window.puqDnsLimit || 0;
        if (lim <= 0) return false;
        var alive = $('#puq-dns-table tbody tr[data-key]').filter(function(){
            var badge = $(this).find('.puq-badge:not(.puq-badge-primary)').text() || '';
            return badge.indexOf('queued for delete') === -1 && badge.indexOf('deleting') === -1;
        }).length;
        return alive >= lim;
    }

    // ----- Modal open/close ---------------------------------------------------
    function openModal(){
        var $ov = $('#puq-dns-edit-overlay').show();
        requestAnimationFrame(function(){ requestAnimationFrame(function(){ $ov.addClass('puq-confirm-show'); }); });
    }
    function closeModal(){
        var $ov = $('#puq-dns-edit-overlay');
        $ov.removeClass('puq-confirm-show');
        setTimeout(function(){ $ov.hide(); }, 200);
    }
    $('#puq-dns-edit-cancel').on('click', closeModal);
    $('#puq-dns-edit-overlay').on('click', function(e){ if (e.target === this) closeModal(); });
    $(document).on('keydown.puqDnsEdit', function(e){
        if (e.key === 'Escape' && $('#puq-dns-edit-overlay').is(':visible')) closeModal();
    });
    $('#puq-dns-type').on('change', function(){
        applyTypeMeta(this.value);
        // Re-validate value field against the new type — clears stale error
        // when switching from a stricter type (A) back to a permissive one (TXT).
        validateValueLive();
    });
    function validateValueLive(){
        var $v = $('#puq-dns-value');
        var type = String($('#puq-dns-type').val() || '').toUpperCase();
        var val = String($v.val() || '').trim();
        var prio = String($('#puq-dns-priority').val() || '').trim();
        // Empty is OK while still typing — only flag actual format errors.
        if (val === '') { $v.removeClass('puq-field-error'); return; }
        var ok = puqValidate.dnsValue(type, val, prio);
        $v.toggleClass('puq-field-error', !ok);
    }
    $('#puq-dns-value').on('blur input', validateValueLive);
    $('#puq-dns-priority').on('blur input', validateValueLive);

    // ----- Add ----------------------------------------------------------------
    $('#puq-dns-add').on('click', function(e){
        e.preventDefault();
        if (atLimit()) {
            puqConfirm({
                type:'warning', icon:'fa-ban', title:puqT('dz_record_limit_reached'),
                text:puqT('dz_record_limit_body_pre')+(window.puqDnsLimit||0)+puqT('dz_record_limit_body_post'),
                ok:puqT('dz_got_it'), cancel:puqT('dz_close')
            });
            return;
        }
        document.getElementById('puq-dns-edit-form').reset();
        $('#puq-dns-mode').val('create');
        $('#puq-dns-old-type, #puq-dns-old-name, #puq-dns-old-value, #puq-dns-old-priority').val('');
        $('#puq-dns-edit-title').text(puqT('dz_add_dns_record'));
        $('#puq-dns-type').val('A');
        $('#puq-dns-ttl').val(3600);
        applyTypeMeta('A');
        $('.puq-dns-edit-err').text('');
        openModal();
        setTimeout(function(){ $('#puq-dns-name').focus(); }, 50);
    });

    // ----- Edit ---------------------------------------------------------------
    $(document).on('click', '#puq-dns-table .puq-edit', function(){
        var $tr = $(this).closest('tr');
        // .attr() — NOT .data(). jQuery's .data() auto-parses values that
        // look like JSON; a TXT record value of `"v=spf1"` is technically
        // a valid JSON string literal, so .data() would strip the quotes
        // and the edit modal would show `v=spf1` without them. .attr()
        // returns the raw string verbatim.
        var type     = String($tr.attr('data-type') || '');
        var name     = String($tr.attr('data-name') || '');
        var value    = String($tr.attr('data-value') || '');
        var priority = String($tr.attr('data-priority') || '');
        var ttl      = String($tr.attr('data-ttl') || '');

        $('#puq-dns-mode').val('update');
        $('#puq-dns-old-type').val(type);
        $('#puq-dns-old-name').val(name);
        $('#puq-dns-old-value').val(value);
        $('#puq-dns-old-priority').val(priority);

        $('#puq-dns-edit-title').text(puqT('dz_edit_prefix') + type + puqT('dz_edit_record_suffix'));
        $('#puq-dns-type').val(type);
        $('#puq-dns-name').val(name);
        $('#puq-dns-value').val(value);
        $('#puq-dns-priority').val(priority);
        $('#puq-dns-ttl').val(ttl);
        applyTypeMeta(type);
        $('.puq-dns-edit-err').text('');
        openModal();
    });

    // ----- Delete -------------------------------------------------------------
    $(document).on('click', '#puq-dns-table .puq-del', function(e){
        e.preventDefault();
        var $tr = $(this).closest('tr');
        // .attr() not .data() — same JSON-auto-parse trap as Edit handler.
        var type     = String($tr.attr('data-type') || '');
        var name     = String($tr.attr('data-name') || '');
        var value    = String($tr.attr('data-value') || '');
        var priority = String($tr.attr('data-priority') || '');
        puqConfirm({
            type:'danger', icon:'fa-trash-alt', title:puqT('dz_delete_dns_record_q'),
            text:'<span class="puq-badge puq-badge-primary" style="font-family:monospace;">' + puqEsc(type) + '</span> '
                 + '<code>' + puqEsc(name) + '</code><br>'
                 + '<small style="color:var(--puq-muted);">→ <code>' + puqEsc(value.length > 60 ? value.substring(0,60)+'…' : value) + '</code></small>',
            ok:puqT('dz_delete'), cancel:puqT('dz_keep'),
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    puqClientAjax('dnsRecordDelete', {
                        record_type: type, name: name, value: value, priority: priority
                    }, function(r){
                        if (r.status === 'success') { puqToast('success', puqT('dz_record_queued_deletion')); load(); resolve(); }
                        else reject(new Error(r.msg || puqT('dz_delete_failed')));
                    }, 'POST');
                });
            }
        });
    });

    // ----- Save (create OR update) -------------------------------------------
    $('#puq-dns-edit-save').on('click', function(e){
        e.preventDefault();
        var $btn = $(this);
        var $err = $('.puq-dns-edit-err').text('');
        var type     = String($('#puq-dns-type').val()).toUpperCase();
        var name     = String($('#puq-dns-name').val() || '').trim();
        var value    = String($('#puq-dns-value').val() || '').trim();
        var priority = String($('#puq-dns-priority').val() || '').trim();
        var ttl      = String($('#puq-dns-ttl').val() || '').trim();
        var mode     = String($('#puq-dns-mode').val());
        var meta     = TYPE_META[type] || TYPE_META.A;

        if (!puqValidate.dnsName(name)) { $err.text(puqT('dz_err_name')); return; }
        if (type === 'CNAME' && name === '@') { $err.text(puqT('dz_err_cname_apex')); return; }
        if (!puqValidate.integer(ttl, 60, 86400)) { $err.text(puqT('dz_err_ttl')); return; }
        if (meta.hasPrio && !puqValidate.integer(priority, 0, 65535)) { $err.text(puqT('dz_err_priority_pre') + type + puqT('dz_err_priority_post')); return; }
        // Type-aware value check — single source of truth via puqValidate.dnsValue.
        if (!puqValidate.dnsValue(type, value, priority)) {
            $err.text(puqValidate.dnsValueMsg(type));
            return;
        }

        var payload = {
            record_type: type, name: name, value: value, ttl: ttl,
            priority: meta.hasPrio ? priority : ''
        };
        if (mode === 'update') {
            payload.old_record_type = $('#puq-dns-old-type').val();
            payload.old_name        = $('#puq-dns-old-name').val();
            payload.old_value       = $('#puq-dns-old-value').val();
            payload.old_priority    = $('#puq-dns-old-priority').val();
        }
        var action = mode === 'update' ? 'dnsRecordUpdate' : 'dnsRecordCreate';
        puqBtnSpin($btn, puqT('dz_saving'));
        puqClientAjax(action, payload, function(r){
            puqBtnRestore($btn);
            if (r.status === 'success') {
                puqToast('success', mode === 'update' ? puqT('dz_record_update_queued') : puqT('dz_record_creation_queued'));
                closeModal(); load();
            } else {
                $err.text(r.msg || puqT('dz_save_failed'));
                if (window.puqToast) puqToast('error', r.msg || puqT('dz_save_failed'));
            }
        }, 'POST');
    });

    // ----- Reset to template (destructive) ------------------------------------
    $('#puq-dns-reset').on('click', function(e){
        e.preventDefault();
        puqConfirm({
            type:'warning', icon:'fa-magic',
            title:puqT('dz_restore_default_records_q'),
            text:puqT('dz_restore_records_body'),
            ok:puqT('dz_restore_defaults'), cancel:puqT('dz_keep_current'),
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    puqClientAjax('dnsRedeployFromTemplate', {}, function(r){
                        if (r.status === 'success') {
                            puqToast('success', puqT('dz_defaults_queued'));
                            load(); resolve();
                        } else {
                            reject(new Error(r.msg || puqT('dz_restore_failed')));
                        }
                    }, 'POST');
                });
            }
        });
    });

    load();
})();
</script>
{/literal}
