{* UI minimalista: solo Secret y verificaciÃ³n (AJAX) *}
<div class="porto-admin-card">
    <div id="wb_msg"></div>
    <div id="wb_unique_notice">
    {if $settings.verified && !$settings.unique}
        <div class="wb-alert wb-alert--warn" role="status">
            <span data-i18n="settings.notice.needunique">{l s='La clave está verificada, pero aún falta vincular el número de WhatsApp desde el que se enviarán los mensajes. Conéctalo para obtener tu id_unique y poder enviar mensajes.' mod='whatsboost'}</span>
        </div>
    {/if}
    </div>

    {if $settings.verified && $settings.unique}
        <div id="wb_ok_notice">
            <div class="wb-alert wb-alert--ok" role="status"><span data-i18n="settings.notice.ok">{l s='Todo correcto. Enviaremos WhatsApps desde tu numero.' mod='whatsboost'}</span></div>
        </div>
    {else}
        <div id="wb_ok_notice"></div>
    {/if}
    <h3 class="wb-card-title" data-i18n="settings.license">{l s='Verificación de licencia' mod='whatsboost'}</h3>
    <form action="javascript:void(0)" method="post" class="wb-license-form" id="wb_license_form">
        <div class="wb-field">
            <label class="wb-label" for="wb_secret" data-i18n="settings.secret">{l s='Secret' mod='whatsboost'}</label>
            <input class="wb-input" id="wb_secret" name="WHATSBOOST_SECRET" type="text" value="{$settings.secret|escape:'htmlall':'UTF-8'}" placeholder="{l s='Pega aquí tu clave privada.' mod='whatsboost'}" data-i18n-ph="settings.secret.ph" />
        </div>
        <input type="hidden" name="confirm_overwrite" id="wb_confirm_overwrite" value="0" />

        <div class="wb-actions">
            <button type="button" id="wb_verify_btn" class="wb-btn wb-btn-primary" data-i18n="settings.verify">{l s='Verificar clave' mod='whatsboost'}</button>
        </div>
    </form>

    {assign var=img_base value=$module_dir|cat:'views/img/' }
    <div class="whatsboost-docs-callout whatsboost-docs-callout--primary whatsboost-docs-callout--wide porto-admin-card wb-settings-onboarding" style="margin-top:16px;{if !($settings.verified && !$settings.unique)}display:none;{/if}">
        <div class="heder">
            <h2 class="whatsboost-docs-h2" data-i18n="settings.onb.title">{l s='¿Aún no tienes tu número conectado?' mod='whatsboost'}</h2>
            <p class="whatsboost-docs-desc" data-i18n="settings.onb.desc">{l s='Sigue estos pasos para conectar tu WhatsApp y que podamos enviar mensajes desde tu número.' mod='whatsboost'}</p>
        </div>
        <div class="whatsboost-docs-flex">
            <div class="whatsboost-docs-col">
                <ol class="wb-stepper">
                    <li>
                        <span data-i18n="settings.onb.login">{l s='Inicia sesión en tu cuenta:' mod='whatsboost'}</span>
                        <a href="https://whatsboost.net/dashboard/auth" target="_blank" rel="noopener noreferrer" title="Inicio sesión de whatsboost">https://whatsboost.net/dashboard/auth</a>
                        <div class="whatsboost-mt-8">
                            <div class="wb-browser-frame">
                                <div class="wb-browser-bar"><span class="wb-dot"></span><span class="wb-dot"></span><span class="wb-dot"></span></div>
                                <div class="wb-browser-body">
                                    <img class="whatsboost-docs-img js-wb-zoom" src="{$img_base}iniciarSesion.PNG" alt="{l s='Inicia sesión en WhatsBoost' mod='whatsboost'}">
                                </div>
                            </div>
                        </div>
                    </li>
                </ol>
            </div>
        </div>
    </div>

    <div class="whatsboost-docs-callout whatsboost-docs-callout--primary whatsboost-docs-callout--wide porto-admin-card wb-settings-onboarding"{if !($settings.verified && !$settings.unique)} style="display:none"{/if}>
        <div class="whatsboost-docs-flex">
            <div class="whatsboost-docs-col">
                <ol class="wb-stepper">
                    <li style="margin:12px 0;">
                        <span data-i18n="settings.onb.hosts.pre">{l s='En el menú de la izquierda, entra en' mod='whatsboost'}</span> <strong>Hosts (1) → WhatsApp</strong>, <span data-i18n="settings.onb.hosts.or">{l s='o ve directo a' mod='whatsboost'}</span>
                        <a href="https://whatsboost.net/dashboard/hosts/whatsapp" target="_blank" rel="noopener noreferrer" data-i18n="settings.onb.hosts.thisurl">{l s='esta URL' mod='whatsboost'}</a>.
                        <span data-i18n="settings.onb.hosts.then">{l s='Luego pulsa' mod='whatsboost'}</span> <strong>“<span data-i18n="settings.onb.hosts.add">{l s='Añadir cuenta' mod='whatsboost'}</span>” (2)</strong> <span data-i18n="settings.onb.hosts.aspic">{l s='como en la captura.' mod='whatsboost'}</span>
                        <div class="whatsboost-mt-8">
                            <div class="wb-browser-frame">
                                <div class="wb-browser-bar"><span class="wb-dot"></span><span class="wb-dot"></span><span class="wb-dot"></span></div>
                                <div class="wb-browser-body">
                                    <img class="whatsboost-docs-img js-wb-zoom" src="{$img_base}tlf1.PNG" alt="{l s='Paso: Hosts (1) y Añadir cuenta (2)' mod='whatsboost'}" data-i18n-alt="settings.onb.hosts.alt">
                                </div>
                            </div>
                        </div>
                    </li>
                    <li style="margin:12px 0;">
                        <span data-i18n="settings.onb.link.click">{l s='Haz clic en' mod='whatsboost'}</span> <strong><span data-i18n="settings.onb.link.linkaccount">{l s='Vincular cuenta' mod='whatsboost'}</span></strong> <span data-i18n="settings.onb.link.scan">{l s='y escanea el QR con tu WhatsApp.' mod='whatsboost'}</span>
                        <div class="whatsboost-docs-row">
                            <div class="wb-browser-frame">
                                <div class="wb-browser-bar"><span class="wb-dot"></span><span class="wb-dot"></span><span class="wb-dot"></span></div>
                                <div class="wb-browser-body">
                                    <img class="whatsboost-docs-img js-wb-zoom" src="{$img_base}Captura de pantalla 2025-10-23 100939.png" alt="{l s='QR para vincular' mod='whatsboost'}" data-i18n-alt="settings.onb.qr.alt">
                                </div>
                            </div>
                            <div class="wb-browser-frame">
                                <div class="wb-browser-bar"><span class="wb-dot"></span><span class="wb-dot"></span><span class="wb-dot"></span></div>
                                <div class="wb-browser-body">
                                    <img class="whatsboost-docs-img js-wb-zoom" src="{$img_base}Captura de pantalla 2025-10-23 100958.png" alt="{l s='Paso: Vincular cuenta' mod='whatsboost'}" data-i18n-alt="settings.onb.link.alt">
                                </div>
                            </div>
                        </div>
                    </li>
                </ol>
                <p style="margin-top:12px; color:#334155;" data-i18n="settings.onb.back">{l s='Cuando tu cuenta esté conectada, vuelve aquí y pulsa “Verificar clave”. Detectaremos tu ID automáticamente.' mod='whatsboost'}</p>
                <div style="margin-top:16px;">
                    <h3 style="margin:0 0 8px;" data-i18n="settings.video.title">{l s='Vídeo: cómo escanear el QR y vincular tu WhatsApp' mod='whatsboost'}</h3>
                    <p style="margin:0 0 10px; color:#374151;" data-i18n="settings.video.desc">{l s='Si no sabes cómo escanear el QR, este vídeo te lo muestra paso a paso.' mod='whatsboost'}</p>
                    <div class="wb-video">
                        <iframe src="https://www.youtube.com/embed/sLV8Mhd_l_Y" title="{l s='Vincular dispositivo secundario de WhatsApp en WhatsBoost' mod='whatsboost'}" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
                    </div>
                </div>
                <div class="wb-page-footer">
                    <div class="wb-page-footer-inner">
                        <span class="wb-page-footer-text">WhatsBoost</span>
                        <img class="wb-page-footer-logo" src="{$module_dir|escape:'htmlall':'UTF-8'}views/img/almc-logo.webp" alt="Logo" onerror="this.style.display='none'" />
                    </div>
                </div>
            </div>
            {literal}
            <script>
            (function(){
              var footer = document.querySelector('.wb-page-footer');
              var anchor = document.querySelector('.wb-video');
              if(!footer || !anchor){ return; }
              function place(){
                try {
                  var r = anchor.getBoundingClientRect();
                  footer.style.left = r.left + 'px';
                  footer.style.width = r.width + 'px';
                  footer.style.right = 'auto';
                } catch(e){}
              }
              place();
              window.addEventListener('resize', place);
            })();
            </script>
            {/literal}
            <aside class="whatsboost-docs-aside wb-tipcard">
                <h3 style="margin-top:0;" data-i18n="settings.tip.title">{l s='Consejo' mod='whatsboost'}</h3>
                <p style="margin:8px 0; color:#374151;" data-i18n="settings.tip.1">{l s='Si ya tienes la sesión de WhatsApp Web abierta en tu móvil, el QR se vincula en segundos. Asegúrate de que tu línea aparece como connected en el panel.' mod='whatsboost'}</p>
                <p style="margin:8px 0; color:#374151;" data-i18n="settings.tip.2">{l s='Tras vincular, el ID único se guardará aquí como “ID de cuenta detectado”.' mod='whatsboost'}</p>
            </aside>
        </div>
    </div>

    {literal}
    <script>
    (function(){
      try{
        var lang=(document.documentElement.getAttribute('lang')||'').toLowerCase();
        var isEN = lang.indexOf('en')===0;
        window.wbI18n = {
          isEN: isEN,
          dict: {
            'settings.license': 'License verification',
            'settings.secret': 'Secret',
            'settings.secret.ph': 'Paste your private key here.',
            'settings.verify': 'Verify key',
            'settings.msg.enter': 'Enter your key (Secret) to verify it.',
            'settings.msg.confirm': 'You are about to change the saved key. If you proceed, the previous one will be replaced. Are you sure you want to continue?',
            'settings.msg.wait': 'Verifying, please wait...',
            'settings.msg.http': 'HTTP error',
            'settings.msg.ok': 'Valid key',
            'settings.msg.fail': 'Verification failed',
            'settings.msg.invalid': 'Invalid server response',
            'settings.msg.net': 'Network error during verification.',
            'settings.notice.needunique': 'The key is verified, but you still need to link the WhatsApp number from which messages will be sent. Connect it to obtain your id_unique and be able to send messages.',
            'settings.notice.ok': 'All set. We will send WhatsApps from your number.',
            'acc.title.number': 'Number to send WhatsApps',
            'acc.title.accounts': 'WhatsApp accounts',
            'acc.th.phone': 'Phone',
            'acc.th.id': 'Account ID',
            'acc.th.status': 'Status',
            'acc.tip.select': 'You will only see working (connected) accounts in this dropdown. If you have several, choose here the one you want to use.',
            'acc.tip.status': 'If a number appears as Not working, it is because it is not connected. Link it and return to this page.',
            'accounts.loading': 'Loading accounts...',
            'accounts.works': 'Works',
            'accounts.noworks': 'Does not work',
            'accounts.none': 'No accounts',
            'accounts.select': 'Select account...',
            'settings.onb.title': 'Don\'t have your number connected yet?',
            'settings.onb.desc': 'Follow these steps to connect your WhatsApp so we can send messages from your number.',
            'settings.onb.login': 'Log in to your account:',
            'settings.onb.back': 'When your account is connected, come back here and click “Verify key”. We\'ll detect your ID automatically.',
            'settings.video.title': 'Video: how to scan the QR and link your WhatsApp',
            'settings.video.desc': 'If you don\'t know how to scan the QR, this video shows it step by step.',
            'settings.tip.title': 'Tip',
            'settings.tip.1': 'If you already have WhatsApp Web session open on your phone, the QR links in seconds. Make sure your line shows as connected on the panel.',
            'settings.tip.2': 'After linking, the unique ID will be saved here as “Detected account ID”.',
            
            /* New onboarding host/link steps */
            'settings.onb.hosts.pre': 'In the left menu, go to',
            'settings.onb.hosts.or': 'or go straight to',
            'settings.onb.hosts.thisurl': 'this URL',
            'settings.onb.hosts.then': 'Then click',
            'settings.onb.hosts.add': 'Add account',
            'settings.onb.hosts.aspic': 'as in the screenshot.',
            'settings.onb.hosts.alt': 'Step: Hosts (1) and Add account (2)',
            'settings.onb.link.click': 'Click on',
            'settings.onb.link.linkaccount': 'Link account',
            'settings.onb.link.scan': 'and scan the QR with your WhatsApp.',
            'settings.onb.qr.alt': 'QR to link',
            'settings.onb.link.alt': 'Step: Link account'
          },
          t: function(k, def){ if(this.isEN && this.dict[k]) return this.dict[k]; return def || this.dict[k] || k; }
        };
      }catch(e){}
    })();
    </script>
    {/literal}
    {literal}
    <script>
    (function(){
      try{
        if(!(window.wbI18n && wbI18n.isEN)) return;
        var scope = document.querySelector('.porto-admin-card');
        if(!scope) return;
        scope.querySelectorAll('[data-i18n]').forEach(function(el){
          var k = el.getAttribute('data-i18n');
          if(k){ el.textContent = wbI18n.t(k, el.textContent||''); }
        });
        scope.querySelectorAll('[data-i18n-ph]').forEach(function(el){
          var k = el.getAttribute('data-i18n-ph');
          if(k){ el.setAttribute('placeholder', wbI18n.t(k, el.getAttribute('placeholder')||'')); }
        });
      }catch(e){}
    })();
    </script>
    {/literal}
    {literal}
    <script>
        (function(){
            var form = document.getElementById('wb_license_form');
            if(!form) return;
            var input = form.querySelector('#wb_secret');
            var confirmField = form.querySelector('#wb_confirm_overwrite');
            var existing = "{/literal}{$settings.secret|escape:'javascript':'UTF-8'}{literal}";
            var btn = document.getElementById('wb_verify_btn');
            var ajaxUrl = "{/literal}{$ajax_url|escape:'javascript':'UTF-8'}{literal}";

            function showMessage(ok, msg){
                var holder = document.getElementById('wb_msg') || form.parentNode;
                var old = holder.querySelector('.wb-ajax-msg');
                if(old) old.parentNode.removeChild(old);
                var div = document.createElement('div');
                div.className = 'wb-ajax-msg ' + (ok ? 'wb-alert wb-alert--info' : 'wb-alert wb-alert--danger');
                div.setAttribute('role', ok ? 'status' : 'alert');
                div.textContent = msg;
                holder.insertBefore(div, holder.firstChild || null);
                try { holder.scrollIntoView({behavior:'smooth',block:'start'}); } catch(e) {}
            }

            function renderUniqueNotice(show){
                var box = document.getElementById('wb_unique_notice');
                if(!box) return;
                if(show){
                    var msg = (window.wbI18n && typeof wbI18n.t==='function') ? wbI18n.t('settings.notice.needunique','La clave está verificada, pero aún falta vincular el número de WhatsApp desde el que se enviarán los mensajes. Conéctalo para obtener tu id_unique y poder enviar mensajes.') : 'La clave está verificada, pero aún falta vincular el número de WhatsApp desde el que se enviarán los mensajes. Conéctalo para obtener tu id_unique y poder enviar mensajes.';
                    box.innerHTML = '<div class="wb-alert wb-alert--warn" role="status">'+ msg +'</div>';
                } else {
                    box.innerHTML = '';
                }
            }
            function renderOkNotice(show){
                var ok = document.getElementById('wb_ok_notice');
                if(!ok) return;
                if(show){
                    var msgOk = (window.wbI18n && typeof wbI18n.t==='function') ? wbI18n.t('settings.notice.ok','Todo correcto. Enviaremos WhatsApps desde tu numero.') : 'Todo correcto. Enviaremos WhatsApps desde tu numero.';
                    ok.innerHTML = '<div class=\"wb-alert wb-alert--ok\" role=\"status\">'+ msgOk +'</div>';
                } else {
                    ok.innerHTML = '';
                }
            }
            // Mostrar/ocultar documentación de onboarding
            function wbToggleOnboarding(show){
                try {
                    var nodes = document.querySelectorAll('.wb-settings-onboarding');
                    if(nodes && nodes.length){ nodes.forEach(function(n){ n.style.display = show ? '' : 'none'; }); }
                } catch(e){}
            }
            window.wbToggleOnboarding = wbToggleOnboarding;
            btn.addEventListener('click', function(){
                var secret = (input.value||'').trim();
                if(!secret){ showMessage(false, (window.wbI18n? wbI18n.t('settings.msg.enter','Escribe tu clave (Secret) para verificarla.') : 'Escribe tu clave (Secret) para verificarla.')); return; }
                var confirmOverwrite = 0;
                if(existing && secret !== existing){
                    var ok = window.confirm((window.wbI18n? wbI18n.t('settings.msg.confirm','Vas a cambiar la clave guardada. Si sigues, se reemplazará la anterior. ¿Seguro que quieres continuar?') : 'Vas a cambiar la clave guardada. Si sigues, se reemplazará la anterior. ¿Seguro que quieres continuar?'));
                    if(!ok){ return; }
                    confirmOverwrite = 1;
                }

                showMessage(true, (window.wbI18n? wbI18n.t('settings.msg.wait','Verificando, por favor espera...') : 'Verificando, por favor espera...'));; try { renderOkNotice(false); } catch(e){}

                var body = 'ajax=1&action=verify&secret=' + encodeURIComponent(secret) + '&confirm_overwrite=' + confirmOverwrite;
                fetch(ajaxUrl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: body,
                    credentials: 'same-origin'
                })
                    .then(function(r){
                        return r.text().then(function(text){ return { status:r.status, ok:r.ok, text:text }; });
                    })
                    .then(function(resp){
                        var json = null;
                        try { json = resp.text ? JSON.parse(resp.text) : null; } catch(e) {}

                        if(!resp.ok){
                            var snippet = (resp.text||'').slice(0,300);
                            var httpLabel = (window.wbI18n? wbI18n.t('settings.msg.http','Error HTTP') : 'Error HTTP');
                            showMessage(false, httpLabel + ' ' + resp.status + (snippet? (': ' + snippet) : ''));
                            try { renderUniqueNotice(false); } catch(e){}
                            if(typeof window.wbToggleOnboarding==='function'){ window.wbToggleOnboarding(false); }
                            return;
                        }

                        if(json && typeof json.ok !== 'undefined'){
                            var okText = (window.wbI18n? wbI18n.t('settings.msg.ok','Clave valida') : 'Clave valida');
                            var failText = (window.wbI18n? wbI18n.t('settings.msg.fail','Verificacion fallida') : 'Verificacion fallida');
                            showMessage(json.ok, json.message || (json.ok ? okText : failText));
                            if(json.saved){ existing = secret; confirmField.value = '0'; }
                            if(json.ok){
                                var need = (json.needs_unique === 1) || (!json.unique);
                                // Hide persistent invalid-secret banner immediately on success
                                try { var inv = document.getElementById('wb_invalid_secret'); if(inv){ inv.style.display='none'; } } catch(e){}
                                renderUniqueNotice(need);
                                if(typeof window.wbToggleAccounts==='function'){ window.wbToggleAccounts(!need); }
                                if(typeof window.wbToggleOnboarding==='function'){ window.wbToggleOnboarding(need); }
                                renderOkNotice(!need);
                            } else {
                                renderOkNotice(false);
                                try { renderUniqueNotice(false); } catch(e){}
                                if(typeof window.wbToggleAccounts==='function'){ window.wbToggleAccounts(false); }
                                if(typeof window.wbToggleOnboarding==='function'){ window.wbToggleOnboarding(false); }
                            }
                            // Fuerza refresco inmediato de los avisos globales (toast) sin esperar al polling
                            if(typeof window.wbStatusRefresh==='function'){ try{ window.wbStatusRefresh(); }catch(e){} }
                        } else {
                            var snippet2 = (resp.text||'').slice(0,300);
                            var invalidMsg = (window.wbI18n? wbI18n.t('settings.msg.invalid','Respuesta no valida del servidor') : 'Respuesta no valida del servidor');
                            showMessage(false, invalidMsg + (snippet2? (': ' + snippet2) : ''));
                        }
                    })
                    .catch(function(){
                        var netMsg = (window.wbI18n? wbI18n.t('settings.msg.net','Error de red al verificar.') : 'Error de red al verificar.');
                        showMessage(false, netMsg);
                        try { renderUniqueNotice(false); } catch(e){}
                        if(typeof window.wbToggleOnboarding==='function'){ window.wbToggleOnboarding(false); }
                    });
            });
        })();
    </script>
    {/literal}

    <div id="wb_accounts_section"{if !$settings.verified || !$settings.unique} style="display:none"{/if}>
    <div class="wb-card">
        <h3 class="wb-card-title" data-i18n="acc.title.number">{l s='Numero para enviar WhatsApps' mod='whatsboost'}</h3>
        <form id="wb_unique_form" action="{$admin_base|escape:'htmlall':'UTF-8'}" method="post" style="margin:8px 0;">
            <select id="wb_numbers_select" class="wb-input" style="max-width:460px">
                <option value="" data-i18n="accounts.loading">{l s='Cargando cuentas...' mod='whatsboost'}</option>
            </select>
            <input type="hidden" name="WB_SELECTED_UNIQUE" id="wb_selected_unique" value="" />
        </form>
        <p class="wb-subtle" data-i18n="acc.tip.select">{l s='Solo veras en este desplegable las cuentas que funcionan (conectadas). Si tienes varias, elige aqui la que quieras usar.' mod='whatsboost'}</p>
    </div>

    <div class="wb-card" id="wb_accounts_card">
        <h3 class="wb-card-title" data-i18n="acc.title.accounts">{l s='Cuentas de WhatsApp' mod='whatsboost'}</h3>
        <div class="wb-table-wrap">
            <table class="table" id="wb_accounts_table" style="width:100%">
                <thead>
                    <tr>
                        <th data-i18n="acc.th.phone">{l s='Telefono' mod='whatsboost'}</th>
                        <th data-i18n="acc.th.id">{l s='ID de cuenta' mod='whatsboost'}</th>
                        <th data-i18n="acc.th.status">{l s='Estado' mod='whatsboost'}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr><td colspan="3" data-i18n="accounts.loading">{l s='Cargando cuentas...' mod='whatsboost'}</td></tr>
                </tbody>
            </table>
        </div>
        <p class="wb-subtle" style="margin-top:8px;" data-i18n="acc.tip.status">{l s='Si un numero aparece como No funciona, es porque no esta conectado. Vinculalo y vuelve a esta pagina.' mod='whatsboost'}</p>
    </div>

    {literal}
    <script>
    (function(){
        var ajaxUrl = "{/literal}{$ajax_url|escape:'javascript':'UTF-8'}{literal}";
        var selectEl = document.getElementById('wb_numbers_select');
        var hiddenUnique = document.getElementById('wb_selected_unique');
        var formUnique = document.getElementById('wb_unique_form');
        var tableBody = document.querySelector('#wb_accounts_table tbody');
        var btnRefresh = null;
        var section = document.getElementById('wb_accounts_section');
        var savedUnique = "{/literal}{$settings.unique|escape:'javascript':'UTF-8'}{literal}";

        function statusLabel(s){
            var ok = (String(s||'').toLowerCase() === 'connected');
            var yes = (window.wbI18n? wbI18n.t('accounts.works','Funciona') : 'Funciona');
            var no = (window.wbI18n? wbI18n.t('accounts.noworks','No funciona') : 'No funciona');
            return ok ? yes : no;
        }
        function statusClass(s){
            var val = String(s||'').toLowerCase();
            if(val==='connected'){ return 'wb-badge wb-badge--ok'; }
            if(val==='pending' || val==='connecting'){ return 'wb-badge wb-badge--warn'; }
            return 'wb-badge wb-badge--danger';
        }

        function maskUnique(u){ if(!u) return ''; return String(u).slice(0,8) + '...' + String(u).slice(-6); }

        function paint(accounts){
            tableBody.innerHTML = '';
            if(!accounts || !accounts.length){
                var tr = document.createElement('tr');
                var td = document.createElement('td'); td.colSpan = 3; td.textContent = (window.wbI18n? wbI18n.t('accounts.none','Sin cuentas') : 'Sin cuentas');
                tr.appendChild(td); tableBody.appendChild(tr);
            } else {
                accounts.forEach(function(a){
                    var tr = document.createElement('tr');
                    var td1 = document.createElement('td'); td1.textContent = a.phone || '';
                    var td2 = document.createElement('td'); var code = document.createElement('code'); code.textContent = maskUnique(a.unique||''); td2.appendChild(code);
                    var td3 = document.createElement('td');
                    var badge = document.createElement('span');
                    badge.className = statusClass(a.status);
                    badge.textContent = statusLabel(a.status);
                    td3.appendChild(badge);
                    tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3);
                    tableBody.appendChild(tr);
                });
            }

            var options = [];
            (accounts||[]).forEach(function(a){ if(String(a.status).toLowerCase()==='connected'){ options.push({value:a.unique, label:a.phone||a.unique, id:a.id||0, phone:a.phone||''}); } });
            selectEl.innerHTML = '';
            options.forEach(function(op){ var o=document.createElement('option'); o.value = op.value||''; o.textContent = op.label||''; if(op.id){ o.setAttribute('data-id', String(op.id)); } if(op.phone){ o.setAttribute('data-phone', String(op.phone)); } selectEl.appendChild(o); });
            // Auto-select: pick savedUnique if still valid, otherwise first working account
            var picked = '';
            if(savedUnique){
                for(var i=0;i<options.length;i++){ if(options[i].value===savedUnique){ picked = savedUnique; break; } }
            }
            if(!picked && options.length>0){ picked = options[0].value || ''; }
            if(picked){
                selectEl.value = picked;
                // Persist automatically if changed, via AJAX (no reload)
                if(picked !== (savedUnique||'')){
                    var opt = selectEl.options[selectEl.selectedIndex];
                    var accId = parseInt(opt && opt.getAttribute('data-id') ? opt.getAttribute('data-id') : '0', 10) || 0;
                    var phone = opt ? (opt.getAttribute('data-phone') || opt.textContent || '') : '';
                    persistSelection(picked, accId, phone, true);
                }
            }
        }

        function toast(ok, msg){
            try{
                var holder = document.getElementById('wb_accounts_card') || section || document.body;
                var old = holder.querySelector('.wb-ajax-msg');
                if(old){ old.parentNode.removeChild(old); }
                var div = document.createElement('div');
                div.className = 'wb-ajax-msg ' + (ok ? 'wb-alert wb-alert--info' : 'wb-alert wb-alert--danger');
                div.setAttribute('role', ok ? 'status' : 'alert');
                div.textContent = msg || (ok? 'Hecho' : 'Error');
                // Insert on top of accounts card
                if(holder.firstChild){ holder.insertBefore(div, holder.firstChild); } else { holder.appendChild(div); }
                setTimeout(function(){ try{ if(div && div.parentNode){ div.parentNode.removeChild(div); } }catch(e){} }, 3000);
            }catch(e){}
        }

        function persistSelection(unique, accountId, phone, isAuto){
            if(!unique){ return; }
            var body = 'ajax=1&action=saveUnique&unique=' + encodeURIComponent(unique) + '&account_id=' + (parseInt(accountId||0,10)||0) + '&phone=' + encodeURIComponent(phone||'');
            fetch(ajaxUrl, { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: body, credentials:'same-origin' })
                .then(function(r){ return r.text().then(function(t){ return {ok:r.ok, text:t}; }); })
                .then(function(resp){ var json=null; try{ json = JSON.parse(resp.text||'{}'); }catch(e){}
                    if(json && json.ok){ savedUnique = unique; hiddenUnique.value = unique; toast(true, json.message||'Se utilizará este número para enviar WhatsApps.'); if(typeof window.wbStatusRefresh==='function'){ try{ window.wbStatusRefresh(); }catch(e){} } }
                    else { var msg = (json && json.message) ? json.message : 'No se pudo guardar la selección.'; toast(false, msg); }
                })
                .catch(function(){ toast(false, 'Error de red'); });
        }

        function load(){
            if(section && section.style.display === 'none'){ return; }
            var body = 'ajax=1&action=accounts';
            fetch(ajaxUrl, { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: body, credentials:'same-origin' })
                .then(function(r){ return r.text().then(function(t){ return {ok:r.ok, text:t}; }); })
                .then(function(resp){ var json=null; try{ json = JSON.parse(resp.text||'{}'); }catch(e){}
                    if(json && json.accounts){ paint(json.accounts); }
                })
                .catch(function(){});
        }

        // Guardar por AJAX al cambiar la selección (sin recargar)
        if(formUnique && selectEl){
            selectEl.addEventListener('change', function(){
                var val = selectEl.value || '';
                var opt = selectEl.options[selectEl.selectedIndex];
                var accId = parseInt(opt && opt.getAttribute('data-id') ? opt.getAttribute('data-id') : '0', 10) || 0;
                var phone = opt ? (opt.getAttribute('data-phone') || opt.textContent || '') : '';
                hiddenUnique.value = val;
                persistSelection(val, accId, phone, false);
            });
        }

        window.wbAccountsReload = load;
        // toggle helper from verify flow (solo cuentas)
        window.wbToggleAccounts = function(show){
            if(section){ section.style.display = show ? '' : 'none'; if(show){ load(); } }
        };
        load();
    })();
    </script>
    {/literal}
</div>
</div>


