/* ---- legacy style block 1 ---- */

    :root {
      --bg-main: #0b1120;
      --bg-card: #131c31;
      --bg-card-hover: #1b2742;
      --border-color: #24324f;
      --text-main: #f1f5f9;
      --text-muted: #94a3b8;
      --accent: #10b981;
      --accent-soft: rgba(16, 185, 129, 0.14);
      --accent-secondary: #3b82f6;
    }

    body {
      font-family: 'Vazirmatn', sans-serif;
      background-color: var(--bg-main);
      color: var(--text-main);
      transition: background-color 0.25s ease, color 0.25s ease;
      overflow-x: hidden;
    }

    .theme-card {
      background-color: var(--bg-card);
      border: 1px solid var(--border-color);
      transition: all 0.2s ease;
    }

    .theme-card:hover {
      border-color: var(--accent);
    }

    .theme-border {
      border-color: var(--border-color);
    }

    .theme-text-muted {
      color: var(--text-muted);
    }

    .btn-accent {
      background-color: var(--accent);
      color: #ffffff;
      transition: opacity 0.2s ease, transform 0.1s ease;
    }

    .btn-accent:hover {
      opacity: 0.92;
    }

    .btn-accent:active {
      transform: scale(0.98);
    }

    .badge-accent {
      background-color: var(--accent-soft);
      color: var(--accent);
      border: 1px solid var(--accent);
    }

    .tab-active {
      background-color: var(--accent-soft);
      color: var(--accent);
      border-bottom: 2px solid var(--accent);
      font-weight: 700;
    }

    .sidebar-tab-active {
      background-color: var(--accent-soft);
      color: var(--accent);
      border-right: 3px solid var(--accent);
      font-weight: 700;
    }

    ::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }
    ::-webkit-scrollbar-track {
      background: var(--bg-main);
    }
    ::-webkit-scrollbar-thumb {
      background: var(--border-color);
      border-radius: 9999px;
    }
    ::-webkit-scrollbar-thumb:hover {
      background: var(--accent);
    }
      :root {
      --sx-btn-bg: #10b981;
      --sx-btn-text: #ffffff;
      --sx-btn-border-col: #34d399;
      --sx-btn-border-w: 1px;
      --sx-btn-border-style: solid;
      --sx-btn-radius: 12px;
      --sx-btn-font-size: 12px;
      --sx-btn-font-weight: 700;
    }
    .btn-accent {
      background: var(--sx-btn-bg) !important;
      color: var(--sx-btn-text) !important;
      border: var(--sx-btn-border-w) var(--sx-btn-border-style) var(--sx-btn-border-col) !important;
      border-radius: var(--sx-btn-radius) !important;
      font-size: var(--sx-btn-font-size) !important;
      font-weight: var(--sx-btn-font-weight) !important;
      transition: all 0.2s ease !important;
    }
    .btn-accent:hover { filter: brightness(1.08); transform: translateY(-1px); }

    main#mainContentWorkspace,
    main#mainContentWorkspace > section {
      width: 100% !important;
      max-width: 100% !important;
    }
    body, .theme-card, header, nav, main {
      transition: background-color 0.28s ease, border-color 0.28s ease, color 0.2s ease;
    }
  
    /* =========================================================================
       v4.4 MINIMAL 2-COLUMN (50% / 50%) & SINGLE-LINE NON-WRAPPING UI STANDARD
       ========================================================================= */
    .sx-two-col-grid {
      display: grid;
      grid-template-columns: repeat(1, minmax(0, 1fr));
      gap: 1.5rem;
      align-items: start;
    }
    @media (min-width: 1024px) {
      .sx-two-col-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
      }
    }
    .sx-setting-row {
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
      justify-content: space-between;
      gap: 1rem;
      padding: 0.7rem 0.95rem;
      border-radius: 0.85rem;
      background: rgba(6, 11, 20, 0.55);
      border: 1px solid rgba(51, 65, 85, 0.55);
      transition: border-color 0.2s ease;
    }
    .sx-setting-row:hover {
      border-color: rgba(56, 189, 248, 0.45);
    }
    .sx-setting-row label,
    .sx-single-line {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    details.sx-accordion > summary {
      list-style: none;
      cursor: pointer;
      user-select: none;
    }
    details.sx-accordion > summary::-webkit-details-marker {
      display: none;
    }
    details.sx-accordion .sx-acc-arrow {
      transition: transform 0.22s ease;
      display: inline-block;
    }
    details.sx-accordion[open] .sx-acc-arrow {
      transform: rotate(180deg);
    }
  

/* ---- legacy style block 2 ---- */

        .sx-caption-box-wrap .sx-rt-toolbar,
        .sx-caption-box-wrap [class*="toolbar"] { display: none; }
        .sx-caption-box-wrap:focus-within .sx-rt-toolbar,
        .sx-caption-box-wrap:focus-within [class*="toolbar"] { display: flex; }
      

/* ---- legacy style block 3 ---- */

  body { font-family: Tahoma, sans-serif; background:#0b1120; color:#f1f5f9; padding:24px; line-height:1.7; }
  .card { background:#131c31; border:1px solid #24324f; border-radius:16px; padding:20px; margin-bottom:20px; }
  table { width:100%; border-collapse:collapse; font-size:13px; text-align:right; }
<\/style>
<\/head>
<body>
  <div class="card" style="border-right:5px solid #10b981;">
    <h2 style="margin:0 0 6px 0;color:#10b981;">📊 کارنامه هوشمند رشد و آنالیز باگ‌ها: ${profile.persianName}</h2>
    <p style="margin:0;font-size:13px;color:#94a3b8;">تعداد کل تمرین‌ها: ${profile.totalSubmissions} | میانگین نمره: ${profile.avgScore} از ۱۰</p>
  </div>
  <div class="card">
    <h3 style="margin-top:0;color:#fbbf24;">🐞 خلاصه وضعیت</h3>
    <p><strong>💪 نقطه قوت:</strong> ${profile.topStrength}</p>
    <p><strong>⚠️ باگ پرتکرار:</strong> ${profile.topBug}</p>
  </div>
  <div class="card">
    <h3 style="margin-top:0;color:#38bdf8;">🗂️ تاریخچه تمرین‌ها</h3>
    <table>
      <thead>
        <tr style="color:#94a3b8;border-bottom:2px solid #24324f;">
          <th style="padding:10px;">دانشجو</th>
          <th style="padding:10px;">تاریخ</th>
          <th style="padding:10px;">نماد</th>
          <th style="padding:10px;">جلسه</th>
          <th style="padding:10px;">نمره</th>
          <th style="padding:10px;">نکته ثبت‌شده</th>
        </tr>
      </thead>
      <tbody>${rowsHtml}</tbody>
    </table>
  </div>
<\/body>
<\/html>`;
    }

    function openStudentHtmlReportModal() {
      const profile = computeAggregatedProfile();
      const modal = document.getElementById('studentHtmlReportModal');
      const titleEl = document.getElementById('modalReportStudentTitle');
      const container = document.getElementById('studentHtmlPreviewContainer');
      if (titleEl) titleEl.textContent = `پیش‌نمایش فایل کارنامه HTML: «${profile.persianName}»`;
      if (container) {
        container.innerHTML = `
          <div class="p-4 rounded-xl bg-emerald-950/40 border border-emerald-500/40 flex flex-wrap items-center justify-between gap-3">
            <div class="text-sm font-bold text-emerald-400">📊 کارنامه رسمی: ${profile.persianName} (${profile.totalSubmissions} تمرین)</div>
            <span class="px-3 py-1 rounded-full bg-emerald-500/20 text-emerald-300 font-bold text-xs">میانگین: ${profile.avgScore} از ۱۰</span>
          </div>
          <div class="p-4 rounded-xl bg-slate-900 border border-slate-800 space-y-2">
            <p class="text-emerald-300"><strong>💪 نقطه قوت:</strong> ${profile.topStrength}</p>
            <p class="text-rose-300"><strong>⚠️ باگ اصلی:</strong> ${profile.topBug}</p>
          </div>
        `;
      }
      if (modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); }
    }

    function closeStudentHtmlReportModal() {
      const modal = document.getElementById('studentHtmlReportModal');
      if (modal) { modal.classList.add('hidden'); modal.classList.remove('flex'); }
    }

    function downloadStandaloneStudentHtml() {
      const profile = computeAggregatedProfile();
      const htmlContent = buildStandaloneReportHtmlString(profile);
      const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `Trading_ReportCard.html`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      showToast('فایل کارنامه HTML دانلود شد!');
    }

    // ==========================================
    // TAB 3: AUTHORIZED ADMINS & ROLES
    // ==========================================
    function renderCustomRoles() {
      const roleSelect = document.getElementById('newAdminRole');
      const badgeContainer = document.getElementById('customRolesBadgeList');
      if (roleSelect) {
        roleSelect.innerHTML = appState.availableRoles.map(r => `<option value="${r}">${r}</option>`).join('');
      }
      if (badgeContainer) {
        badgeContainer.innerHTML = appState.availableRoles.map((r, idx) => `
          <span class="inline-flex items-center gap-2 px-2.5 py-1 rounded-lg text-xs bg-emerald-500/15 text-emerald-300 border border-emerald-500/30 font-semibold">
            <span>${r}</span>
            <button onclick="startRoleRename(${idx})" class="text-amber-300 hover:text-amber-100" title="ویرایش نام نقش">✏️</button>
            <button onclick="deleteCustomRole(${idx})" class="text-rose-400 hover:text-rose-200 font-bold" title="حذف این نقش">✕</button>
          </span>
        `).join('');
      }
    }

    function addCustomRole() {
      const inp = document.getElementById('newCustomRoleInput');
      if (!inp || !inp.value.trim()) {
        showToast('لطفاً عنوان نقش جدید را بنویسید.', '⚠️');
        return;
      }
      const roleName = inp.value.trim();
      if (!appState.availableRoles.includes(roleName)) {
        appState.availableRoles.push(roleName);
      }
      inp.value = '';
      renderCustomRoles();
      renderAuthorizedAdmins();
      renderPanelSubAdmins();
      applyLoginAndFaviconUI();
      syncConfigToBotServer(`نقش جدید «${roleName}» ساخته شد.`);
    }

    function deleteCustomRole(idx) {
      const removed = appState.availableRoles[idx];
      appState.availableRoles.splice(idx, 1);
      renderCustomRoles();
      renderAuthorizedAdmins();
      renderPanelSubAdmins();
      applyLoginAndFaviconUI();
      syncConfigToBotServer(`نقش «${removed}» حذف شد.`, '🗑️');
    }

    function startRoleRename(idx) {
      editingRoleIndex = idx;
      const box = document.getElementById('editRoleInlineBox');
      const inp = document.getElementById('editRoleInlineInput');
      if (box && inp) {
        inp.value = appState.availableRoles[idx] || '';
        box.classList.remove('hidden');
        box.classList.add('flex');
      }
    }

    function saveRoleRename() {
      if (editingRoleIndex === null) return;
      const inp = document.getElementById('editRoleInlineInput');
      if (!inp || !inp.value.trim()) return;
      const oldName = appState.availableRoles[editingRoleIndex];
      const newName = inp.value.trim();
      appState.availableRoles[editingRoleIndex] = newName;
      appState.authorizedAdmins.forEach(a => { if (a.role === oldName) a.role = newName; });
      cancelRoleRename();
      renderCustomRoles();
      renderAuthorizedAdmins();
      renderPanelSubAdmins();
      applyLoginAndFaviconUI();
      syncConfigToBotServer(`نام نقش به «${newName}» تغییر یافت.`);
    }

    function cancelRoleRename() {
      editingRoleIndex = null;
      const box = document.getElementById('editRoleInlineBox');
      if (box) { box.classList.add('hidden'); box.classList.remove('flex'); }
    }

    function startAdminInlineEdit(adminId) {
      const adm = appState.authorizedAdmins.find(a => a.id === adminId);
      if (!adm) return;
      editingAdminId = adminId;
      const box = document.getElementById('editAdminInlineBox');
      const nameInp = document.getElementById('editAdminNameInput');
      const userInp = document.getElementById('editAdminUsernameInput');
      if (box && nameInp && userInp) {
        nameInp.value = adm.name;
        userInp.value = adm.username;
        box.classList.remove('hidden');
        box.classList.add('flex');
      }
    }

    function saveAdminInlineEdit() {
      if (editingAdminId === null) return;
      const adm = appState.authorizedAdmins.find(a => a.id === editingAdminId);
      const nameInp = document.getElementById('editAdminNameInput');
      const userInp = document.getElementById('editAdminUsernameInput');
      if (adm && nameInp && userInp && userInp.value.trim()) {
        adm.name = nameInp.value.trim() || adm.name;
        let u = userInp.value.trim();
        if (!u.startsWith('@') && isNaN(Number(u))) u = '@' + u;
        adm.username = u;
        renderAuthorizedAdmins();
      renderPanelSubAdmins();
      applyLoginAndFaviconUI();
        syncConfigToBotServer('مشخصات آیدی مجاز ویرایش شد.');
      }
      cancelAdminInlineEdit();
    }

    function cancelAdminInlineEdit() {
      editingAdminId = null;
      const box = document.getElementById('editAdminInlineBox');
      if (box) { box.classList.add('hidden'); box.classList.remove('flex'); }
    }

    function changeAdminRole(adminId, newRole) {
      const adm = appState.authorizedAdmins.find(a => a.id === adminId);
      if (adm) {
        adm.role = newRole;
        syncConfigToBotServer(`نقش ${window.escHtml(adm.name)} به «${newRole}» تغییر یافت.`);
      }
    }

    function toggleTelegramAdminPerm(adminId, permKey, checked) {
      const adm = appState.authorizedAdmins.find(a => a.id === adminId);
      if (!adm) return;
      if (!adm.perms || typeof adm.perms !== 'object') {
        adm.perms = { correct: true, announce: true, dm: true, settings: adm.role !== 'دستیار استاد' };
      }
      adm.perms[permKey] = !!checked;
      renderAuthorizedAdmins();
      syncConfigToBotServer(`مجوزهای تلگرامی «${window.escHtml(adm.name)}» بروزرسانی و ذخیره شد! 🔐`);
    }

    function renderAuthorizedAdmins() {
      renderCustomRoles();
      const list = document.getElementById('authorizedAdminsList');
      if (!list) return;
      if (appState.authorizedAdmins.length === 0) {
        list.innerHTML = `<div class="p-4 rounded-xl bg-black/20 border theme-border text-xs theme-text-muted text-center">هیچ آیدی مجازی ثبت نشده است.</div>`;
        return;
      }
      list.innerHTML = appState.authorizedAdmins.map(a => {
        const roleOptions = appState.availableRoles.map(r => `<option value="${r}" ${r === a.role ? 'selected' : ''}>${r}</option>`).join('');
        const p = a.perms || { correct: true, announce: true, dm: true, settings: a.role !== 'دستیار استاد' };
        return `
          <div class="p-3.5 rounded-xl bg-black/25 border theme-border space-y-2.5">
            <div class="flex flex-wrap items-center justify-between gap-3">
              <div class="flex items-center gap-3">
                <div class="w-9 h-9 rounded-xl bg-emerald-500/20 text-emerald-400 flex items-center justify-center font-bold text-sm">🛡️</div>
                <div>
                  <div class="text-xs font-bold">${a.name}</div>
                  <div class="text-xs font-mono text-emerald-400 mt-0.5" dir="ltr">${a.username}</div>
                </div>
              </div>
              <div class="flex items-center gap-2">
                <select onchange="changeAdminRole(${a.id}, this.value)" class="px-2.5 py-1 rounded-lg text-xs bg-black/40 border theme-border text-sky-300 font-semibold">
                  ${roleOptions}
                </select>
                <button onclick="startAdminInlineEdit(${a.id})" class="text-xs text-amber-300 hover:text-amber-200 px-2.5 py-1 rounded-lg border border-amber-500/30">✏️ ویرایش</button>
                <button onclick="removeAuthorizedAdmin(${a.id})" class="text-xs text-rose-400 hover:text-rose-300 px-2.5 py-1 rounded-lg border border-rose-500/30">حذف</button>
              </div>
            </div>
            <div class="pt-2 border-t border-slate-800/80 flex flex-wrap items-center gap-2 text-[10px]">
              <span class="theme-text-muted font-bold">دسترسی در تلگرام (<code dir="ltr">/admin</code>):</span>
              <label class="inline-flex items-center gap-1 px-2 py-1 rounded-lg border cursor-pointer ${p.correct !== false ? 'bg-emerald-500/15 border-emerald-500/40 text-emerald-300 font-bold' : 'bg-black/30 border-slate-700 text-slate-400'}">
                <input type="checkbox" ${p.correct !== false ? 'checked' : ''} onchange="toggleTelegramAdminPerm(${a.id}, 'correct', this.checked)" class="accent-emerald-500 w-3.5 h-3.5" />
                <span>✏️ اصلاح چارت</span>
              </label>
              <label class="inline-flex items-center gap-1 px-2 py-1 rounded-lg border cursor-pointer ${p.announce !== false ? 'bg-amber-500/15 border-amber-500/40 text-amber-300 font-bold' : 'bg-black/30 border-slate-700 text-slate-400'}">
                <input type="checkbox" ${p.announce !== false ? 'checked' : ''} onchange="toggleTelegramAdminPerm(${a.id}, 'announce', this.checked)" class="accent-amber-500 w-3.5 h-3.5" />
                <span>📢 ارسال اطلاعیه تاپیک/کانال</span>
              </label>
              <label class="inline-flex items-center gap-1 px-2 py-1 rounded-lg border cursor-pointer ${p.dm !== false ? 'bg-sky-500/15 border-sky-500/40 text-sky-300 font-bold' : 'bg-black/30 border-slate-700 text-slate-400'}">
                <input type="checkbox" ${p.dm !== false ? 'checked' : ''} onchange="toggleTelegramAdminPerm(${a.id}, 'dm', this.checked)" class="accent-sky-500 w-3.5 h-3.5" />
                <span>✉️ پیام به پیوی دانشجو</span>
              </label>
              <label class="inline-flex items-center gap-1 px-2 py-1 rounded-lg border cursor-pointer ${p.settings ? 'bg-purple-500/15 border-purple-500/40 text-purple-300 font-bold' : 'bg-black/30 border-slate-700 text-slate-400'}">
                <input type="checkbox" ${p.settings ? 'checked' : ''} onchange="toggleTelegramAdminPerm(${a.id}, 'settings', this.checked)" class="accent-purple-500 w-3.5 h-3.5" />
                <span>🎛️ تنظیمات ربات و اخبار</span>
              </label>
              <label class="inline-flex items-center gap-1 px-2 py-1 rounded-lg border cursor-pointer ${p.live_class !== false ? 'bg-rose-500/15 border-rose-500/40 text-rose-300 font-bold' : 'bg-black/30 border-slate-700 text-slate-400'}">
                <input type="checkbox" ${p.live_class !== false ? 'checked' : ''} onchange="toggleTelegramAdminPerm(${a.id}, 'live_class', this.checked)" class="accent-rose-500 w-3.5 h-3.5" />
                <span>🔴 کلاس آنلاین زنده (یوزر/پسورد ویژه نقش)</span>
              </label>
            </div>
          </div>
        `;
      }).join('');
    }

    function addAuthorizedAdmin() {
      const nameInp = document.getElementById('newAdminName');
      const userInp = document.getElementById('newAdminUsername');
      const roleInp = document.getElementById('newAdminRole');
      if (!nameInp || !userInp || !userInp.value.trim()) {
        showToast('لطفاً آیدی تلگرام را وارد کنید.', '⚠️');
        return;
      }
      let rawUser = userInp.value.trim();
      if (!rawUser.startsWith('@') && isNaN(Number(rawUser))) rawUser = '@' + rawUser;
      const chosenRole = (roleInp && roleInp.value) ? roleInp.value : 'دستیار استاد';
      const pCorrect  = document.getElementById('newAdmPerm_correct')?.checked ?? true;
      const pAnnounce = document.getElementById('newAdmPerm_announce')?.checked ?? true;
      const pDm       = document.getElementById('newAdmPerm_dm')?.checked ?? true;
      const pSettings = document.getElementById('newAdmPerm_settings')?.checked ?? false;
      appState.authorizedAdmins.push({
        id: Date.now() + Math.floor(Math.random() * 1000),
        name: nameInp.value.trim() || chosenRole,
        username: rawUser,
        role: chosenRole,
        perms: {
          correct: pCorrect,
          announce: pAnnounce,
          dm: pDm,
          settings: pSettings
        }
      });
      nameInp.value = '';
      userInp.value = '';
      renderAuthorizedAdmins();
      renderPanelSubAdmins();
      applyLoginAndFaviconUI();
      syncConfigToBotServer(`آیدی ${rawUser} با نقش «${chosenRole}» و مجوزهای انتخابی اضافه شد.`);
    }

    function removeAuthorizedAdmin(id) {
      appState.authorizedAdmins = appState.authorizedAdmins.filter(a => a.id !== id);
      renderAuthorizedAdmins();
      renderPanelSubAdmins();
      applyLoginAndFaviconUI();
      syncConfigToBotServer('آیدی مورد نظر حذف شد.', '🗑️');
    }

    
    function getActiveSectionHumanTitle() {
      const tabNames = {
        buttons: 'تب ۱: دکمه‌های جلسات و پرامپت‌ها',
        reportcard: 'تب ۲: کارنامه رشد (' + (appState.selectedReportStudentKey === 'ALL' ? 'میانگین کل کلاس' : (appState.studentProfiles[appState.selectedReportStudentKey]?.persianName || appState.selectedReportStudentKey)) + ')',
        permissions: 'تب ۳: مدیریت اساتید و امنیت',
        students: 'تب ۴: دانشجویان و تاپیک گروه',
        news: 'تب ۵: اخبار فارکس فکتوری',
        simulator: 'تب ۶: شبیه‌ساز زنده تلگرام',
        themes: 'تب ۷: تنظیمات جامع پنل و کلیدها'
      };
      return tabNames[appState.activeTab] || ('بخش: ' + appState.activeTab);
    }

    
    function handleNativePlayerLogoUpload(inputEl, targetType) {
      const file = inputEl.files && inputEl.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = function(ev) {
        const rawUrl = ev.target.result;
        const imgObj = new Image();
        imgObj.onload = function() {
          const maxDim = (targetType === 'logo') ? 320 : 128;
          let w = imgObj.width || maxDim;
          let h = imgObj.height || maxDim;
          if (w > maxDim || h > maxDim) {
            if (w >= h) { h = Math.round((h * maxDim) / w); w = maxDim; }
            else { w = Math.round((w * maxDim) / h); h = maxDim; }
          }
          const cvs = document.createElement('canvas');
          cvs.width = w;
          cvs.height = h;
          const ctx = cvs.getContext('2d');
          ctx.clearRect(0, 0, w, h);
          ctx.drawImage(imgObj, 0, 0, w, h);
          const pngDataUrl = cvs.toDataURL('image/png');
          if (!appState.nativeBranding) appState.nativeBranding = {};
          if (targetType === 'logo') {
            appState.nativeBranding.logo_data_url = pngDataUrl;
            const previewEl = document.getElementById('nativeLogoPreviewImg');
            if (previewEl) { previewEl.src = pngDataUrl; previewEl.classList.remove('hidden'); }
          } else {
            appState.nativeBranding.taskbar_icon_data_url = pngDataUrl;
            const previewEl = document.getElementById('nativeTaskbarPreviewImg');
            if (previewEl) { previewEl.src = pngDataUrl; previewEl.classList.remove('hidden'); }
          }
          saveSecurityRadarSettings(true);
        };
        imgObj.src = rawUrl;
      };
      reader.readAsDataURL(file);
    }

    function applyNativePlayerThemePreset(presetName) {
      const presets = {
        stratex_royal: { hdr: '#0f3d91', btn: '#d4af37', stg: '#070a12', sb: '#0d1322', ctrl: '#0a0f1d', txt: '#f8fafc', hdl: '#fbbf24', trk: '#2563eb' },
        obsidian_emerald: { hdr: '#065f46', btn: '#10b981', stg: '#06090e', sb: '#0b131e', ctrl: '#080d14', txt: '#ecfdf5', hdl: '#34d399', trk: '#10b981' },
        cyber_violet: { hdr: '#581c87', btn: '#c084fc', stg: '#090612', sb: '#140d26', ctrl: '#0d081a', txt: '#f5f3ff', hdl: '#e879f9', trk: '#9333ea' }
      };
      const p = presets[presetName] || presets.stratex_royal;
      const setV = (id, v) => { const el = document.getElementById(id); if (el) el.value = v; };
      setV('nativeHeaderColorInput', p.hdr); setV('nativeHeaderColorHex', p.hdr);
      setV('nativeBtnColorInput', p.btn); setV('nativeBtnColorHex', p.btn);
      setV('nativeStageBgInput', p.stg);
      setV('nativeSidebarBgInput', p.sb);
      setV('nativeCtrlBgInput', p.ctrl);
      setV('nativeTextColorInput', p.txt);
      setV('nativeHandleColorInput', p.hdl);
      setV('nativeSliderFillInput', p.trk);
      saveSecurityRadarSettings(true);
    }

    
    
    // ==========================================
    // STUDIO A: DYNAMIC REGISTRATION FIELDS BUILDER
    // ==========================================
    function renderRegistrationFieldsStudio() {
      const box = document.getElementById('dynamicRegistrationFieldsList');
      const chk = document.getElementById('onboardingCustomFieldsEnabledChk');
      if (chk) chk.checked = !!appState.onboardingCustomFieldsEnabled;
      if (!box) return;
      if (!Array.isArray(appState.registrationFields)) appState.registrationFields = [];
      box.innerHTML = appState.registrationFields.map((f, idx) => `
        <div class="p-3 rounded-xl bg-black/50 border ${f.enabled ? 'border-indigo-500/50' : 'border-slate-800 opacity-65'} space-y-2">
          <div class="flex items-center justify-between gap-2">
            <label class="flex items-center gap-2 cursor-pointer font-extrabold text-indigo-300 text-xs">
              <input type="checkbox" ${f.enabled ? 'checked' : ''} onchange="toggleRegistrationField(${idx}, this.checked)" class="w-4 h-4 accent-indigo-500" />
              <span>فیلد #${idx + 1}: ${f.label}</span>
            </label>
            <div class="flex items-center gap-1">
              <span class="px-2 py-0.5 rounded bg-amber-500/15 border border-amber-500/30 font-mono text-[10px] text-amber-300" dir="ltr">${f.pdfTag || '{field_' + (idx+1) + '}'}</span>
              <button type="button" onclick="moveRegistrationField(${idx}, -1)" class="px-1.5 py-0.5 rounded bg-black/60 text-slate-300 hover:text-white">▲</button>
              <button type="button" onclick="moveRegistrationField(${idx}, 1)" class="px-1.5 py-0.5 rounded bg-black/60 text-slate-300 hover:text-white">▼</button>
              <button type="button" onclick="deleteRegistrationField(${idx})" class="px-1.5 py-0.5 rounded bg-rose-500/20 text-rose-300 hover:bg-rose-500/40">✕</button>
            </div>
          </div>
          <div class="grid grid-cols-1 sm:grid-cols-3 gap-2">
            <input type="text" value="${f.label || ''}" onchange="updateRegistrationFieldProp(${idx}, 'label', this.value)" class="px-2.5 py-1 rounded-lg bg-black/60 border theme-border text-white font-bold text-[11px]" placeholder="عنوان فیلد" />
            <select onchange="updateRegistrationFieldProp(${idx}, 'type', this.value)" class="px-2 py-1 rounded-lg bg-black/60 border theme-border text-sky-300 font-bold text-[11px]">
              <option value="text" ${f.type === 'text' ? 'selected' : ''}>📝 متن آزاد</option>
              <option value="number" ${f.type === 'number' ? 'selected' : ''}>🔢 فقط عدد</option>
              <option value="photo" ${f.type === 'photo' ? 'selected' : ''}>🖼️ آپلود عکس</option>
            </select>
            <input type="text" dir="ltr" value="${f.pdfTag || ''}" onchange="updateRegistrationFieldProp(${idx}, 'pdfTag', this.value)" class="px-2 py-1 rounded-lg bg-black/60 border theme-border text-amber-300 font-mono text-[11px] text-center" placeholder="{tag}" />
          </div>
          <input type="text" value="${f.prompt || ''}" onchange="updateRegistrationFieldProp(${idx}, 'prompt', this.value)" class="w-full px-2.5 py-1 rounded-lg bg-black/60 border theme-border text-slate-200 text-[11px]" placeholder="متن سوال ربات از کاربر..." />
        </div>
      `).join('');
    }

    function toggleRegistrationField(idx, val) {
      if (!appState.registrationFields[idx]) return;
      appState.registrationFields[idx].enabled = !!val;
      renderRegistrationFieldsStudio();
      saveSecurityRadarSettings();
    }

    function updateRegistrationFieldProp(idx, key, val) {
      if (!appState.registrationFields[idx]) return;
      appState.registrationFields[idx][key] = val;
      saveSecurityRadarSettings();
    }

    function moveRegistrationField(idx, dir) {
      const target = idx + dir;
      if (target < 0 || target >= appState.registrationFields.length) return;
      const tmp = appState.registrationFields[idx];
      appState.registrationFields[idx] = appState.registrationFields[target];
      appState.registrationFields[target] = tmp;
      renderRegistrationFieldsStudio();
      saveSecurityRadarSettings();
    }

    function deleteRegistrationField(idx) {
      appState.registrationFields.splice(idx, 1);
      renderRegistrationFieldsStudio();
      saveSecurityRadarSettings();
    }

    function addNewRegistrationField() {
      const lbl = document.getElementById('newRegFieldLabelInput')?.value.trim();
      const prm = document.getElementById('newRegFieldPromptInput')?.value.trim();
      const typ = document.getElementById('newRegFieldTypeSelect')?.value || 'text';
      let tag   = document.getElementById('newRegFieldTagInput')?.value.trim() || ('{field_' + (appState.registrationFields.length + 1) + '}');
      if (!lbl) { showToast('لطفاً عنوان فیلد ثبت‌نام را وارد کنید.', '⚠️'); return; }
      if (!tag.startsWith('{')) tag = '{' + tag.replace(/[{}]/g, '') + '}';
      appState.registrationFields.push({
        id: 'reg_' + Date.now(),
        label: lbl,
        prompt: prm || ('لطفاً «' + lbl + '» خود را وارد نمایید:'),
        type: typ,
        pdfTag: tag,
        enabled: true
      });
      document.getElementById('newRegFieldLabelInput').value = '';
      document.getElementById('newRegFieldPromptInput').value = '';
      document.getElementById('newRegFieldTagInput').value = '';
      renderRegistrationFieldsStudio();
      saveSecurityRadarSettings(true);
    }

    // ==========================================
    // STUDIO B: UNLIMITED MULTI-METHOD PAYMENT STUDIO
    // ==========================================
    function renderPaymentMethodsStudio() {
      const box = document.getElementById('multiPaymentMethodsContainer');
      const chk = document.getElementById('onboardingPaymentRequiredChk');
      const pos = document.getElementById('paymentStagePositionSelect');
      const hdr = document.getElementById('paymentPromptHeaderInput');
      if (chk) chk.checked = !!appState.onboardingPaymentRequired;
      if (pos && appState.paymentStagePosition) pos.value = appState.paymentStagePosition;
      if (hdr && appState.paymentPromptHeader) hdr.value = appState.paymentPromptHeader;
      if (!box) return;
      if (!Array.isArray(appState.paymentMethods)) appState.paymentMethods = [];
      box.innerHTML = appState.paymentMethods.map((pm, idx) => `
        <div class="p-3.5 rounded-2xl bg-black/50 border ${pm.enabled ? 'border-emerald-500/50' : 'border-slate-800 opacity-65'} space-y-2.5">
          <div class="flex items-center justify-between gap-2 border-b border-slate-800 pb-2">
            <label class="flex items-center gap-2 cursor-pointer font-extrabold text-emerald-300 text-xs">
              <input type="checkbox" ${pm.enabled ? 'checked' : ''} onchange="togglePaymentMethod(${idx}, this.checked)" class="w-4 h-4 accent-emerald-500" />
              <span>روش #${idx + 1}: ${pm.title}</span>
            </label>
            <div class="flex items-center gap-1">
              <button type="button" onclick="movePaymentMethod(${idx}, -1)" class="px-1.5 py-0.5 rounded bg-black/60 text-slate-300 hover:text-white">▲</button>
              <button type="button" onclick="movePaymentMethod(${idx}, 1)" class="px-1.5 py-0.5 rounded bg-black/60 text-slate-300 hover:text-white">▼</button>
              <button type="button" onclick="deletePaymentMethod(${idx})" class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-300 hover:bg-rose-500/40 text-[11px]">حذف</button>
            </div>
          </div>
          <div class="grid grid-cols-1 sm:grid-cols-3 gap-2">
            <div class="sm:col-span-2">
              <label class="block text-[10px] theme-text-muted mb-0.5">عنوان دکمه در تلگرام:</label>
              <input type="text" value="${pm.title || ''}" onchange="updatePaymentMethodProp(${idx}, 'title', this.value)" class="w-full px-2.5 py-1.5 rounded-lg bg-black/60 border theme-border text-white font-bold text-[11px]" />
            </div>
            <div>
              <label class="block text-[10px] theme-text-muted mb-0.5">رنگ دکمه در تلگرام:</label>
              <select onchange="updatePaymentMethodProp(${idx}, 'style', this.value)" class="w-full px-2 py-1.5 rounded-lg bg-black/60 border theme-border text-sky-300 font-bold text-[11px]">
                <option value="success" ${pm.style === 'success' ? 'selected' : ''}>🟢 سبز (Success)</option>
                <option value="primary" ${pm.style === 'primary' ? 'selected' : ''}>🔵 آبی (Primary)</option>
                <option value="danger" ${pm.style === 'danger' ? 'selected' : ''}>🔴 قرمز (Danger)</option>
                <option value="" ${!pm.style ? 'selected' : ''}>⚪ پیش‌فرض</option>
              </select>
            </div>
          </div>
          <div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
            <div>
              <label class="block text-[10px] theme-text-muted mb-0.5">مبلغ / تعرفه نمایشی:</label>
              <input type="text" value="${pm.amountLabel || ''}" onchange="updatePaymentMethodProp(${idx}, 'amountLabel', this.value)" class="w-full px-2.5 py-1 rounded-lg bg-black/60 border theme-border text-amber-300 font-bold text-[11px]" />
            </div>
            <div>
              <label class="block text-[10px] theme-text-muted mb-0.5">نحوه تایید پرداخت:</label>
              <select onchange="updatePaymentMethodProp(${idx}, 'verifyMode', this.value)" class="w-full px-2 py-1 rounded-lg bg-black/60 border theme-border text-emerald-300 font-bold text-[11px]">
                <option value="both" ${pm.verifyMode === 'both' ? 'selected' : ''}>📸📝 عکس رسید یا کد پیگیری/TxID</option>
                <option value="receipt_photo" ${pm.verifyMode === 'receipt_photo' ? 'selected' : ''}>📸 فقط عکس رسید / اسکرین‌شات</option>
                <option value="txid_text" ${pm.verifyMode === 'txid_text' ? 'selected' : ''}>📝 فقط متن کد پیگیری / TxID</option>
                <option value="online_link" ${pm.verifyMode === 'online_link' ? 'selected' : ''}>🌐 لینک درگاه پرداخت آنلاین</option>
              </select>
            </div>
          </div>
          <div>
            <label class="block text-[10px] theme-text-muted mb-0.5">شماره کارت / شماره شبا / آدرس ولت تتر (USDT) / لینک درگاه:</label>
            <input type="text" value="${(pm.accountInfo || '').replace(/\n/g, ' | ')}" onchange="updatePaymentMethodProp(${idx}, 'accountInfo', this.value)" class="w-full px-2.5 py-1.5 rounded-lg bg-black/70 border theme-border text-emerald-200 font-mono text-[11px]" />
          </div>
          <div>
            <label class="block text-[10px] theme-text-muted mb-0.5">متن راهنمای پرداخت برای دانشجو:</label>
            <input type="text" value="${pm.instructions || ''}" onchange="updatePaymentMethodProp(${idx}, 'instructions', this.value)" class="w-full px-2.5 py-1 rounded-lg bg-black/60 border theme-border text-slate-300 text-[11px]" />
          </div>
        </div>
      `).join('');
    }

    function togglePaymentMethod(idx, val) {
      if (!appState.paymentMethods[idx]) return;
      appState.paymentMethods[idx].enabled = !!val;
      renderPaymentMethodsStudio();
      saveSecurityRadarSettings();
    }

    function updatePaymentMethodProp(idx, key, val) {
      if (!appState.paymentMethods[idx]) return;
      appState.paymentMethods[idx][key] = val;
      saveSecurityRadarSettings();
    }

    function movePaymentMethod(idx, dir) {
      const target = idx + dir;
      if (target < 0 || target >= appState.paymentMethods.length) return;
      const tmp = appState.paymentMethods[idx];
      appState.paymentMethods[idx] = appState.paymentMethods[target];
      appState.paymentMethods[target] = tmp;
      renderPaymentMethodsStudio();
      saveSecurityRadarSettings();
    }

    function deletePaymentMethod(idx) {
      appState.paymentMethods.splice(idx, 1);
      renderPaymentMethodsStudio();
      saveSecurityRadarSettings();
    }

    function addNewPaymentMethod() {
      const title = document.getElementById('newPayTitleInput')?.value.trim();
      const amt   = document.getElementById('newPayAmountInput')?.value.trim() || 'طبق تعرفه دوره';
      const vMode = document.getElementById('newPayVerifyModeSelect')?.value || 'both';
      const style = document.getElementById('newPayStyleSelect')?.value ?? 'primary';
      const acc   = document.getElementById('newPayAccountInput')?.value.trim() || '';
      const inst  = document.getElementById('newPayInstInput')?.value.trim() || 'لطفاً پس از واریز، رسید یا کد پیگیری خود را ارسال نمایید:';
      if (!title) { showToast('لطفاً عنوان روش پرداخت جدید را وارد کنید.', '⚠️'); return; }
      appState.paymentMethods.push({
        id: 'pay_' + Date.now(),
        title,
        type: 'custom',
        style,
        amountLabel: amt,
        accountInfo: acc,
        instructions: inst,
        verifyMode: vMode,
        enabled: true
      });
      document.getElementById('newPayTitleInput').value = '';
      document.getElementById('newPayAmountInput').value = '';
      document.getElementById('newPayAccountInput').value = '';
      document.getElementById('newPayInstInput').value = '';
      renderPaymentMethodsStudio();
      saveSecurityRadarSettings(true);
    }

    // ==========================================
    // STUDIO C: VISUAL BOT FLOW & SUB-MENU BUILDER
    // ==========================================
    
    // =========================================================================
    // FOCUS-SAFE UNIFIED BOT PIPELINE & MENU BUILDER ENGINE (v3.2)
    // =========================================================================
    appState.wpCurrentStageIdx = 0;
    appState.wpSelectedSlotRef = { rowIdx: 0, colIdx: 0 };
    appState.wpPreviewSubViewBtnId = null; // If set, phone preview shows the inside of that button!
    appState.wpShowRowStructurePicker = false;
    let _wpSaveDebounceTimer = null;

    function debouncedSaveBotBuilder() {
      if (!window.__SX_SERVER_CFG_LOADED__) return;
      try { updateSmartChangelogCounterBadge(); } catch(e) {}
      if (_wpSaveDebounceTimer) clearTimeout(_wpSaveDebounceTimer);
      _wpSaveDebounceTimer = setTimeout(() => {
        syncMainMenuRowsToButtons();
        try {
          const payload = buildFullBotConfigPayload();
          localStorage.setItem('trading_bot_live_config_v68', JSON.stringify(payload));
        } catch(e) {}
      }, 350);
    }

    function ensureWpSimState() {
      if (!appState.wpSimStudent) {
        appState.wpSimStudent = {
          full_name: 'سولا آرانی',
          national_id: '0012345678',
          username: '@Solay_Trader',
          phone: '09123456789',
          email: 'student@gmail.com',
          city: 'تهران',
          trade_exp: '۳ سال',
          date: '1405/08/27',
          id: '95041523'
        };
      }
      if (!Array.isArray(appState.wpSimChatLog)) appState.wpSimChatLog = [];
    }

    function replacePreviewStudentVars(txt) {
      ensureWpSimState();
      const s = appState.wpSimStudent;
      return String(txt || '')
        .replace(/\{full_name\}/g, s.full_name || 'سولا آرانی')
        .replace(/\{name\}/g, s.full_name || 'سولا آرانی')
        .replace(/\{national_id\}/g, s.national_id || '0012345678')
        .replace(/\{username\}/g, s.username || '@Solay_Trader')
        .replace(/\{phone\}/g, s.phone || '09123456789')
        .replace(/\{email\}/g, s.email || 'student@gmail.com')
        .replace(/\{city\}/g, s.city || 'تهران')
        .replace(/\{trade_exp\}/g, s.trade_exp || '۳ سال')
        .replace(/\{date\}/g, s.date || '1405/08/27')
        .replace(/\{id\}/g, s.id || '95041523');
    }

    function ensureWpPipelineAndRows() {
      if (!Array.isArray(appState.onboardingPipeline) || appState.onboardingPipeline.length === 0) {
        appState.onboardingPipeline = [
          { id: 'step_pass',     kind: 'builtin', title: '🔐 رمز ورود',              enabled: true,  promptText: '', inputMode: 'password', buttons: [] },
          { id: 'step_terms',    kind: 'builtin', title: '📜 قوانین بدو ورود',       enabled: true,  promptText: '', inputMode: 'inline_buttons', buttons: [] },
          { id: 'step_email',    kind: 'builtin', title: '📧 ایمیل + کد ۶ رقمی',     enabled: true,  promptText: '', inputMode: 'email_otp', buttons: [] },
          { id: 'step_phone',    kind: 'builtin', title: '📱 موبایل (۳ حالته)',      enabled: true,  promptText: '', inputMode: 'contact', buttons: [] },
          { id: 'step_fname',    kind: 'builtin', title: '👤 نام',                    enabled: true,  promptText: '', inputMode: 'text', buttons: [] },
        { id: 'step_lname',    kind: 'builtin', title: '👤 نام خانوادگی',           enabled: true,  promptText: '', inputMode: 'text', buttons: [] },
          { id: 'step_nid',      kind: 'builtin', title: '🪪 کارت ملی زنده + OCR',  enabled: true,  promptText: '', inputMode: 'webapp_nid', buttons: [] },
          { id: 'step_reg',      kind: 'builtin', title: '📝 فیلدهای سفارشی',       enabled: false, promptText: '', inputMode: 'text', buttons: [] },
          { id: 'step_pay',      kind: 'builtin', title: '💳 پرداخت چندحالته',       enabled: false, promptText: '', inputMode: 'payment', buttons: [] },
          { id: 'step_contract', kind: 'builtin', title: '✍️ تعهدنامه PDF',          enabled: true,  promptText: '', inputMode: 'webapp_contract', buttons: [] }
        ];
      } else {
        const hasIds = new Set(appState.onboardingPipeline.map(s => s && s.id));
        if (!hasIds.has('step_email') || !hasIds.has('step_fname') || !hasIds.has('step_lname') || !hasIds.has('step_nid')) {
          const oldMap = {};
          appState.onboardingPipeline.forEach(s => { if (s && s.id) oldMap[s.id] = s; });
          const migrated = [
            oldMap.step_pass     || { id: 'step_pass',     kind: 'builtin', title: '🔐 رمز ورود',              enabled: true,  promptText: '', inputMode: 'password', buttons: [] },
            oldMap.step_terms    || { id: 'step_terms',    kind: 'builtin', title: '📜 قوانین بدو ورود',       enabled: true,  promptText: '', inputMode: 'inline_buttons', buttons: [] },
            oldMap.step_email    || { id: 'step_email',    kind: 'builtin', title: '📧 ایمیل + کد ۶ رقمی',     enabled: (appState.onboardingEmailRequired !== false), promptText: '', inputMode: 'email_otp', buttons: [] },
            oldMap.step_phone    || { id: 'step_phone',    kind: 'builtin', title: '📱 موبایل (۳ حالته)',      enabled: (appState.onboardingPhoneRequired !== false), promptText: '', inputMode: 'contact', buttons: [] },
            oldMap.step_fname    || { id: 'step_fname',    kind: 'builtin', title: '👤 نام',                    enabled: true,  promptText: '', inputMode: 'text', buttons: [] },
            oldMap.step_lname    || { id: 'step_lname',    kind: 'builtin', title: '👤 نام خانوادگی',           enabled: true,  promptText: '', inputMode: 'text', buttons: [] },
            oldMap.step_nid      || { id: 'step_nid',      kind: 'builtin', title: '🪪 کارت ملی زنده + OCR',  enabled: true,  promptText: '', inputMode: 'webapp_nid', buttons: [] },
            oldMap.step_reg      ? Object.assign({}, oldMap.step_reg, { title: '📝 فیلدهای سفارشی' }) : { id: 'step_reg', kind: 'builtin', title: '📝 فیلدهای سفارشی', enabled: !!appState.onboardingCustomFieldsEnabled, promptText: '', inputMode: 'text', buttons: [] },
            oldMap.step_pay      || { id: 'step_pay',      kind: 'builtin', title: '💳 پرداخت چندحالته',       enabled: !!appState.onboardingPaymentRequired, promptText: '', inputMode: 'payment', buttons: [] },
            oldMap.step_contract || { id: 'step_contract', kind: 'builtin', title: '✍️ تعهدنامه PDF',          enabled: true,  promptText: '', inputMode: 'webapp_contract', buttons: [] }
          ];
          appState.onboardingPipeline.forEach(s => {
            if (s && s.id && s.id.indexOf('custom_step_') === 0) migrated.push(s);
          });
          appState.onboardingPipeline = migrated;
        }
      }

      // Normalize telegramMenuButtons so every button has both .label and .text, .actionType, .replyText, .subButtons, .showNavButtons
      const defaultBtns = [
        {
          id: 'submit_practice',
          label: '📤 ارسال تمرین جدید',
          style: 'primary',
          row: 1,
          enabled: true,
          actionType: 'practice_upload',
          replyText: '📸 {full_name} عزیز، لطفاً اسکرین‌شات چارت تمرین خود را ارسال کنید تا دکمه‌های جلسات زیر برایتان باز شود:',
          showNavButtons: true,
          subButtonsLayout: 'side_by_side',
          subButtons: []
        },
        {
          id: 'player_license',
          label: '🎓 دوره‌های من',
          style: 'primary',
          row: 1,
          enabled: true,
          actionType: 'course_menu',
          replyText: '🎓 {full_name} عزیز (کد ملی: {national_id})، فهرست دوره‌های آموزشی شما در آکادمی:',
          showNavButtons: true,
          subButtonsLayout: 'side_by_side',
          subButtons: [
            { text: '🔑 دریافت کلید لایسنس دوره', style: 'success', action: 'course_license', url: '' },
            { text: '📋 مشاهده فهرست جلسات این دوره', style: 'primary', action: 'course_sessions_list', url: '' }
          ]
        },
        {
          id: 'my_report',
          label: '📊 دریافت کارنامه HTML من',
          style: 'success',
          row: 2,
          enabled: true,
          actionType: 'html_report',
          replyText: '📊 {full_name} عزیز، فایل کارنامه تعاملی رشد و آنالیز باگ‌های معاملاتی شما آماده شد!',
          showNavButtons: true,
          subButtonsLayout: 'side_by_side',
          subButtons: []
        },
        {
          id: 'ai_chat',
          label: '🧠 چت مشورتی با مربی هوشمند',
          style: 'success',
          row: 2,
          enabled: true,
          actionType: 'ai_coach',
          replyText: '🧠 {full_name} عزیز، به اتاق گفت‌وگوی هوشمند خوش آمدید! هر سوالی درباره استراتژی یا ستاپ‌ها دارید بپرسید:',
          showNavButtons: true,
          subButtonsLayout: 'side_by_side',
          subButtons: []
        },
        {
          id: 'rules_guide',
          label: '📖 قوانین جلسات استاد',
          style: '',
          row: 3,
          enabled: true,
          actionType: 'session_rules',
          replyText: '📖 {full_name} عزیز، سرفصل‌ها و قوانین کلیدی جلسات استاد به شرح زیر است:',
          showNavButtons: true,
          subButtonsLayout: 'side_by_side',
          subButtons: []
        }
      ];

      if (!Array.isArray(appState.telegramMenuButtons) || appState.telegramMenuButtons.length === 0) {
        appState.telegramMenuButtons = defaultBtns;
      } else {
        appState.telegramMenuButtons.forEach((b, idx) => {
          const lbl = b.label || b.text || ('دکمه ' + (idx + 1));
          b.label = lbl;
          b.text  = lbl;
          if (!b.id) b.id = 'btn_' + idx + '_' + Date.now();
          if (!b.actionType || b.actionType === 'custom_submenu') {
            if (lbl.includes('تمرین')) b.actionType = 'practice_upload';
            else if (lbl.includes('استاد')) b.actionType = 'professor_chat';
            else if (lbl.includes('هوش مصنوعی') || lbl.includes('مربی')) b.actionType = 'ai_coach';
            else if (lbl.includes('کارنامه')) b.actionType = 'html_report';
            else if (lbl.includes('قوانین')) b.actionType = 'session_rules';
            else if (lbl.includes('دوره‌های من') || lbl.includes('دوره های من') || lbl.includes('لایسنس')) b.actionType = 'course_menu';
            else if (lbl.includes('پنل مدیریت')) { b.actionType = 'admin_panel'; b.adminOnly = true; }
            else if (!b.actionType) b.actionType = 'custom_submenu';
          }
          // Clean out empty [null, null] subRows on action buttons that have no subButtons so they never block real engines
          if (Array.isArray(b.subRows) && (!Array.isArray(b.subButtons) || b.subButtons.length === 0)) {
            const hasAnyNonNull = b.subRows.some(sr => Array.isArray(sr.slots) && sr.slots.some(s => s !== null && s !== undefined));
            if (!hasAnyNonNull && ['practice_upload', 'ai_coach', 'professor_chat', 'html_report', 'session_rules'].includes(b.actionType)) {
              b.subRows = [];
            }
          }
          if (b.showNavButtons === undefined) b.showNavButtons = true;
          if (!b.subButtonsLayout) b.subButtonsLayout = 'side_by_side';
          if (!Array.isArray(b.subButtons)) {
            if (b.actionType === 'course_menu') {
              b.subButtons = [
                { text: '🔑 دریافت کلید لایسنس دوره', style: 'success', action: 'course_license', url: '' },
                { text: '📋 مشاهده فهرست جلسات این دوره', style: 'primary', action: 'course_sessions_list', url: '' }
              ];
            } else {
              b.subButtons = [];
            }
          }
        });
      }

      // Ensure `⚙️ ` (`actionType: 'admin_panel'`) exists as a customizable Elementor button!
      // Ensure "🎓 " has the 2 standard buttons (License + Sessions List) and no longer holds Player Download
      appState.telegramMenuButtons.forEach(b => {
        if (!b) return;
        const lbl = String(b.label || b.text || '');
        if (b.actionType === 'course_menu' || lbl.includes('دوره‌های من') || lbl.includes('دوره های من')) {
          b.actionType = 'course_menu';
          if (!Array.isArray(b.subButtons) || b.subButtons.length === 0) {
            b.subButtons = [
              { text: '🔑 دریافت کلید لایسنس دوره', style: 'success', action: 'course_license', url: '' },
              { text: '📋 مشاهده فهرست جلسات این دوره', style: 'primary', action: 'course_sessions_list', url: '' }
            ];
          } else {
            // Migrate any legacy course_player_dl inside course_menu to course_sessions_list
            let hasLic = false;
            let hasSess = false;
            b.subButtons = b.subButtons.map(sb => {
              if (!sb) return sb;
              if (sb.action === 'course_player_dl' || String(sb.text || '').includes('Player') || String(sb.text || '').includes('پلیر')) {
                return { text: '📋 مشاهده فهرست جلسات این دوره', style: 'primary', action: 'course_sessions_list', url: '' };
              }
              if (sb.action === 'course_license' && sb.text === '🔑 دریافت کلید لایسنس') {
                sb.text = '🔑 دریافت کلید لایسنس دوره';
              }
              if (sb.action === 'course_license') hasLic = true;
              if (sb.action === 'course_sessions_list') hasSess = true;
              return sb;
            });
            if (!hasLic) b.subButtons.unshift({ text: '🔑 دریافت کلید لایسنس دوره', style: 'success', action: 'course_license', url: '' });
            if (!hasSess) b.subButtons.push({ text: '📋 مشاهده فهرست جلسات این دوره', style: 'primary', action: 'course_sessions_list', url: '' });
            // Deduplicate if both existed
            const seenActs = new Set();
            b.subButtons = b.subButtons.filter(sb => {
              if (!sb) return false;
              if ((sb.action === 'course_license' || sb.action === 'course_sessions_list') && seenActs.has(sb.action)) return false;
              seenActs.add(sb.action);
              return true;
            });
            b.subRows = [{ cols: 2, slots: [0, 1] }];
          }
        }
      });

      // Ensure "📈 " button exists and includes Player Download + Software + Indicators
      let expBtnIdx = appState.telegramMenuButtons.findIndex(b => b && (b.id === 'experts_indicators' || String(b.label || b.text || '').includes('اکسپرت') || String(b.label || b.text || '').includes('اندیکاتور')));
      if (expBtnIdx === -1) {
        const expBtn = {
          id: 'experts_indicators',
          label: '📈 اکسپرت و اندیکاتور',
          text: '📈 اکسپرت و اندیکاتور',
          style: 'primary',
          row: 3,
          col: 2,
          enabled: true,
          actionType: 'custom_submenu',
          replyText: '📈 {full_name} عزیز، به بخش اکسپرت‌ها، اندیکاتورها و نرم‌افزارهای رسمی آکادمی استراتکس خوش آمدید.\nلطفاً نرم‌افزار یا ابزار مورد نظر خود را از دکمه‌های زیر انتخاب نمایید:',
          subButtons: [
            { text: '💻 دانلود نرم‌افزار پلیر (StrateX Player)', style: 'primary', action: 'course_player_dl', url: appState.nativePlayerDownloadUrl || 'https://thestratexbot.solaarani.com/StrateX_Player.exe', replyText: '💻 نسخه رسمی پلیر دسکتاپ و موبایل آکادمی استراتکس (StrateX Player v1.8) جهت تماشای امن جلسات:' },
            { text: '📊 دانلود اکسپرت و اندیکاتورهای اختصاصی', style: 'success', action: 'reply_text', url: '', replyText: '📊 فایل آخرین نسخه اکسپرت مدیریت سرمایه و اندیکاتور شکار نقدینگی آکادمی استراتکس آماده دانلود است.' },
            { text: '🛠️ نرم‌افزارها و ابزارهای کمکی ترید', style: 'primary', action: 'reply_text', url: '', replyText: '🛠️ مجموعه نرم‌افزارهای جانبی، ماشین‌حساب پوزیشن‌سایز و تقویم اقتصادی دسکتاپ آکادمی استراتکس:' }
          ],
          subRows: [
            { cols: 2, slots: [0, 1] },
            { cols: 1, slots: [2] }
          ]
        };
        appState.telegramMenuButtons.push(expBtn);
        expBtnIdx = appState.telegramMenuButtons.length - 1;
        if (Array.isArray(appState.elementorMainRows) && appState.elementorMainRows.length > 0) {
          const alreadyInRows = appState.elementorMainRows.some(rw => (rw.slots || []).some(sl => sl && sl.index === expBtnIdx));
          if (!alreadyInRows) {
            appState.elementorMainRows.push({ id: 'row_experts_' + Date.now(), cols: 1, slots: [{ source: 'main_menu', index: expBtnIdx }] });
          }
        }
      } else {
        const expBtn = appState.telegramMenuButtons[expBtnIdx];
        if (!Array.isArray(expBtn.subButtons) || expBtn.subButtons.length === 0) {
          expBtn.subButtons = [
            { text: '💻 دانلود نرم‌افزار پلیر (StrateX Player)', style: 'primary', action: 'course_player_dl', url: appState.nativePlayerDownloadUrl || 'https://thestratexbot.solaarani.com/StrateX_Player.exe', replyText: '💻 نسخه رسمی پلیر دسکتاپ و موبایل آکادمی استراتکس (StrateX Player v1.8) جهت تماشای امن جلسات:' },
            { text: '📊 دانلود اکسپرت و اندیکاتورهای اختصاصی', style: 'success', action: 'reply_text', url: '', replyText: '📊 فایل آخرین نسخه اکسپرت مدیریت سرمایه و اندیکاتور شکار نقدینگی آکادمی استراتکس آماده دانلود است.' },
            { text: '🛠️ نرم‌افزارها و ابزارهای کمکی ترید', style: 'primary', action: 'reply_text', url: '', replyText: '🛠️ مجموعه نرم‌افزارهای جانبی، ماشین‌حساب پوزیشن‌سایز و تقویم اقتصادی دسکتاپ آکادمی استراتکس:' }
          ];
          expBtn.subRows = [
            { cols: 2, slots: [0, 1] },
            { cols: 1, slots: [2] }
          ];
        } else if (!expBtn.subButtons.some(sb => sb && (sb.action === 'course_player_dl' || String(sb.text||'').includes('Player') || String(sb.text||'').includes('پلیر')))) {
          expBtn.subButtons.unshift({
            text: '💻 دانلود نرم‌افزار پلیر (StrateX Player)',
            style: 'primary',
            action: 'course_player_dl',
            url: appState.nativePlayerDownloadUrl || 'https://thestratexbot.solaarani.com/StrateX_Player.exe',
            replyText: '💻 نسخه رسمی پلیر دسکتاپ و موبایل آکادمی استراتکس (StrateX Player v1.8) جهت تماشای امن جلسات:'
          });
          expBtn.subRows = null;
          ensureButtonSubRows(expBtn);
        }
      }

      // Clean legacy auto-filler replyText on course_player_dl / open_url subButtons
      appState.telegramMenuButtons.forEach(btnItem => {
        if (!btnItem || !Array.isArray(btnItem.subButtons)) return;
        btnItem.subButtons.forEach(sb => {
          if (!sb) return;
          if (sb.action === 'course_player_dl' || sb.action === 'open_url' || sb.action === 'send_url') {
            if (sb.replyText === 'پاسخ مربوط به این دکمه برای {full_name} عزیز.' || sb.replyText === 'پاسخ برای {full_name} عزیز.') {
              sb.replyText = '';
            }
            if (!sb.linkLabel) {
              sb.linkLabel = (sb.action === 'course_player_dl') ? '📥 دانلود مستقیم نرم‌افزار StrateX Player' : (sb.text || '🌐 باز کردن لینک');
            }
          }
        });
      });

      // Ensure "🔴 کلاس آنلاین زنده" button exists with role-based credentials & status sub-buttons
      let liveBtnIdx = appState.telegramMenuButtons.findIndex(b => b && (b.id === 'live_class_hub' || b.actionType === 'live_class_menu' || String(b.label || b.text || '').includes('کلاس آنلاین')));
      if (liveBtnIdx === -1) {
        const liveBtn = {
          id: 'live_class_hub',
          label: '🔴 کلاس آنلاین زنده',
          text: '🔴 کلاس آنلاین زنده',
          style: 'danger',
          row: 3,
          col: 2,
          enabled: true,
          actionType: 'live_class_menu',
          replyText: '🔴 {full_name} عزیز، به تالار کلاس آنلاین زنده آکادمی استراتکس خوش آمدید.\nجهت دریافت نام کاربری (Username) و رمز عبور (Password) اختصاصی خود برای ورود به بخش کلاس آنلاین در پلیر دسکتاپ، یکی از گزینه‌های زیر را انتخاب نمایید:',
          subButtons: [
            { text: '🔑 دریافت یوزر و پسورد ورود به کلاس آنلاین', style: 'success', action: 'live_class_credentials', url: '', replyText: '' },
            { text: '📡 وضعیت برگزاری و راهنمای ورود در پلیر', style: 'primary', action: 'live_class_status', url: '', replyText: '' }
          ],
          subRows: [
            { cols: 1, slots: [0] },
            { cols: 1, slots: [1] }
          ]
        };
        appState.telegramMenuButtons.push(liveBtn);
        liveBtnIdx = appState.telegramMenuButtons.length - 1;
        if (Array.isArray(appState.elementorMainRows) && appState.elementorMainRows.length > 0) {
          const alreadyInRows = appState.elementorMainRows.some(rw => (rw.slots || []).some(sl => sl && sl.index === liveBtnIdx));
          if (!alreadyInRows) {
            appState.elementorMainRows.push({ id: 'row_live_class_' + Date.now(), cols: 1, slots: [{ source: 'main_menu', index: liveBtnIdx }] });
          }
        }
      }

      let hasAdminPanelBtn = appState.telegramMenuButtons.some(b => b && (b.actionType === 'admin_panel' || String(b.label||'').includes('پنل مدیریت تلگرام')));
      if (!hasAdminPanelBtn) {
        const maxRow = appState.telegramMenuButtons.reduce((m, b) => Math.max(m, parseInt(b?.row, 10) || 1), 1);
        const admBtn = {
          id: 'tg_admin_panel',
          label: '⚙️ پنل مدیریت تلگرام',
          text: '⚙️ پنل مدیریت تلگرام',
          style: 'primary',
          row: maxRow + 1,
          col: 1,
          enabled: true,
          adminOnly: true,
          actionType: 'admin_panel',
          replyText: '⚙️ پنل مدیریت سریع ربات از داخل تلگرام:\nاز دکمه‌های زیر می‌توانید بخش‌های مجاز خود را مدیریت کنید:',
          subButtons: [
            { text: '📢 ارسال اطلاعیه به تاپیک گروه', style: 'primary', action: 'tgadm|ann_topic', permKey: 'announce', row: 1, col: 1 },
            { text: '📣 ارسال اطلاعیه به کانال', style: 'primary', action: 'tgadm|ann_channel', permKey: 'announce', row: 1, col: 2 },
            { text: '🚀 ارسال همزمان به تاپیک + کانال', style: 'success', action: 'tgadm|ann_both', permKey: 'announce', row: 2, col: 1 },
            { text: '✉️ ارسال پیام به پیوی دانشجو', style: 'primary', action: 'tgadm|dm_menu', permKey: 'dm', row: 3, col: 1 },
            { text: '👥 مدیریت دسترسی و تاریخ انقضای دانشجویان', style: 'success', action: 'tgadm|stu_acl_list', permKey: 'dm', row: 3, col: 2 },
            { text: '🟢 روشن / خاموش کردن ربات', style: 'danger', action: 'tgadm|toggle_power', permKey: 'settings', row: 4, col: 1 },
            { text: '📸 ارسال فوری کارت اخبار فارکس', style: 'primary', action: 'tgadm|send_news', permKey: 'settings', row: 4, col: 2 },
            { text: '📊 آمار زنده دانشجویان', style: '', action: 'tgadm|stats', permKey: 'all', row: 5, col: 1 }
          ],
          subRows: [
            { cols: 2, slots: [0, 1] },
            { cols: 1, slots: [2] },
            { cols: 2, slots: [3, 4] },
            { cols: 2, slots: [5, 6] },
            { cols: 1, slots: [7] }
          ]
        };
        appState.telegramMenuButtons.push(admBtn);
        if (Array.isArray(appState.elementorMainRows) && appState.elementorMainRows.length > 0) {
          appState.elementorMainRows.push({ id: 'row_admin_panel', cols: 1, slots: [{ source: 'main_menu', index: appState.telegramMenuButtons.length - 1 }] });
        }
      }

      // Build or repair elementorMainRows from telegramMenuButtons so they are 100% synced!
      if (!Array.isArray(appState.elementorMainRows) || appState.elementorMainRows.length === 0) {
        const byRow = {};
        appState.telegramMenuButtons.forEach((b, idx) => {
          const r = parseInt(b.row, 10) || 1;
          if (!byRow[r]) byRow[r] = [];
          byRow[r].push({ source: 'main_menu', index: idx });
        });
        const rKeys = Object.keys(byRow).map(Number).sort((a, b) => a - b);
        appState.elementorMainRows = rKeys.map((rk, i) => ({
          id: 'row_' + (i + 1),
          cols: Math.max(1, Math.min(4, byRow[rk].length)),
          slots: byRow[rk]
        }));
      } else {
        // v4.5.0: Deduplicate main_menu indices across elementorMainRows (fixes duplicate 'دوره‌های من' row below admin panel!)
        const seenMainIdx = new Set();
        const seenCourseMenu = { hit: false };
        appState.elementorMainRows = appState.elementorMainRows.map(rw => {
          if (!rw || !Array.isArray(rw.slots)) return null;
          const hadAnySlotBefore = rw.slots.some(Boolean);
          const cleanSlots = rw.slots.map(sl => {
            if (!sl || sl.source !== 'main_menu') return sl;
            const bIdx = parseInt(sl.index, 10);
            const bObj = appState.telegramMenuButtons[bIdx];
            if (!bObj) return null;
            if (seenMainIdx.has(bIdx)) return null;
            if (bObj.actionType === 'course_menu') {
              if (seenCourseMenu.hit) return null;
              seenCourseMenu.hit = true;
            }
            seenMainIdx.add(bIdx);
            return sl;
          });
          if (hadAnySlotBefore && !cleanSlots.some(Boolean)) return null;
          return Object.assign({}, rw, { slots: cleanSlots });
        }).filter(Boolean);
      }
    }

    function getWpStagesCatalog() {
      ensureWpPipelineAndRows();
      const list = appState.onboardingPipeline.map(st => ({
        id: st.id,
        kind: st.kind || 'builtin',
        enabled: st.enabled !== false,
        short: st.title,
        title: st.title
      }));
      const menuTitle = appState.mainMenuStageTitle || '🏠 منوی اصلی و دکمه‌های ربات';
      list.push({ id: 'main_menu', kind: 'fixed', enabled: true, short: menuTitle, title: menuTitle });
      return list;
    }

    function stepBotBuilderStage(delta) {
      const stages = getWpStagesCatalog();
      appState.wpPreviewSubViewBtnId = null;
      appState.wpCurrentStageIdx = (appState.wpCurrentStageIdx + delta + stages.length) % stages.length;
      renderWpBotBuilderStudio();
    }

    function selectWpBuilderStage(idx) {
      appState.wpPreviewSubViewBtnId = null;
      appState.wpCurrentStageIdx = idx;
      renderWpBotBuilderStudio();
    }

    function movePipelineStep(pipeIdx, dir) {
      ensureWpPipelineAndRows();
      const target = pipeIdx + dir;
      if (target < 0 || target >= appState.onboardingPipeline.length) return;
      const tmp = appState.onboardingPipeline[pipeIdx];
      appState.onboardingPipeline[pipeIdx] = appState.onboardingPipeline[target];
      appState.onboardingPipeline[target] = tmp;
      appState.wpCurrentStageIdx = target;
      debouncedSaveBotBuilder();
      renderWpBotBuilderStudio();
    }

    function togglePipelineStepEnabled(pipeIdx, val) {
      ensureWpPipelineAndRows();
      const st = appState.onboardingPipeline[pipeIdx];
      if (!st) return;
      st.enabled = !!val;
      if (st.id === 'step_pass') { appState.onboardingPasswordRequired = !!val; const c = document.getElementById('onboardingPasswordRequiredChk'); if (c) c.checked = !!val; }
      if (st.id === 'step_terms') { appState.onboardingRequired = !!val; const c = document.getElementById('onboardingRequiredChk'); if (c) c.checked = !!val; }
      if (st.id === 'step_phone') { appState.onboardingPhoneRequired = !!val; const c = document.getElementById('onboardingPhoneRequiredChk'); if (c) c.checked = !!val; }
      if (st.id === 'step_pay') { appState.onboardingPaymentRequired = !!val; const c = document.getElementById('onboardingPaymentRequiredChk'); if (c) c.checked = !!val; }
      if (st.id === 'step_contract') { appState.onboardingContractRequired = !!val; const c = document.getElementById('onboardingContractRequiredChk'); if (c) c.checked = !!val; }
      saveSecurityRadarSettings();
      updateWpLivePreviewOnly();
    }

    function addCustomPipelineStep() {
      ensureWpPipelineAndRows();
      const title = prompt('نام مرحله جدید را وارد کنید (مثلاً: 🎯 تعیین سطح یا 📸 ارسال مدرک):', '');
      if (!title || !title.trim()) return;
      const newStep = {
        id: 'custom_step_' + Date.now(),
        kind: 'custom',
        title: title.trim(),
        enabled: true,
        promptText: `{full_name} عزیز، لطفاً برای مرحله «${title.trim()}» گزینه مورد نظر را انتخاب نمایید:`,
        inputMode: 'inline_buttons',
        buttons: [
          { text: '✅ تایید و ادامه', style: 'success', nextStepId: '__next__', linkUrl: '' }
        ]
      };
      appState.onboardingPipeline.push(newStep);
      appState.wpCurrentStageIdx = appState.onboardingPipeline.length - 1;
      syncConfigToBotServer(`مرحله «${title.trim()}» به مسیر اضافه شد!`);
      renderWpBotBuilderStudio();
    }

    function deletePipelineStepAt(idx) {
      if (!Array.isArray(appState.onboardingPipeline) || appState.onboardingPipeline.length <= 1) {
        showToast('حداقل یک مرحله باید در مسیر باقی بماند.', '⚠️');
        return;
      }
      appState.onboardingPipeline.splice(idx, 1);
      appState.wpSimStageIdx = Math.max(0, Math.min(appState.wpSimStageIdx || 0, appState.onboardingPipeline.length));
      saveSecurityRadarSettings();
      renderWpPipelineAndPreview();
      showToast('مرحله از مسیر ثبت‌نام حذف شد.', '🗑️');
    }

    function addButtonToCustomPipelineStep(pipeIdx) {
      const st = appState.onboardingPipeline[pipeIdx];
      if (!st) return;
      if (!Array.isArray(st.buttons)) st.buttons = [];
      st.buttons.push({ text: '🔹 گزینه جدید', style: 'primary', nextStepId: '__next__', linkUrl: '' });
      debouncedSaveBotBuilder();
      renderWpBotBuilderStudio();
    }

    function getTgColorClasses(style) {
      if (style === 'primary') return 'bg-sky-600 hover:bg-sky-500 text-white border-sky-400';
      if (style === 'success') return 'bg-emerald-600 hover:bg-emerald-500 text-white border-emerald-400';
      if (style === 'danger')  return 'bg-rose-600 hover:bg-rose-500 text-white border-rose-400';
      return 'bg-[#2b5278]/65 hover:bg-[#2b5278] text-slate-100 border-slate-600';
    }

    function resolveSlotObj(slot) {
      if (!slot) return null;
      if (slot.source === 'main_menu') {
        const b = appState.telegramMenuButtons?.[slot.index];
        if (!b) return null;
        const lbl = b.label || b.text || 'دکمه';
        b.label = lbl; b.text = lbl;
        const isLocked = !!b.isLocked;
        const dispText = (isLocked && b.showLockIcon !== false && !lbl.includes('🔒')) ? ('🔒 ' + lbl) : lbl;
        return { source: 'main_menu', index: slot.index, text: dispText, rawText: lbl, isLocked, style: b.style || '', enabled: b.enabled !== false, btnObj: b };
      }
      return null;
    }

    function syncMainMenuRowsToButtons() {
      ensureWpPipelineAndRows();
      appState.botFlowNodes = [];
      const activeIndices = new Set();
      (appState.elementorMainRows || []).forEach((rw, rIdx) => {
        const rowNum = rIdx + 1;
        (rw.slots || []).forEach((sl, cIdx) => {
          if (!sl) return;
          if (sl.source === 'main_menu' && appState.telegramMenuButtons?.[sl.index]) {
            activeIndices.add(sl.index);
            const b = appState.telegramMenuButtons[sl.index];
            b.row = rowNum;
            b.col = cIdx + 1;
            b.label = b.label || b.text || 'دکمه';
            b.text  = b.label;
            ensureButtonSubRows(b);
            syncSubRowsToSubButtons(b);
          }
        });
      });
      (appState.telegramMenuButtons || []).forEach((b, idx) => {
        if (!b) return;
        ensureButtonSubRows(b);
        syncSubRowsToSubButtons(b);
        if (!activeIndices.has(idx)) {
          b.enabled = false;
        }
      });
      appState.privateMenuButtons = (appState.telegramMenuButtons || [])
        .filter((b, idx) => b && activeIndices.has(idx) && b.enabled !== false && (b.label || b.text))
        .map(b => b.label || b.text);
    }

        async function manualUnlockStudentKyc(idx) {
      const st = (appState.studentDictionary || [])[idx];
      if (!st) return;
      showToast('در حال تایید دستی احراز هویت...', '⏳');
      try {
        const r = await fetch('index.php?api_manual_unlock_kyc=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ chat_id: st.chat_id || '', username: st.username || '' })
        });
        const d = await r.json();
        if (d && d.ok) {
          st.kyc_locked = true; st.kyc_pdf_v43_sent = true; st.contractSigned = true;
          st.nidOcrVerified = true; st.nationalIdVerifiedByOcr = true;
          if (typeof renderStudentsTable === 'function') renderStudentsTable();
          showToast('✅ احراز هویت دانشجو با موفقیت تایید و قفل گروه/ربات باز شد!', '🔓');
        } else {
          showToast('⚠️ دانشجو در دیتابیس سرور پیدا نشد.', '⚠️');
        }
      } catch (e) { showToast('❌ خطا در ارتباط با سرور', '⚠️'); }
    }
    async function toggleStudentEditUnlock(idx) {
      const st = (appState.studentDictionary || [])[idx];
      if (!st || !st.chat_id) { showToast('⚠️ آیدی عددی این دانشجو ثبت نشده است.', '⚠️'); return; }
      const nextState = !st.edit_unlocked_by_admin;
      try {
        const r = await fetch('index.php?api_toggle_student_edit=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ chat_id: st.chat_id, enable: nextState })
        });
        const d = await r.json();
        if (d && d.ok) {
          st.edit_unlocked_by_admin = nextState;
          if (typeof renderStudentsTable === 'function') renderStudentsTable();
          showToast(nextState ? '✏️ مداد ویرایش پروفایل برای این دانشجو باز شد!' : '🔒 مداد ویرایش برای این دانشجو بسته شد.', '✅');
        }
      } catch (e) { showToast('❌ خطا در ارتباط با سرور', '⚠️'); }
    }
    async function unbanRestoreStudent(idx) {
      const st = (appState.studentDictionary || [])[idx];
      if (!st || !st.chat_id) return;
      if (!confirm('آیا از رفع مسدودی و آن‌بن کردن این دانشجو در گروه و ربات مطمئن هستید؟')) return;
      try {
        const r = await fetch('index.php?api_unban_restore_student=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ chat_id: st.chat_id })
        });
        const d = await r.json();
        if (d && d.ok) {
          st.expelled_after_deadline = false; st.access_status = 'approved'; st.approved = true;
          if (typeof renderStudentsTable === 'function') renderStudentsTable();
          showToast('🔓 دانشجو با موفقیت آن‌بن و بازگردانی شد!', '✅');
        }
      } catch (e) { showToast('❌ خطا در ارتباط با سرور', '⚠️'); }
    }
    function showKycV46Report(text) {
      const box = document.getElementById('kycV46ReportBox');
      if (!box) return;
      box.classList.remove('hidden');
      box.textContent = text;
    }
    async function runDedupPreview() {
      showKycV46Report('⏳ در حال اسکن تکراری‌ها (حالت پیش‌نمایش بدون تغییر)...');
      try {
        const r = await fetch('index.php?api_dedup_preview=1&t=' + Date.now(), { credentials: 'same-origin' });
        const d = await r.json();
        if (d && d.ok) {
          let txt = `🔍 گزارش پیش‌نمایش پاکسازی تکراری‌ها (Dry-Run):\n`;
          txt += `• کل ردیف‌های دانشجو فعلی: ${d.total_before} → پس از ادغام: ${d.total_after}\n`;
          txt += `• ردیف‌های تکراری دانشجو: ${d.duplicate_student_rows}\n`;
          txt += `• لایسنس‌های تکراری ابزار: ${d.duplicate_licenses_removed}\n`;
          txt += `• فایل‌های موقت قدیمی روی سرور: ${d.stale_temp_files}\n`;
          if (Array.isArray(d.duplicate_students_sample) && d.duplicate_students_sample.length) {
            txt += `\nنمونه تکراری‌ها:\n` + d.duplicate_students_sample.map(x => ` - ${x.key} (${x.count}×): ${(x.names||[]).join(' / ')}`).join('\n');
          }
          showKycV46Report(txt);
        }
      } catch (e) { showKycV46Report('❌ خطا در دریافت گزارش.'); }
    }
    async function runDedupExecute() {
      if (!confirm('ابتدا بکاپ کامل گرفته می‌شود و سپس دانشجوها و لایسنس‌های تکراری ادغام می‌شوند. ادامه می‌دهید؟')) return;
      showKycV46Report('⏳ در حال گرفتن بکاپ و اجرای پاکسازی هوشمند...');
      try {
        const r = await fetch('index.php?api_dedup_execute=1&t=' + Date.now(), { method: 'POST', credentials: 'same-origin' });
        const d = await r.json();
        if (d && d.ok) {
          showKycV46Report(`✅ پاکسازی و ادغام هوشمند انجام شد!\n• پوشه بکاپ: backups/${d.backup_folder}\n• دانشجوها: ${d.total_before} → ${d.total_after}\n• لایسنس‌های تکراری حذف‌شده: ${d.duplicate_licenses_removed}\n• فایل‌های موقت پاک‌شده: ${d.stale_temp_files}\n\nصفحه را یکبار رفرش کنید تا لیست تمیز بارگذاری شود.`);
          showToast('✅ پاکسازی هوشمند با بکاپ کامل انجام شد!', '🧹');
        }
      } catch (e) { showKycV46Report('❌ خطا در اجرای پاکسازی.'); }
    }
    async function broadcastKycGrace() {
      if (!confirm('پیام اطلاع‌رسانی مهلت تکمیل ۵ تیک (همراه دکمه مستقیم پروفایل) برای همه دانشجویان ناقص ارسال شود؟')) return;
      showKycV46Report('⏳ در حال ارسال پیام مهلت به دانشجویان ناقص...');
      try {
        const r = await fetch('index.php?api_kyc_broadcast_grace=1&t=' + Date.now(), { method: 'POST', credentials: 'same-origin' });
        const d = await r.json();
        if (d && d.ok) {
          renderKycActionTabularReport(d);
          showToast(`📣 به ${d.sent} دانشجو ارسال شد!`, '✅');
        }
      } catch (e) { showKycV46Report('❌ خطا در ارسال همگانی.'); }
    }
    function sxJalaliTripletToGregorian(jy, jm, jd) {
      let gy = (jy <= 979) ? 621 : 1600;
      jy -= (jy <= 979) ? 0 : 979;
      let days = (365 * jy) + (Math.floor(jy / 33) * 8) + Math.floor(((jy % 33) + 3) / 4) + 78 + jd + ((jm < 7) ? (jm - 1) * 31 : ((jm - 7) * 30) + 186);
      gy += 400 * Math.floor(days / 146097);
      days %= 146097;
      if (days > 36524) { gy += 100 * Math.floor(--days / 36524); days %= 36524; if (days >= 365) days++; }
      gy += 4 * Math.floor(days / 1461);
      days %= 1461;
      gy += Math.floor((days - 1) / 365);
      if (days > 365) days = (days - 1) % 365;
      let gd = days + 1;
      const sal_a = [0, 31, ((gy % 4 === 0 && gy % 100 !== 0) || (gy % 400 === 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      let gm = 0;
      for (gm = 1; gm <= 12 && gd > sal_a[gm]; gm++) gd -= sal_a[gm];
      return [gy, gm, gd];
    }
    function syncJalaliDeadlineToIso(doSave) {
      const jInp = document.getElementById('kycDeadlineJalaliInput');
      const tInp = document.getElementById('kycDeadlineTimeInput');
      const isoInp = document.getElementById('kycDeadlineIsoInput');
      const prev = document.getElementById('kycDeadlineGregPreview');
      if (!jInp || !isoInp) return;
      const raw = (jInp.value || '').replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/[٠-٩]/g, d => '٠١٢٣٤٥٦٧٨٩'.indexOf(d)).trim();
      const tm = (tInp?.value || '23:59').trim();
      const m = raw.match(/^(\d{4})[\/\-.](\d{1,2})[\/\-.](\d{1,2})$/);
      if (!m) {
        if (prev) prev.textContent = raw ? 'فرمت صحیح: 1405/09/05' : '';
        if (!raw) isoInp.value = '';
        if (doSave) saveSecurityRadarSettings();
        return;
      }
      const jy = parseInt(m[1], 10), jm = parseInt(m[2], 10), jd = parseInt(m[3], 10);
      if (jy < 1390 || jy > 1500 || jm < 1 || jm > 12 || jd < 1 || jd > 31) {
        if (prev) prev.textContent = 'تاریخ شمسی نامعتبر';
        return;
      }
      const [gy, gm, gd] = sxJalaliTripletToGregorian(jy, jm, jd);
      const pad = n => String(n).padStart(2, '0');
      const iso = `${gy}-${pad(gm)}-${pad(gd)}T${tm}:00+03:30`;
      isoInp.value = iso;
      if (prev) prev.textContent = `= ${gy}-${pad(gm)}-${pad(gd)} ${tm} IRST`;
      if (doSave) saveSecurityRadarSettings();
    }
    async function previewKycExpulsion() {
      showKycV46Report('⏳ در حال محاسبه صف اخراج (کاربران کمتر از ۵ تیک، بدون ادمین‌ها و معاف‌ها)...');
      try {
        const r = await fetch('index.php?api_kyc_expel_preview=1&t=' + Date.now(), { credentials: 'same-origin' });
        const raw = await r.text();
        let d = null;
        try { d = JSON.parse(raw); } catch (_) { showKycV46Report('❌ پاسخ غیرمنتظره سرور (HTTP ' + r.status + '): ' + raw.slice(0, 220)); return; }
        if (d && d.ok) {
          let txt = `👀 پیش‌نمایش صف اخراج پس از مهلت (${d.count} نفر ناقص):\n`;
          txt += `• مهلت تنظیم‌شده: ${d.deadline_iso || 'تنظیم‌نشده'} | اخراج خودکار کرون: ${d.auto_expel_enabled ? 'روشن' : 'خاموش'}\n`;
          (d.targets || []).slice(0, 40).forEach(t => {
            txt += ` - ${t.name} (${t.uid}) → ${t.done_count}/5 تیک | نواقص: ${(t.missing||[]).join(', ')} ${t.expelled ? '[قبلاً اخراج‌شده]' : ''}\n`;
          });
          showKycV46Report(txt);
        } else {
          showKycV46Report('⚠️ ' + ((d && d.error) || 'خطا در دریافت صف اخراج.'));
        }
      } catch (e) { showKycV46Report('❌ خطای شبکه در دریافت صف اخراج: ' + (e && e.message ? e.message : '')); }
    }
    function renderKycActionTabularReport(d) {
      const box = document.getElementById('kycV46ReportBox');
      if (!box) return;
      box.classList.remove('hidden');
      const isRestore = (d.type === 'restore');
      const hdr = isRestore
        ? `🚑 گزارش جدولی بازگردانی و آن‌بن (${d.time || ''}) — کل: ${d.restored || 0} نفر | پیام پی‌وی موفق: ${d.notified || 0} نفر | لینک گروه: ${d.has_invite_link ? 'فعال' : 'ندارد'}`
        : `📣 گزارش جدولی ارسال پیام مهلت (${d.time || ''}) — ارسال موفق: ${d.sent || 0} نفر | ناموفق: ${d.failed || 0} نفر | کل: ${d.total_targets || 0} نفر`;
      const rows = Array.isArray(d.details) ? d.details : [];
      let html = `<div class="font-extrabold text-emerald-300 mb-2">${escapeHtml(hdr)}</div>`;
      if (!rows.length) {
        html += `<div class="text-slate-400">موردی در این عملیات ثبت نشده است.</div>`;
      } else {
        html += `<div class="overflow-x-auto"><table class="w-full text-[11px] text-right border-collapse">
          <thead><tr class="border-b border-slate-700 text-slate-300">
            <th class="py-1 px-1.5 text-center w-8">ردیف</th>
            <th class="py-1 px-2">نام دانشجو</th>
            <th class="py-1 px-2">آیدی / یوزرنیم</th>
            <th class="py-1 px-2 text-center">${isRestore ? 'وضعیت گروه/ربات' : 'وضعیت تیک‌ها'}</th>
            <th class="py-1 px-2 text-center">ارسال پیام پی‌وی</th>
          </tr></thead><tbody>` +
          rows.map((r, i) => `<tr class="border-b border-slate-800/70">
            <td class="py-1 px-1.5 text-center text-slate-400 font-mono">${i + 1}</td>
            <td class="py-1 px-2 font-bold text-white">${escapeHtml(r.name || '-')}</td>
            <td class="py-1 px-2 font-mono text-sky-300" dir="ltr">${escapeHtml(r.uid || '')}${r.username ? ' (' + escapeHtml(r.username) + ')' : ''}</td>
            <td class="py-1 px-2 text-center text-cyan-200">${escapeHtml(r.status_col || '-')}</td>
            <td class="py-1 px-2 text-center">${r.dm_ok ? '<span class="text-emerald-300 font-bold">✅ ارسال شد</span>' : '<span class="text-rose-400 font-bold" title="' + escapeHtml(r.dm_error || '') + '">❌ ناموفق' + (r.dm_error ? ' (' + escapeHtml(r.dm_error.slice(0, 35)) + ')' : '') + '</span>'}</td>
          </tr>`).join('') + `</tbody></table></div>`;
      }
      box.innerHTML = html;
    }
    async function loadLastKycActionReport() {
      showKycV46Report('⏳ در حال بارگذاری آخرین گزارش جدولی ذخیره‌شده...');
      try {
        const r = await fetch('index.php?api_kyc_last_action_report=1&t=' + Date.now(), { credentials: 'same-origin' });
        const d = await r.json();
        if (d && d.ok) renderKycActionTabularReport(d);
        else showKycV46Report('ℹ️ ' + ((d && d.error) || 'هنوز گزارشی ثبت نشده است.'));
      } catch (e) { showKycV46Report('❌ خطا در دریافت گزارش.'); }
    }
    async function massUnbanRestoreExpelled() {
      if (!confirm('همه دانشجویانی که به خاطر پایان مهلت اخراج/مسدود شده‌اند، فوراً از گروه آن‌بن، در ربات رفع مسدودی و پیام آرامش‌بخش همراه لینک بازگشت به گروه برایشان ارسال شود؟')) return;
      showKycV46Report('🚑 در حال آن‌بن و بازگردانی فوری همه دانشجویان اخراج‌شده...');
      try {
        const r = await fetch('index.php?api_kyc_mass_unban_restore=1&t=' + Date.now(), { method: 'POST', credentials: 'same-origin' });
        const d = await r.json();
        if (d && d.ok) {
          const chk = document.getElementById('kycAutoExpelChk');
          if (chk) chk.checked = false;
          renderKycActionTabularReport(d);
          showToast(`🚑 ${d.restored} دانشجو با موفقیت آن‌بن و بازگردانی شدند!`, '✅');
          if (typeof loadKycMatrixTable === 'function') loadKycMatrixTable();
        } else {
          showKycV46Report('⚠️ خطا در بازگردانی.');
        }
      } catch (e) { showKycV46Report('❌ خطای ارتباط با سرور.'); }
    }
    async function runKycExpulsionNow() {
      if (!confirm('⚠️ هشدار: همه کاربران غیرمعاف با کمتر از ۵ تیک پیام دریافت کرده، از گروه بن دائم (بدون آن‌بن) و در ربات مسدود می‌شوند. مطمئن هستید؟')) return;
      showKycV46Report('⏳ در حال اجرای اخراج و بن دائم افراد ناقص...');
      try {
        const r = await fetch('index.php?api_kyc_run_expulsion=1&t=' + Date.now(), { method: 'POST', credentials: 'same-origin' });
        const d = await r.json();
        if (d && d.ok) {
          showKycV46Report(`⛔ اجرای اخراج پایان یافت:\n• تعداد اخراج و بن دائم‌شده: ${d.expelled}\n• کل افراد ناقص بررسی‌شده: ${d.total_incomplete}`);
          showToast(`⛔ ${d.expelled} کاربر ناقص اخراج و مسدود شدند.`, '⚠️');
        }
      } catch (e) { showKycV46Report('❌ خطا در اجرای اخراج.'); }
    }
    window._kycMatrixRows = [];
    window._kycMatrixFilter = 'all';
    window._kycMatrixSelected = new Set();

    async function loadKycMatrixTable() {
      const tb = document.getElementById('kycMatrixTbody');
      if (tb) tb.innerHTML = '<tr><td colspan="10" class="py-5 text-center text-sky-300">⏳ در حال دریافت وضعیت زنده از SQLite...</td></tr>';
      try {
        const r = await fetch('index.php?api_kyc_matrix=1&t=' + Date.now(), { credentials: 'same-origin' });
        const d = await r.json();
        if (d && d.ok && Array.isArray(d.rows)) {
          window._kycMatrixRows = d.rows;
          window._kycMatrixSelected.clear();
          const selAll = document.getElementById('kmSelectAllChk');
          if (selAll) selAll.checked = false;
          renderKycMatrixTable();
        } else if (tb) {
          tb.innerHTML = '<tr><td colspan="10" class="py-5 text-center text-rose-300">⚠️ خطا در دریافت داده‌های جدول.</td></tr>';
        }
      } catch (e) {
        if (tb) tb.innerHTML = '<tr><td colspan="10" class="py-5 text-center text-rose-300">❌ خطای ارتباط با سرور.</td></tr>';
      }
    }

    function setKycMatrixFilter(mode) {
      window._kycMatrixFilter = mode;
      ['all', 'complete', 'incomplete', 'exempt', 'expelled', 'left_group', 'left_channel'].forEach(k => {
        const b = document.getElementById('kmFil-' + k);
        if (!b) return;
        if (k === mode) { b.classList.add('bg-sky-600', 'text-white'); b.classList.remove('bg-slate-800'); }
        else { b.classList.remove('bg-sky-600', 'text-white'); b.classList.add('bg-slate-800'); }
      });
      renderKycMatrixTable();
    }

    function getFilteredKycMatrixRows() {
      const rows = Array.isArray(window._kycMatrixRows) ? window._kycMatrixRows : [];
      const q = (document.getElementById('kycMatrixSearchInp')?.value || '').trim().toLowerCase();
      const missFil = document.getElementById('kycMatrixMissingFilter')?.value || 'any';
      const sortBy = document.getElementById('kycMatrixSortSel')?.value || 'alpha_asc';
      const mode = window._kycMatrixFilter || 'all';

      let list = rows.filter(r => {
        if (mode === 'complete' && !r.all_5_done) return false;
        if (mode === 'incomplete' && (r.all_5_done || r.is_exempt || r.is_admin)) return false;
        if (mode === 'exempt' && !r.is_exempt && !r.is_admin) return false;
        if (mode === 'expelled' && !r.expelled) return false;
        if (mode === 'left_group' && !['left', 'kicked'].includes(r.sync_group_status || '')) return false;
        if (mode === 'left_channel' && !['left', 'kicked'].includes(r.sync_channel_status || '')) return false;

        if (missFil === 'no_identity' && r.has_identity) return false;
        if (missFil === 'no_phone' && r.has_phone) return false;
        if (missFil === 'no_email' && r.has_email) return false;
        if (missFil === 'no_nid_scan' && r.has_nid_scan) return false;
        if (missFil === 'no_pdf' && r.has_pdf) return false;

        if (q) {
          const hay = [r.first_name, r.last_name, r.full_name, r.username, r.uid, r.national_id, r.phone, r.email].join(' ').toLowerCase();
          if (!hay.includes(q)) return false;
        }
        return true;
      });

      if (sortBy === 'alpha_asc') {
        list.sort((a, b) => String(a.full_name || a.first_name || a.username || '').localeCompare(String(b.full_name || b.first_name || b.username || ''), 'fa'));
      } else if (sortBy === 'alpha_desc') {
        list.sort((a, b) => String(b.full_name || b.first_name || b.username || '').localeCompare(String(a.full_name || a.first_name || a.username || ''), 'fa'));
      } else if (sortBy === 'most_missing') {
        list.sort((a, b) => (a.done_count || 0) - (b.done_count || 0));
      } else if (sortBy === 'most_complete') {
        list.sort((a, b) => (b.done_count || 0) - (a.done_count || 0));
      }
      return list;
    }

    function updateKycMatrixSelCounter() {
      const el = document.getElementById('kmSelectedCount');
      if (el) el.textContent = String(window._kycMatrixSelected.size);
    }

    function toggleOneKycMatrix(uid, checked) {
      if (!uid) return;
      if (checked) window._kycMatrixSelected.add(uid);
      else window._kycMatrixSelected.delete(uid);
      updateKycMatrixSelCounter();
    }

    function toggleSelectAllKycMatrix(checked) {
      const list = getFilteredKycMatrixRows();
      list.forEach(r => {
        if (!r.uid) return;
        if (checked) window._kycMatrixSelected.add(r.uid);
        else window._kycMatrixSelected.delete(r.uid);
      });
      renderKycMatrixTable();
    }

    function renderKycMatrixTable() {
      const all = Array.isArray(window._kycMatrixRows) ? window._kycMatrixRows : [];
      const cOk = all.filter(r => r.all_5_done).length;
      const cInc = all.filter(r => !r.all_5_done && !r.is_exempt && !r.is_admin).length;
      const cEx = all.filter(r => r.is_exempt || r.is_admin).length;
      const cExp = all.filter(r => r.expelled).length;
      const setT = (id, v) => { const e = document.getElementById(id); if (e) e.textContent = String(v); };
      const cLeftGrp = all.filter(r => ['left', 'kicked'].includes(r.sync_group_status || '')).length;
      const cLeftCh = all.filter(r => ['left', 'kicked'].includes(r.sync_channel_status || '')).length;
      setT('kmCntAll', all.length); setT('kmCntOk', cOk); setT('kmCntInc', cInc); setT('kmCntEx', cEx); setT('kmCntExp', cExp); setT('kmCntLeftGrp', cLeftGrp); setT('kmCntLeftCh', cLeftCh);
      const badge = document.getElementById('kycMatrixSummaryBadge');
      if (badge) badge.textContent = `کل: ${all.length} | کامل: ${cOk} | ناقص: ${cInc}`;

      const list = getFilteredKycMatrixRows();
      const tb = document.getElementById('kycMatrixTbody');
      if (!tb) return;
      if (!list.length) {
        tb.innerHTML = '<tr><td colspan="11" class="py-5 text-center text-slate-400">موردی با این فیلتر پیدا نشد.</td></tr>';
        updateKycMatrixSelCounter();
        return;
      }
      const okCell = (ok, val) => ok
        ? `<span class="text-emerald-300 font-bold" title="${escapeHtml(val || '')}">✓ ${escapeHtml(val || '')}</span>`
        : `<span class="text-rose-400 font-bold">✗ ناقص</span>`;

      tb.innerHTML = list.map((r, i) => {
        const chk = r.uid && window._kycMatrixSelected.has(r.uid) ? 'checked' : '';
        const rowBg = r.expelled ? 'bg-rose-950/35' : (r.all_5_done ? 'bg-emerald-950/15' : 'hover:bg-slate-900/70');
        const grpBadge = ['left', 'kicked'].includes(r.sync_group_status || '') ? ' <span class="text-[9px] px-1 rounded bg-orange-600/35 text-orange-200" title="در گروه کلاب عضو نیست">👻 خارج از گروه</span>' : '';
        const exTag = (r.is_admin ? ' <span class="text-[9px] px-1 rounded bg-purple-600/40 text-purple-200">ادمین</span>' : (r.is_exempt ? ' <span class="text-[9px] px-1 rounded bg-cyan-600/40 text-cyan-200">معاف</span>' : '')) + grpBadge;
        return `<tr class="border-b border-slate-800/70 ${rowBg}">
          <td class="py-1.5 px-1.5 text-center">${r.uid ? `<input type="checkbox" ${chk} onchange="toggleOneKycMatrix('${escapeHtml(r.uid)}',this.checked)" class="w-3.5 h-3.5 accent-amber-400 cursor-pointer" />` : '-'}</td>
          <td class="py-1.5 px-1.5 text-center text-slate-400 font-mono">${i + 1}</td>
          <td class="py-1.5 px-2 font-bold text-white">${escapeHtml(r.first_name || '-')}${exTag}</td>
          <td class="py-1.5 px-2 text-slate-200">${escapeHtml(r.last_name || '-')}</td>
          <td class="py-1.5 px-2 font-mono" dir="ltr">${okCell(r.has_nat, r.national_id)}</td>
          <td class="py-1.5 px-2 font-mono" dir="ltr">${okCell(r.has_phone, r.phone)}</td>
          <td class="py-1.5 px-2 font-mono text-[10px]" dir="ltr">${okCell(r.has_email, r.email)}</td>
          <td class="py-1.5 px-2 text-center whitespace-nowrap">${(() => {
            const pBadge = (st, lbl) => {
              if (st === true) return `<span class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-500/35 font-bold text-[10px]">✓ ${lbl}</span>`;
              if (st === false) return `<span class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-rose-500/20 text-rose-300 border border-rose-500/35 font-bold text-[10px]">✗ ${lbl}</span>`;
              return `<span class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 font-bold text-[10px]" title="برای استعلام، سینک را بزنید">؟ ${lbl}</span>`;
            };
            const inBot = (r.sync_in_bot === false) ? false : !!r.uid;
            const inGrp = r.sync_in_group === true ? true : (['left','kicked'].includes(r.sync_group_status || '') ? false : null);
            const inCh  = r.sync_in_channel === true ? true : (['left','kicked'].includes(r.sync_channel_status || '') ? false : null);
            const inPnl = r.sync_in_panel === false ? false : !r.expelled;
            return `<div class="inline-flex items-center gap-1 flex-wrap justify-center">${pBadge(inBot,'ربات')}${pBadge(inGrp,'گروه')}${pBadge(inCh,'کانال')}${pBadge(inPnl,'پنل')}</div>`;
          })()}</td>
          <td class="py-1.5 px-2 text-center">${r.has_nid_scan ? '<span class="px-1.5 py-0.5 rounded bg-emerald-500/20 text-emerald-300 font-bold">✓ دارد</span>' : '<span class="px-1.5 py-0.5 rounded bg-rose-500/20 text-rose-300 font-bold">✗ ندارد</span>'}</td>
          <td class="py-1.5 px-2 text-center">${r.has_pdf ? '<span class="px-1.5 py-0.5 rounded bg-emerald-500/20 text-emerald-300 font-bold">✓ دارد</span>' : '<span class="px-1.5 py-0.5 rounded bg-rose-500/20 text-rose-300 font-bold">✗ ندارد</span>'}</td>
          <td class="py-1.5 px-2 text-center whitespace-nowrap">
            ${r.uid ? `<button type="button" onclick="toggleMatrixRowEdit('${escapeHtml(r.uid)}', ${r.edit_unlocked ? 'false' : 'true'})" class="px-1.5 py-0.5 rounded ${r.edit_unlocked ? 'bg-amber-500 text-slate-950' : 'bg-slate-800 text-slate-300'} font-bold ml-1" title="${r.edit_unlocked ? 'مداد باز است (کلیک = بستن)' : 'مداد بسته است (کلیک = باز کردن)'}">✏️</button><button type="button" onclick="sendKycGraceToSingle('${escapeHtml(r.uid)}','${escapeHtml(r.full_name || r.uid)}')" class="px-1.5 py-0.5 rounded bg-sky-600/80 hover:bg-sky-500 text-white font-bold" title="ارسال پیام مهلت فقط به این دانشجو">📩</button><button type="button" onclick="purgeSingleKycMatrixRow('${escapeHtml(r.uid)}','${escapeHtml(r.key || '')}','${escapeHtml(r.full_name || r.uid)}')" class="px-1.5 py-0.5 rounded bg-rose-600/80 hover:bg-rose-500 text-white font-bold mr-1" title="حذف ریشه‌ای از کل سامانه (ربات، کارنامه، SQLite و ماتریس)">🗑️</button>` : '-'}
          </td>
        </tr>`;
      }).join('');
      updateKycMatrixSelCounter();
    }

    async function toggleMatrixRowEdit(uid, enable) {
      try {
        const r = await fetch('index.php?api_toggle_student_edit=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ chat_id: uid, enable: !!enable })
        });
        const d = await r.json();
        if (d && d.ok) {
          const row = (window._kycMatrixRows || []).find(x => x.uid === uid);
          if (row) row.edit_unlocked = !!enable;
          renderKycMatrixTable();
          showToast(enable ? '✏️ مداد ویرایش برای این دانشجو باز شد!' : '🔒 مداد ویرایش بسته شد.', '✅');
        }
      } catch (e) { showToast('❌ خطا در ارتباط با سرور', '⚠️'); }
    }

    async function bulkToggleEditForSelected(enable) {
      const uids = Array.from(window._kycMatrixSelected);
      if (!uids.length) { showToast('⚠️ ابتدا حداقل یک دانشجو را از جدول انتخاب کنید.', '⚠️'); return; }
      try {
        const r = await fetch('index.php?api_kyc_bulk_edit_toggle=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ uids, enable: !!enable })
        });
        const d = await r.json();
        if (d && d.ok) {
          const s = new Set(uids);
          (window._kycMatrixRows || []).forEach(x => { if (s.has(x.uid)) x.edit_unlocked = !!enable; });
          renderKycMatrixTable();
          showToast(enable ? `✏️ مداد ویرایش برای ${d.count} نفر باز شد!` : `🔒 مداد ویرایش برای ${d.count} نفر بسته شد.`, '✅');
        }
      } catch (e) { showToast('❌ خطا در ارتباط با سرور', '⚠️'); }
    }

    async function sendKycGraceToSingle(uid, name) {
      if (!confirm(`پیام مهلت تکمیل پرونده (همراه دکمه مستقیم پروفایل) فقط برای «${name}» ارسال شود؟`)) return;
      try {
        const r = await fetch('index.php?api_kyc_broadcast_grace=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ uids: [uid] })
        });
        const d = await r.json();
        if (d && d.ok) showToast(d.sent > 0 ? `📩 پیام مهلت برای ${name} ارسال شد!` : '⚠️ ارسال ناموفق بود (ربات استارت نشده یا بلاک است).', d.sent > 0 ? '✅' : '⚠️');
      } catch (e) { showToast('❌ خطا در ارسال.', '⚠️'); }
    }

    async function sendKycGraceToSelected() {
      const uids = Array.from(window._kycMatrixSelected);
      if (!uids.length) { showToast('⚠️ ابتدا افراد مورد نظر را از جدول تیک بزنید.', '⚠️'); return; }
      if (!confirm(`پیام مهلت تکمیل ۵ تیک (بر اساس تنظیمات همین بخش) برای ${uids.length} دانشجوی انتخاب‌شده ارسال شود؟`)) return;
      showKycV46Report(`⏳ در حال ارسال پیام هدفمند به ${uids.length} نفر انتخاب‌شده...`);
      try {
        const r = await fetch('index.php?api_kyc_broadcast_grace=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ uids })
        });
        const d = await r.json();
        if (d && d.ok) {
          renderKycActionTabularReport(d);
          showToast(`📣 برای ${d.sent} نفر ارسال شد!`, '✅');
        }
      } catch (e) { showKycV46Report('❌ خطا در ارسال هدفمند.'); }
    }

    
    // =========================================================================
    // v4.9.39: UNIFIED 4-SOURCE SYNC ENGINE & SINGLE/BULK ROOT PURGE
    // =========================================================================
    async function runEcosystemSync(source) {
      const labels = {
        bot: '🤖 ربات و SQLite',
        group: '👥 گروه تلگرام',
        channel: '📢 کانال تلگرام',
        panel: '🖥️ پنل تحت وب',
        all: '⚡ هر ۴ بستر (ربات، گروه، کانال و پنل)'
      };
      const badges = document.querySelectorAll('.sxSyncStatusBadge');
      badges.forEach(b => { b.textContent = `⏳ در حال همگام‌سازی ${labels[source] || source}...`; });
      showToast(`⏳ در حال همگام‌سازی ${labels[source] || source}...`, '🔄');
      try {
        const r = await fetch('index.php?api_sync_ecosystem_students=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ source })
        });
        const d = await r.json();
        if (!d || !d.ok) {
          showToast((d && d.error) || '❌ خطا در همگام‌سازی', '⚠️');
          badges.forEach(b => { b.textContent = '❌ خطا در سینک'; });
          return;
        }
        const st = d.stats || {};
        const summary = `کل: ${st.total_students || 0} | در گروه: ${st.group_in_count || 0}${st.group_total_tg ? ('/' + st.group_total_tg) : ''} | خارج از گروه: ${st.group_left_count || 0} | کانال: ${st.channel_in_count || 0}`;
        badges.forEach(b => { b.textContent = `✅ ${summary}`; });

        // Refresh ALL student views across the admin panel simultaneously
        if (typeof syncLiveStudentsFromServer === 'function') await syncLiveStudentsFromServer(false);
        if (typeof loadKycMatrixTable === 'function') await loadKycMatrixTable();
        if (typeof loadGroupAnalytics === 'function' && document.getElementById('groupAnalyticsTableBody')) {
          try { loadGroupAnalytics(); } catch(_) {}
        }

        let msg = `✅ همگام‌سازی ${labels[source]} انجام شد (${summary})`;
        if (st.added_from_group > 0) msg += ` · +${st.added_from_group} نفر از گروه اضافه شد`;
        if (st.group_error && (source === 'group' || source === 'all')) msg += ` | ⚠️ ${st.group_error}`;
        if (st.channel_error && (source === 'channel' || source === 'all')) msg += ` | ⚠️ ${st.channel_error}`;
        showToast(msg, '✅');
      } catch (e) {
        badges.forEach(b => { b.textContent = '❌ خطای شبکه'; });
        showToast('❌ خطا در ارتباط با سرور هنگام همگام‌سازی', '⚠️');
      }
    }

    async function purgeSingleKycMatrixRow(uid, key, name) {
      if (!confirm(`⚠️ حذف ریشه‌ای «${name}» از کل سامانه (لیست ربات، کارنامه، گزارش گروه، SQLite و ماتریس ۵ تیک) انجام شود؟`)) return;
      try {
        const r = await fetch('index.php?api_purge_students_completely=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ chat_ids: [uid], keys: key ? [key] : [] })
        });
        const d = await r.json();
        if (d && d.ok) {
          window._kycMatrixSelected.delete(uid);
          showToast(`🧹 «${name}» به صورت ریشه‌ای از تمام بخش‌ها حذف شد.`, '✅');
          if (typeof syncLiveStudentsFromServer === 'function') await syncLiveStudentsFromServer(false);
          if (typeof loadKycMatrixTable === 'function') await loadKycMatrixTable();
        } else {
          showToast((d && d.error) || '❌ خطا در حذف دانشجو', '⚠️');
        }
      } catch (e) { showToast('❌ خطا در ارتباط با سرور', '⚠️'); }
    }

    async function bulkPurgeKycMatrixSelected() {
      const uids = Array.from(window._kycMatrixSelected || []);
      if (!uids.length) { showToast('⚠️ ابتدا حداقل یک دانشجو را از جدول تیک بزنید.', '⚠️'); return; }
      if (!confirm(`⚠️ تایید نهایی: ${uids.length} دانشجوی انتخاب‌شده به صورت ریشه‌ای از کل سامانه (ربات، کارنامه، گزارش گروه، SQLite و ماتریس) حذف شوند؟`)) return;
      const rows = (window._kycMatrixRows || []).filter(x => uids.includes(x.uid));
      const keys = rows.map(x => x.key).filter(Boolean);
      try {
        const r = await fetch('index.php?api_purge_students_completely=1&t=' + Date.now(), {
          method: 'POST', credentials: 'same-origin',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ chat_ids: uids, keys })
        });
        const d = await r.json();
        if (d && d.ok) {
          window._kycMatrixSelected.clear();
          showToast(`🧹 ${d.purged_count || uids.length} دانشجو به صورت ریشه‌ای از کل سامانه حذف شدند.`, '✅');
          if (typeof syncLiveStudentsFromServer === 'function') await syncLiveStudentsFromServer(false);
          if (typeof loadKycMatrixTable === 'function') await loadKycMatrixTable();
        } else {
          showToast((d && d.error) || '❌ خطا در حذف گروهی', '⚠️');
        }
      } catch (e) { showToast('❌ خطا در ارتباط با سرور', '⚠️'); }
    }

    function exportKycMatrix(format) {
      const filtered = getFilteredKycMatrixRows();
      const sel = window._kycMatrixSelected || new Set();
      const rows = sel.size > 0 ? filtered.filter(r => r.uid && sel.has(r.uid)) : filtered;
      if (!rows.length) {
        showToast('⚠️ هیچ ردیفی برای خروجی گرفتن وجود ندارد.', '⚠️');
        return;
      }
      const mask = !!document.getElementById('kmExportMaskChk')?.checked;
      const filterNames = { all: 'همه دانشجویان', complete: 'کامل‌ها (۵ از ۵)', incomplete: 'نواقص', exempt: 'معاف‌ها', expelled: 'اخراجی‌ها' };
      const curFilterLbl = filterNames[window._kycMatrixFilter || 'all'] || 'همه';
      const nowStr = new Date().toLocaleString('fa-IR');
      const okCount = rows.filter(r => r.all_5_done).length;
      const incCount = rows.filter(r => !r.all_5_done && !r.is_exempt && !r.is_admin).length;

      const fmtVal = (has, rawVal, doneLabel) => {
        if (!has) return '✗ ناقص';
        return mask ? doneLabel : ('✓ ' + String(rawVal || ''));
      };
      const fmtStatus = (r) => {
        if (r.expelled) return '⛔ اخراجی';
        if (r.is_admin) return '🛡️ ادمین';
        if (r.is_exempt) return '🛡️ معاف';
        return r.all_5_done ? '✅ کامل (۵/۵)' : `⚠️ ناقص (${r.done_count || 0}/۵)`;
      };

      const trRows = rows.map((r, idx) => {
        const natTxt = fmtVal(r.has_nat, r.national_id, '✓ تایید شده');
        const phoneTxt = fmtVal(r.has_phone, r.phone, '✓ تایید شده');
        const emailTxt = fmtVal(r.has_email, r.email, '✓ تایید شده');
        const pSym = (v) => v === true ? '✓' : (v === false ? '✗' : '؟');
        const inBotE = (r.sync_in_bot === false) ? false : !!r.uid;
        const inGrpE = r.sync_in_group === true ? true : (['left','kicked'].includes(r.sync_group_status || '') ? false : null);
        const inChE  = r.sync_in_channel === true ? true : (['left','kicked'].includes(r.sync_channel_status || '') ? false : null);
        const inPnlE = r.sync_in_panel === false ? false : !r.expelled;
        const platTxt = `ربات:${pSym(inBotE)} | گروه:${pSym(inGrpE)} | کانال:${pSym(inChE)} | پنل:${pSym(inPnlE)}`;
        const nidTxt = r.has_nid_scan ? '✓ اسکن شد' : '✗ ندارد';
        const pdfTxt = r.has_pdf ? '✓ امضا شد' : '✗ ندارد';
        const stTxt = fmtStatus(r);
        if (format === 'excel') {
          return `<tr>
            <td style="text-align:center;">${idx + 1}</td>
            <td>${escapeHtml(r.first_name || '-')}</td>
            <td>${escapeHtml(r.last_name || '-')}</td>
            <td style="mso-number-format:'\\@';text-align:center;color:${r.has_nat ? '#047857' : '#be123c'};font-weight:bold;">${escapeHtml(natTxt)}</td>
            <td style="mso-number-format:'\\@';text-align:center;color:${r.has_phone ? '#047857' : '#be123c'};font-weight:bold;">${escapeHtml(phoneTxt)}</td>
            <td style="mso-number-format:'\\@';text-align:center;color:${r.has_email ? '#047857' : '#be123c'};font-weight:bold;">${escapeHtml(emailTxt)}</td>
            <td style="text-align:center;color:${r.has_nid_scan ? '#047857' : '#be123c'};font-weight:bold;">${nidTxt}</td>
            <td style="text-align:center;color:${r.has_pdf ? '#047857' : '#be123c'};font-weight:bold;">${pdfTxt}</td>
            <td style="text-align:center;font-weight:bold;">${escapeHtml(stTxt)}</td>
          </tr>`;
        }
        const badge = (ok, txt) => `<span class="pill ${ok ? 'ok' : 'no'}">${escapeHtml(txt)}</span>`;
        return `<tr>
          <td class="num">${idx + 1}</td>
          <td class="bold">${escapeHtml(r.first_name || '-')}</td>
          <td>${escapeHtml(r.last_name || '-')}</td>
          <td dir="${mask ? 'rtl' : 'ltr'}" class="mono">${badge(r.has_nat, natTxt)}</td>
          <td dir="${mask ? 'rtl' : 'ltr'}" class="mono">${badge(r.has_phone, phoneTxt)}</td>
          <td dir="${mask ? 'rtl' : 'ltr'}" class="mono">${badge(r.has_email, emailTxt)}</td>
          <td class="ctr" style="font-size:11px;font-weight:700;">${escapeHtml(platTxt)}</td>
          <td class="ctr">${badge(r.has_nid_scan, nidTxt)}</td>
          <td class="ctr">${badge(r.has_pdf, pdfTxt)}</td>
          <td class="ctr"><span class="st ${r.all_5_done ? 'ok' : 'warn'}">${escapeHtml(stTxt)}</span></td>
        </tr>`;
      }).join('');

      const dateSlug = new Date().toISOString().slice(0, 10);
      const maskSlug = mask ? '_masked' : '_full';

      if (format === 'excel') {
        const xlsDoc = `\uFEFF<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40" dir="rtl" lang="fa">
<head><meta charset="UTF-8" />
<style>
  body { font-family: Tahoma, Arial, sans-serif; direction: rtl; }
  table { border-collapse: collapse; width: 100%; }
  th { background: #0f172a; color: #ffffff; font-weight: bold; padding: 8px; border: 1px solid #334155; }
  td { padding: 6px 8px; border: 1px solid #cbd5e1; font-size: 12px; }
  tr:nth-child(even) td { background: #f8fafc; }


/* ---- legacy style block 4 ---- */

  *{box-sizing:border-box;font-family:'Vazirmatn',Tahoma,sans-serif}
  body{margin:0;padding:24px 16px;background:#060d18;color:#f1f5f9}
  .wrap{max-width:1120px;margin:0 auto}
  .head{background:linear-gradient(135deg,#0f172a,#102542);border:1px solid rgba(14,165,233,.35);border-radius:16px;padding:18px 20px;margin-bottom:16px;display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px}
  .head h1{margin:0;font-size:18px;font-weight:900;color:#fff}
  .meta{font-size:12px;color:#94a3b8;margin-top:4px}
  .kpis{display:flex;gap:8px;flex-wrap:wrap}
  .kpi{background:rgba(15,23,42,.85);border:1px solid rgba(148,163,184,.2);border-radius:10px;padding:6px 12px;font-size:12px;font-weight:800}
  .card{background:#0b1526;border:1px solid rgba(148,163,184,.18);border-radius:16px;overflow:hidden}
  table{width:100%;border-collapse:collapse;font-size:12.5px}
  th{background:#0f1d35;color:#cbd5e1;padding:11px 10px;text-align:right;border-bottom:1px solid rgba(148,163,184,.2);font-weight:800}
  td{padding:9px 10px;border-bottom:1px solid rgba(148,163,184,.1);vertical-align:middle}
  tr:hover td{background:rgba(14,165,233,.06)}
  .num,.ctr{text-align:center}.bold{font-weight:800;color:#fff}.mono{font-family:Consolas,'Vazirmatn',monospace;font-size:12px}
  .pill{display:inline-block;padding:2px 9px;border-radius:99px;font-size:11px;font-weight:800}
  .pill.ok{background:rgba(16,185,129,.16);color:#34d399;border:1px solid rgba(16,185,129,.35)}
  .pill.no{background:rgba(244,63,94,.16);color:#fda4af;border:1px solid rgba(244,63,94,.35)}
  .st{display:inline-block;padding:2px 9px;border-radius:8px;font-size:11px;font-weight:800}
  .st.ok{background:rgba(16,185,129,.2);color:#34d399}.st.warn{background:rgba(245,158,11,.18);color:#fbbf24}
  @media print{body{background:#fff;color:#0f172a}.head,.card{background:#fff;border-color:#cbd5e1}.head h1,.bold{color:#0f172a}th{background:#f1f5f9;color:#0f172a}td{border-color:#e2e8f0}}


/* ---- legacy style block 5 ---- */
:root{--bg:#060b16;--card:#0f172a;--border:#1e293b;--text:#f1f5f9;--head:#162036;--acc:#06b6d4;}
          html[data-theme='light']{--bg:#ffffff;--card:#ffffff;--border:#cbd5e1;--text:#0f172a;--head:#f1f5f9;--acc:#0284c7;}
          body{margin:0;padding:20px;font-family:'Vazirmatn',Tahoma,sans-serif;background:var(--bg);color:var(--text);}
          .top{display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px;}
          h1{margin:0;font-size:17px;color:var(--acc);} .btn{padding:6px 12px;border-radius:8px;border:1px solid var(--border);background:var(--head);color:var(--text);cursor:pointer;font-family:inherit;font-weight:700;font-size:12px;}
          table{width:100%;border-collapse:collapse;background:var(--card);font-size:11px;} th,td{border:1px solid var(--border);padding:7px 8px;text-align:right;} th{background:var(--head);color:var(--acc);font-weight:800;}
          @media print{.no-print{display:none!important;} @page{size:A4 landscape;margin:10mm;}}
