/* ===================== Navira Mini App ===================== */

const CONFIG = {
  // Base URL of the PHP backend (from config.php -> $domainhosts)
  API_BASE: 'https://naviravip.s14.vipbotdomain.top/mirzabot-main/api',
  // Bot username (from config.php -> $usernamebot), used for the "live chat in bot" deep link
  BOT_USERNAME: 'naviravpnbot',
};

const tg = window.Telegram ? window.Telegram.WebApp : null;

const state = {
  token: null,
  userId: null,
  tgUser: null,
  user: null,      // /user_info response
  countries: [],
  categories: [],
  timeRanges: [],
  services: [],
  buy: { country: null, category: null, timeRange: null, service: null, customService: null },
};

/* ---------------------- tiny icon set (feather-style) ---------------------- */
function icon(name, size = 20) {
  const p = 'stroke="currentColor" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';
  const paths = {
    home: `<path d="M3 11l9-8 9 8"/><path d="M5 10v10h14V10"/>`,
    bag: `<path d="M6 8h12l1 12H5L6 8Z"/><path d="M9 8a3 3 0 0 1 6 0"/>`,
    layers: `<path d="M12 3 2 8l10 5 10-5-10-5Z"/><path d="M2 14l10 5 10-5"/>`,
    user: `<circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4 5-6 8-6s6.5 2 8 6"/>`,
    bell: `<path d="M18 8a6 6 0 1 0-12 0c0 7-3 8-3 8h18s-3-1-3-8"/><path d="M10 21a2 2 0 0 0 4 0"/>`,
    history: `<path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 3v6h6"/><path d="M12 8v5l3 2"/>`,
    plus: `<path d="M12 5v14"/><path d="M5 12h14"/>`,
    chevronRight: `<path d="M9 6l6 6-6 6"/>`,
    chevronLeft: `<path d="M15 6l-6 6 6 6"/>`,
    check: `<path d="M20 6 9 17l-5-5"/>`,
    globe: `<circle cx="12" cy="12" r="9"/><path d="M3 12h18"/><path d="M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18Z"/>`,
    clock: `<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>`,
    tag: `<path d="M20 12 12 20l-8-8V4h8l8 8Z"/><circle cx="8" cy="8" r="1"/>`,
    shield: `<path d="M12 3l7 3v6c0 5-3.5 8-7 9-3.5-1-7-4-7-9V6l7-3Z"/>`,
    copy: `<rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/>`,
    refresh: `<path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/>`,
    alert: `<circle cx="12" cy="12" r="9"/><path d="M12 8v5"/><path d="M12 16h.01"/>`,
    wallet: `<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M16 12h.01"/><path d="M3 10h18"/>`,
    wifi: `<path d="M2 8.5a16 16 0 0 1 20 0"/><path d="M5.5 12.5a11 11 0 0 1 13 0"/><path d="M9 16.5a6 6 0 0 1 6 0"/><circle cx="12" cy="20" r="1"/>`,
    box: `<path d="M21 8 12 3 3 8v8l9 5 9-5V8Z"/><path d="M3 8l9 5 9-5"/><path d="M12 13v8"/>`,
    ticket: `<path d="M3 9a2 2 0 1 0 0 6"/><path d="M21 9a2 2 0 1 1 0 6"/><rect x="3" y="6" width="18" height="12" rx="2"/>`,
    users: `<circle cx="9" cy="8" r="3"/><path d="M2 20c1-3.5 3.5-5 7-5s6 1.5 7 5"/><circle cx="17" cy="9" r="2.5"/><path d="M16 14c2.7.2 4.3 1.6 5 6"/>`,
    star: `<path d="M12 2l3 6.5 7 .8-5.2 4.7 1.4 6.9L12 17.7 5.8 21l1.4-6.9L2 9.3l7-.8L12 2Z"/>`,
    empty: `<path d="M21 8v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8"/><path d="M2 8l3-5h14l3 5"/><path d="M2 8h20"/>`,
    headset: `<path d="M4 14v-2a8 8 0 0 1 16 0v2"/><rect x="2" y="14" width="5" height="7" rx="2"/><rect x="17" y="14" width="5" height="7" rx="2"/>`,
    send: `<path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4 20-7Z"/>`,
    question: `<circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 0 1 5 .5c0 1.7-2.5 2-2.5 3.5"/><path d="M12 17h.01"/>`,
    creditcard: `<rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/>`,
  };
  return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" ${p}>${paths[name] || ''}</svg>`;
}

/* ---------------------- theme switcher ---------------------- */
const THEMES = [
  { key: 'orange', color: '#ff7a45' },
  { key: 'green', color: '#22c55e' },
  { key: 'purple', color: '#8b5cf6' },
];
function getTheme() {
  try { return localStorage.getItem('navira_theme') || 'purple'; } catch (e) { return 'purple'; }
}
function applyTheme(key) {
  if (!THEMES.find(t => t.key === key)) key = 'purple';
  if (key === 'purple') {
    document.body.removeAttribute('data-theme');
  } else {
    document.body.setAttribute('data-theme', key);
  }
  try { localStorage.setItem('navira_theme', key); } catch (e) {}
  if (tg?.setHeaderColor) {
    try { tg.setHeaderColor(key === 'purple' ? '#0f0a1a' : '#0f0a1a'); } catch (e) {}
  }
}
function themeSwatches() {
  const active = getTheme();
  return THEMES.map(t => `<div class="theme-dot ${active === t.key ? 'active' : ''}" style="background:${t.color}" onclick="setTheme('${t.key}')" title="${t.key}"></div>`).join('');
}
window.setTheme = function (key) {
  applyTheme(key);
  haptic('light');
  const row = document.getElementById('themeRow');
  if (row) row.innerHTML = themeSwatches();
};
applyTheme(getTheme());

/* ---------------------- helpers ---------------------- */
function toast(msg) {
  const t = document.createElement('div');
  t.className = 'toast';
  t.textContent = msg;
  document.body.appendChild(t);
  setTimeout(() => t.remove(), 2600);
}
function money(n) {
  n = Math.round(Number(n || 0));
  return n.toLocaleString('en-US');
}
function haptic(kind = 'light') {
  try { tg?.HapticFeedback?.impactOccurred(kind); } catch (e) {}
}
function initials(name) {
  if (!name) return 'N';
  return name.trim().charAt(0).toUpperCase();
}

/* ---------------------- API client ---------------------- */
async function apiCall(action, { method = 'GET', params = {}, body = null } = {}) {
  let url = `${CONFIG.API_BASE}/miniapp`;
  const query = new URLSearchParams({ actions: action, user_id: state.userId || '', ...params });
  if (method === 'GET') url += `?${query.toString()}`;

  const res = await fetch(url, {
    method,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${state.token || ''}`,
    },
    body: method === 'POST' ? JSON.stringify({ actions: action, user_id: state.userId, ...body }) : undefined,
  });
  let json;
  try { json = await res.json(); } catch (e) { json = { status: false, msg: 'invalid_response' }; }
  return json;
}

async function verifySession() {
  const initData = tg?.initData || '';
  if (!initData) throw new Error('این صفحه فقط از داخل تلگرام (دکمه مینی‌اپ) قابل بازه، لینک رو مستقیم باز نکن.');
  const res = await fetch(`${CONFIG.API_BASE}/verify`, {
    method: 'POST',
    headers: { 'Content-Type': 'text/plain' },
    body: initData,
  });
  let json;
  try { json = await res.json(); } catch (e) { throw new Error('پاسخ نامعتبر از سرور'); }
  if (!json.status || !json.token) throw new Error(json.msg || 'verify_failed');
  state.token = json.token;
}

/* ---------------------- router ---------------------- */
const routes = {};
function route(path, renderFn) { routes[path] = renderFn; }
function navigate(path) {
  location.hash = path;
}
async function renderRoute() {
  const hash = location.hash.replace('#', '') || '/home';
  const [path] = hash.split('?');
  const fn = routes[path] || routes['/home'];
  const app = document.getElementById('app');
  try {
    await fn(app);
  } catch (e) {
    console.error(e);
    app.innerHTML = errorScreen(e.message);
  }
  window.scrollTo(0, 0);
}
window.addEventListener('hashchange', renderRoute);

function errorScreen(msg) {
  return `<div class="empty" style="padding-top:90px">
    <div class="ic">${icon('alert', 28)}</div>
    <b>مشکلی پیش اومد</b>
    <p>${msg || 'اتصال به سرور برقرار نشد.'}</p>
    <button class="btn btn-primary" onclick="location.reload()">${icon('refresh',16)} تلاش دوباره</button>
  </div>`;
}

/* ---------------------- bottom nav ---------------------- */
function bottomNav(active) {
  const items = [
    { key: 'home', path: '/home', label: 'خانه', icon: 'home' },
    { key: 'services', path: '/services', label: 'سرویس‌ها', icon: 'layers' },
    { key: 'buy', path: '/buy/country', label: 'خرید', icon: 'bag' },
    { key: 'account', path: '/account', label: 'حساب', icon: 'user' },
  ];
  return `<div class="bottomnav">
    ${items.map(it => `
      <div class="navitem ${active === it.key ? 'active' : ''}" onclick="navigate('${it.path}')">
        <div class="navcirc">${icon(it.icon, 20)}</div>
        <span>${it.label}</span>
      </div>`).join('')}
  </div>`;
}

function pageHeader(title, backPath) {
  return `<div class="pageheader">
    <div class="back-btn" onclick="${backPath ? `navigate('${backPath}')` : 'history.back()'}">${icon('chevronRight', 18)}</div>
    <h2>${title}</h2>
  </div>`;
}

/* ---------------------- HOME ---------------------- */
route('/home', async (app) => {
  app.innerHTML = `
    <div class="topbar">
      <div class="hello">
        <div class="eyebrow">✨ خوش اومدی</div>
        <div class="name">${state.tgUser?.first_name || 'کاربر ناویرا'}</div>
      </div>
      <div class="topbar-actions">
        <div class="icon-btn" onclick="location.reload()">${icon('bell',18)}<span class="dot-badge"></span></div>
        <div class="avatar">${initials(state.tgUser?.first_name)}</div>
      </div>
    </div>
    <div class="page">
      <div class="theme-row">
        <div class="theme-row-label">تم اپلیکیشن:</div>
        <div class="theme-dots" id="themeRow">${themeSwatches()}</div>
      </div>
      <div class="wallet-card">
        <div class="wallet-top"><span class="live"></span> موجودی کیف پول</div>
        <div class="wallet-amount"><b id="walletBalance">···</b><span>تومان</span></div>
        <div class="wallet-actions">
          <button class="btn btn-ghost" onclick="navigate('/services')">${icon('history',15)} تاریخچه</button>
          <button class="btn btn-solid" onclick="toast('برای شارژ کیف‌پول به ربات تلگرام مراجعه کن')">${icon('plus',15)} شارژ کیف پول</button>
        </div>
      </div>

      <div class="quick-grid">
        <div class="quick-item" onclick="navigate('/account')"><div class="ic">${icon('user',18)}</div><span>حساب کاربری</span></div>
        <div class="quick-item" onclick="navigate('/support')"><div class="ic">${icon('shield',18)}</div><span>پشتیبانی</span></div>
        <div class="quick-item" onclick="navigate('/services')"><div class="ic">${icon('layers',18)}</div><span>سرویس‌های من</span></div>
        <div class="quick-item" onclick="navigate('/buy/country')"><div class="ic">${icon('bag',18)}</div><span>خرید سرویس</span></div>
      </div>

      <div class="section-title">
        <h3>سرویس‌های فعال</h3>
        <span class="link" onclick="navigate('/services')">مشاهده همه</span>
      </div>
      <div id="homeServices">${skeletonList(2)}</div>
    </div>
    ${bottomNav('home')}
  `;

  try {
    const info = await apiCall('user_info');
    if (info.status) {
      state.user = info.obj;
      document.getElementById('walletBalance').textContent = money(info.obj.balance);
    }
  } catch (e) { /* keep placeholder */ }

  try {
    const list = await apiCall('invoices', { params: { limit: 3, page: 1 } });
    const box = document.getElementById('homeServices');
    if (list.status && list.obj?.length) {
      box.innerHTML = list.obj.map(serviceCard).join('');
    } else {
      box.innerHTML = emptyState('box', 'هنوز سرویسی نداری', 'اولین سرویست رو همین الان بخر و وصل شو.', 'خرید سرویس', "navigate('/buy/country')");
    }
  } catch (e) {
    document.getElementById('homeServices').innerHTML = emptyState('alert', 'خطا در دریافت سرویس‌ها', 'اتصال برقرار نشد، دوباره تلاش کن.');
  }
});

function skeletonList(n) {
  return Array.from({ length: n }).map(() => `<div class="skel" style="height:74px;margin-bottom:10px;"></div>`).join('');
}
function emptyState(ic, title, desc, btnLabel, onclick) {
  return `<div class="empty">
    <div class="ic">${icon(ic, 26)}</div>
    <b>${title}</b>
    <p>${desc}</p>
    ${btnLabel ? `<button class="btn btn-primary" onclick="${onclick}">${btnLabel}</button>` : ''}
  </div>`;
}

const statusMap = {
  active: { label: 'آنلاین', cls: 'pill-on', ic: 'on' },
  end_of_time: { label: 'منقضی', cls: 'pill-off' },
  end_of_volume: { label: 'اتمام حجم', cls: 'pill-off' },
  sendedwarn: { label: 'رو به اتمام', cls: 'pill-warn' },
  send_on_hold: { label: 'در انتظار', cls: 'pill-warn' },
  Unsuccessful: { label: 'نامشخص', cls: 'pill-off' },
};
function serviceCard(s) {
  const st = statusMap[s.status] || { label: s.status || 'نامشخص', cls: 'pill-off' };
  const isOn = st.cls === 'pill-on';
  return `<div class="svc-card" onclick="toast('برای مدیریت این سرویس به ربات تلگرام مراجعه کن')">
    <div class="svc-ic ${isOn ? '' : 'off'}">${icon('wifi', 19)}</div>
    <div class="svc-body">
      <div class="svc-head-row">
        <div class="svc-name">${s.note || s.username}</div>
        <div class="pill ${st.cls}">${st.label}</div>
      </div>
      <div class="svc-meta">${icon('clock',12)} انقضا: ${s.expire || '-'} <span>·</span> ${icon('tag',12)} ${s.username}</div>
    </div>
  </div>`;
}

/* ---------------------- SERVICES (my services / invoices) ---------------------- */
route('/services', async (app) => {
  app.innerHTML = `
    ${pageHeader('سرویس‌های من', '/home')}
    <div class="page">
      <input type="text" id="svcSearch" placeholder="جستجوی نام کاربری سرویس…" />
      <div id="svcList" style="margin-top:14px">${skeletonList(4)}</div>
    </div>
    ${bottomNav('services')}
  `;
  const load = async (q) => {
    const box = document.getElementById('svcList');
    box.innerHTML = skeletonList(4);
    try {
      const res = await apiCall('invoices', { params: { limit: 10, page: 1, q: q || '' } });
      if (res.status && res.obj?.length) {
        box.innerHTML = res.obj.map(serviceCard).join('');
      } else {
        box.innerHTML = emptyState('box', 'سرویسی پیدا نشد', 'با فیلتر دیگه‌ای امتحان کن یا یه سرویس جدید بخر.', 'خرید سرویس', "navigate('/buy/country')");
      }
    } catch (e) {
      box.innerHTML = emptyState('alert', 'خطا در دریافت لیست', 'اتصال به سرور برقرار نشد.');
    }
  };
  let t;
  document.getElementById('svcSearch').addEventListener('input', (e) => {
    clearTimeout(t);
    t = setTimeout(() => load(e.target.value), 350);
  });
  load();
});

/* ---------------------- ACCOUNT ---------------------- */
route('/account', async (app) => {
  app.innerHTML = `
    ${pageHeader('حساب کاربری', '/home')}
    <div class="page">
      <div class="profile-card">
        <div class="profile-avatar">${initials(state.tgUser?.first_name)}</div>
        <div style="font-size:15px;font-weight:700">${state.tgUser?.first_name || ''} ${state.tgUser?.last_name || ''}</div>
        <div style="font-size:12px;color:var(--muted)">آیدی عددی: ${state.userId}</div>
        <div class="stat-grid" id="acctStats">${skeletonList(2)}</div>
      </div>

      <div class="section-title"><h3>اطلاعات حساب</h3></div>
      <div class="summary-card" id="acctInfo">${skeletonList(1)}</div>

      <div class="section-title"><h3>کد دعوت شما</h3></div>
      <div class="copy-row">
        <code id="inviteCode">···</code>
        <div class="icon-btn" onclick="copyInvite()">${icon('copy',16)}</div>
      </div>
    </div>
    ${bottomNav('account')}
  `;
  try {
    const res = await apiCall('user_info');
    if (res.status) {
      const o = res.obj;
      state.user = o;
      document.getElementById('acctStats').innerHTML = `
        <div class="stat-card"><b>${o.count_order ?? 0}</b><span>سرویس فعال</span></div>
        <div class="stat-card"><b>${o.count_payment ?? 0}</b><span>پرداخت موفق</span></div>
      `;
      document.getElementById('acctInfo').innerHTML = `
        <div class="summary-row"><span class="k">شماره تماس</span><span class="v">${o.phone || '—'}</span></div>
        <div class="summary-row"><span class="k">نوع حساب</span><span class="v">${o.group_type || '—'}</span></div>
        <div class="summary-row"><span class="k">تاریخ عضویت</span><span class="v">${o.time_join || '—'}</span></div>
        <div class="summary-row"><span class="k">تعداد زیرمجموعه</span><span class="v">${o.affiliatescount ?? 0}</span></div>
        <div class="summary-row total"><span class="k">موجودی کیف پول</span><span class="v">${money(o.balance)} تومان</span></div>
      `;
      document.getElementById('inviteCode').textContent = o.codeInvitation || '—';
    }
  } catch (e) {
    document.getElementById('acctInfo').innerHTML = emptyState('alert', 'خطا در دریافت اطلاعات', 'اتصال به سرور برقرار نشد.');
  }
});
window.copyInvite = function () {
  const code = document.getElementById('inviteCode').textContent;
  navigator.clipboard?.writeText(code).then(() => toast('کد دعوت کپی شد ✅'));
};

/* ---------------------- SUPPORT ---------------------- */
route('/support', async (app) => {
  app.innerHTML = `
    ${pageHeader('پشتیبانی', '/home')}
    <div class="page">
      <div class="support-card" onclick="navigate('/support/new')">
        <div class="ic">${icon('headset',20)}</div>
        <div class="body"><b>ارسال تیکت جدید</b><span>پیام مستقیم به تیم پشتیبانی</span></div>
        ${icon('chevronLeft',16)}
      </div>
      <div class="support-card" onclick="navigate('/support/tickets')">
        <div class="ic">${icon('ticket',20)}</div>
        <div class="body"><b>تیکت‌های من</b><span>پیگیری وضعیت پیام‌های قبلی</span></div>
        ${icon('chevronLeft',16)}
      </div>
      <div class="support-card" onclick="navigate('/support/faq')">
        <div class="ic">${icon('question',20)}</div>
        <div class="body"><b>سوالات متداول</b><span>پاسخ سوالات پرتکرار</span></div>
        ${icon('chevronLeft',16)}
      </div>
      <div class="support-card" onclick="openBotChat()">
        <div class="ic">${icon('send',20)}</div>
        <div class="body"><b>گفتگوی آنلاین در ربات</b><span>باز کردن چت مستقیم ربات</span></div>
        ${icon('chevronLeft',16)}
      </div>
    </div>
    ${bottomNav('home')}
  `;
});
window.openBotChat = function () {
  const url = `https://t.me/${CONFIG.BOT_USERNAME}`;
  if (tg?.openTelegramLink) {
    tg.openTelegramLink(url);
  } else {
    window.open(url, '_blank');
  }
};

/* -------- new ticket: department pick + message -------- */
route('/support/new', async (app) => {
  app.innerHTML = `
    ${pageHeader('ارسال تیکت جدید', '/support')}
    <div class="page">
      <div class="field-label">دپارتمان موردنظر رو انتخاب کن</div>
      <div id="deptList">${skeletonList(3)}</div>
    </div>
    ${bottomNav('home')}
  `;
  try {
    const res = await apiCall('support_departments');
    const box = document.getElementById('deptList');
    if (res.status && res.obj?.length) {
      box.innerHTML = res.obj.map(d => `
        <div class="opt-card" onclick="selectDept(${d.id}, '${(d.name_departman || '').replace(/'/g, "\\'")}')">
          <div class="opt-ic">${icon('users',18)}</div>
          <div class="opt-body"><div class="opt-title">${d.name_departman}</div></div>
          ${icon('chevronLeft',15)}
        </div>`).join('');
    } else {
      box.innerHTML = emptyState('alert', 'دپارتمانی یافت نشد', 'لطفاً بعداً دوباره تلاش کن.');
    }
  } catch (e) {
    document.getElementById('deptList').innerHTML = emptyState('alert', 'خطا در دریافت لیست', 'اتصال به سرور برقرار نشد.');
  }
});
window.selectDept = function (id, name) {
  state.supportDept = { id, name };
  navigate('/support/new/message');
};

route('/support/new/message', async (app) => {
  if (!state.supportDept) return navigate('/support/new');
  app.innerHTML = `
    ${pageHeader('متن پیام', '/support/new')}
    <div class="page">
      <div class="summary-card">
        <div class="summary-row"><span class="k">دپارتمان</span><span class="v">${state.supportDept.name}</span></div>
      </div>
      <div class="field-label">پیامت رو بنویس</div>
      <textarea id="ticketText" rows="6" placeholder="مشکلت رو با جزئیات توضیح بده…" style="width:100%; background:var(--surface); border:1px solid var(--border); border-radius:14px; padding:13px 14px; color:var(--text); font-family:inherit; font-size:13.5px; outline:none; resize:vertical;"></textarea>
      <button class="btn btn-primary btn-lg btn-block" style="margin-top:16px" id="sendTicketBtn" onclick="sendTicket()">${icon('send',16)} ارسال تیکت</button>
    </div>
    ${bottomNav('home')}
  `;
});
window.sendTicket = async function () {
  const text = (document.getElementById('ticketText')?.value || '').trim();
  if (!text) { toast('لطفاً متن پیام رو وارد کن'); return; }
  const btn = document.getElementById('sendTicketBtn');
  btn.disabled = true;
  btn.textContent = 'در حال ارسال…';
  try {
    const res = await apiCall('support_ticket_send', { method: 'POST', body: { department_id: state.supportDept.id, text } });
    if (res.status) {
      haptic('medium');
      toast('تیکت با موفقیت ارسال شد ✅');
      state.supportDept = null;
      navigate('/support/tickets');
    } else {
      toast(res.msg || 'ارسال تیکت ناموفق بود');
      btn.disabled = false;
      btn.innerHTML = `${icon('send',16)} ارسال تیکت`;
    }
  } catch (e) {
    toast('خطا در ارتباط با سرور');
    btn.disabled = false;
    btn.innerHTML = `${icon('send',16)} ارسال تیکت`;
  }
};

/* -------- my tickets -------- */
const ticketStatusMap = {
  Answered: { label: 'پاسخ داده شد', cls: 'pill-on' },
  Pending: { label: 'در حال بررسی', cls: 'pill-warn' },
  Unseen: { label: 'در انتظار بررسی', cls: 'pill-warn' },
  Customerresponse: { label: 'پاسخ شما ثبت شد', cls: 'pill-warn' },
  close: { label: 'بسته شده', cls: 'pill-off' },
};
route('/support/tickets', async (app) => {
  app.innerHTML = `
    ${pageHeader('تیکت‌های من', '/support')}
    <div class="page">
      <div id="ticketList">${skeletonList(3)}</div>
    </div>
    ${bottomNav('home')}
  `;
  try {
    const res = await apiCall('support_tickets', { params: { limit: 30, page: 1 } });
    const box = document.getElementById('ticketList');
    if (res.status && res.obj?.length) {
      box.innerHTML = res.obj.map(t => {
        const st = ticketStatusMap[t.status] || { label: t.status, cls: 'pill-off' };
        return `<div class="summary-card">
          <div class="summary-row"><span class="k">دپارتمان</span><span class="v">${t.name_departman}</span></div>
          <div class="summary-row"><span class="k">وضعیت</span><span class="v"><span class="pill ${st.cls}">${st.label}</span></span></div>
          <div class="summary-row"><span class="k">تاریخ</span><span class="v">${t.time || '-'}</span></div>
          <div style="margin-top:10px; font-size:12.5px; color:var(--text-dim); line-height:1.7;">${t.text}</div>
          ${t.result ? `<div style="margin-top:10px; padding-top:10px; border-top:1px solid var(--border-soft); font-size:12.5px; color:var(--success);"><b>پاسخ پشتیبانی:</b><div style="margin-top:4px; color:var(--text-dim);">${t.result}</div></div>` : ''}
        </div>`;
      }).join('');
    } else {
      box.innerHTML = emptyState('ticket', 'هنوز تیکتی نداری', 'اگه سوالی داری، یه تیکت جدید بفرست.', 'ارسال تیکت جدید', "navigate('/support/new')");
    }
  } catch (e) {
    document.getElementById('ticketList').innerHTML = emptyState('alert', 'خطا در دریافت تیکت‌ها', 'اتصال به سرور برقرار نشد.');
  }
});

/* -------- FAQ -------- */
route('/support/faq', async (app) => {
  app.innerHTML = `
    ${pageHeader('سوالات متداول', '/support')}
    <div class="page">
      <div id="faqList">${skeletonList(4)}</div>
    </div>
    ${bottomNav('home')}
  `;
  try {
    const res = await apiCall('faq_list');
    const box = document.getElementById('faqList');
    if (res.status && res.obj?.length) {
      box.innerHTML = res.obj.map((f, i) => `
        <div class="summary-card" style="cursor:pointer" onclick="toggleFaq(${i})">
          <div style="display:flex; align-items:center; justify-content:space-between; gap:10px;">
            <b style="font-size:13px;">${f.name_os}</b>
            <span id="faqChevron${i}">${icon('chevronLeft',14)}</span>
          </div>
          <div id="faqBody${i}" class="hidden" style="margin-top:10px; font-size:12.5px; color:var(--text-dim); line-height:1.8; border-top:1px solid var(--border-soft); padding-top:10px;">${f.Description_os}</div>
        </div>`).join('');
    } else {
      box.innerHTML = emptyState('question', 'سوالی ثبت نشده', 'فعلاً سوال متداولی ثبت نشده.');
    }
  } catch (e) {
    document.getElementById('faqList').innerHTML = emptyState('alert', 'خطا در دریافت سوالات', 'اتصال به سرور برقرار نشد.');
  }
});
window.toggleFaq = function (i) {
  document.getElementById(`faqBody${i}`)?.classList.toggle('hidden');
};

/* ---------------------- BUY WIZARD ---------------------- */
const WIZARD_STEPS = [
  { key: 'country', label: 'کشور' },
  { key: 'category', label: 'دسته‌بندی' },
  { key: 'time', label: 'مدت زمان' },
  { key: 'service', label: 'سرویس' },
  { key: 'confirm', label: 'تأیید' },
];
function stepper(activeKey) {
  const idx = WIZARD_STEPS.findIndex(s => s.key === activeKey);
  return `<div class="stepper">${WIZARD_STEPS.map((s, i) => `
    ${i > 0 ? '<div class="step-line"></div>' : ''}
    <div class="step ${i < idx ? 'done' : ''} ${i === idx ? 'active' : ''}">
      <div class="circ">${i < idx ? icon('check', 12) : i + 1}</div>
      <span>${s.label}</span>
    </div>`).reverse().join('')}</div>`;
  // reversed for RTL visual order (right-to-left progression)
}

route('/buy/country', async (app) => {
  app.innerHTML = `
    ${pageHeader('انتخاب کشور', '/home')}
    ${stepper('country')}
    <div class="page" id="countryList">${skeletonList(4)}</div>
    ${bottomNav('buy')}
  `;
  try {
    const res = await apiCall('countries');
    const box = document.getElementById('countryList');
    if (res.status && res.obj?.length) {
      box.innerHTML = res.obj.map(c => `
        <div class="opt-card" onclick='selectCountry(${JSON.stringify(c)})'>
          <div class="opt-ic">${icon('globe', 18)}</div>
          <div class="opt-body">
            <div class="opt-title">${c.name}</div>
            <div class="opt-sub">${c.is_custom ? 'حجم سفارشی فعال' : 'بسته‌های آماده'}</div>
          </div>
          <div class="opt-check"></div>
        </div>`).join('');
    } else {
      box.innerHTML = emptyState('globe', 'کشوری موجود نیست', 'در حال حاضر سرویسی برای فروش تعریف نشده.');
    }
  } catch (e) {
    document.getElementById('countryList').innerHTML = emptyState('alert', 'خطا', 'اتصال به سرور برقرار نشد.');
  }
});
window.selectCountry = function (c) {
  state.buy = { country: c, category: null, timeRange: null, service: null, customService: null };
  haptic();
  navigate('/buy/category');
};

route('/buy/category', async (app) => {
  if (!state.buy.country) return navigate('/buy/country');
  app.innerHTML = `
    ${pageHeader('انتخاب دسته‌بندی', '/buy/country')}
    ${stepper('category')}
    <div class="page" id="catList">${skeletonList(3)}</div>
    ${bottomNav('buy')}
  `;
  try {
    const res = await apiCall('categories', { params: { country_id: state.buy.country.id } });
    const box = document.getElementById('catList');
    const items = res.obj || [];
    if (res.status && items.length) {
      box.innerHTML = items.map(c => `
        <div class="opt-card" onclick='selectCategory(${JSON.stringify(c)})'>
          <div class="opt-ic">${icon('tag', 18)}</div>
          <div class="opt-body"><div class="opt-title">${c.name}</div></div>
          <div class="opt-check"></div>
        </div>`).join('') + `
        <div class="opt-card" onclick="selectCategory(null)">
          <div class="opt-ic">${icon('layers', 18)}</div>
          <div class="opt-body"><div class="opt-title">بدون دسته‌بندی / همه</div></div>
          <div class="opt-check"></div>
        </div>`;
    } else {
      // no categories defined -> skip straight ahead
      selectCategory(null);
    }
  } catch (e) {
    document.getElementById('catList').innerHTML = emptyState('alert', 'خطا', 'اتصال به سرور برقرار نشد.');
  }
});
window.selectCategory = function (c) {
  state.buy.category = c;
  haptic();
  navigate('/buy/time');
};

route('/buy/time', async (app) => {
  if (!state.buy.country) return navigate('/buy/country');
  app.innerHTML = `
    ${pageHeader('انتخاب مدت زمان', '/buy/category')}
    ${stepper('time')}
    <div class="page" id="timeList">${skeletonList(3)}</div>
    ${bottomNav('buy')}
  `;
  try {
    const res = await apiCall('time_ranges', { params: { country_id: state.buy.country.id } });
    const box = document.getElementById('timeList');
    const items = res.obj || [];
    if (res.status && items.length) {
      box.innerHTML = `<div class="chip-row">` + items.map((t, i) => `
        <div class="chip" data-i="${i}" onclick='selectTime(${JSON.stringify(t)}, this)'>${t.name}</div>`).join('') + `</div>
        <div class="opt-card" style="margin-top:14px" onclick="selectTime(null, null)">
          <div class="opt-ic">${icon('clock', 18)}</div>
          <div class="opt-body"><div class="opt-title">همه مدت‌ها را نشون بده</div></div>
          <div class="opt-check"></div>
        </div>`;
    } else {
      selectTime(null, null);
    }
  } catch (e) {
    document.getElementById('timeList').innerHTML = emptyState('alert', 'خطا', 'اتصال به سرور برقرار نشد.');
  }
});
window.selectTime = function (t, el) {
  state.buy.timeRange = t;
  if (el) {
    document.querySelectorAll('.chip').forEach(c => c.classList.remove('active'));
    el.classList.add('active');
    setTimeout(() => navigate('/buy/service'), 180);
  } else {
    navigate('/buy/service');
  }
  haptic();
};

route('/buy/service', async (app) => {
  if (!state.buy.country) return navigate('/buy/country');
  app.innerHTML = `
    ${pageHeader('انتخاب سرویس', '/buy/time')}
    ${stepper('service')}
    <div class="page" id="svcSelList">${skeletonList(3)}</div>
    ${bottomNav('buy')}
  `;
  const isCustom = !!state.buy.country.is_custom;
  try {
    const res = await apiCall('services', {
      params: {
        country_id: state.buy.country.id,
        category_id: state.buy.category?.id || 0,
        time_range_day: state.buy.timeRange?.day || 0,
      },
    });
    const box = document.getElementById('svcSelList');
    const items = res.obj || [];
    let html = '';
    if (res.status && items.length) {
      html += `<div class="section-title" style="margin-top:0"><h3>سرویس‌های آماده</h3></div>`;
      html += items.map(p => `
        <div class="opt-card" onclick='selectService(${JSON.stringify(p)})'>
          <div class="opt-ic">${icon('box', 18)}</div>
          <div class="opt-body">
            <div class="opt-title">${p.name}</div>
            <div class="opt-sub">${p.traffic_gb == 0 ? 'حجم نامحدود' : p.traffic_gb + ' گیگابایت'} · ${p.time_days == 0 ? 'زمان نامحدود' : p.time_days + ' روز'}</div>
          </div>
          <div class="opt-price">${money(p.price)} ت</div>
        </div>`).join('');
    } else if (!isCustom) {
      html += emptyState('box', 'سرویسی موجود نیست', 'با فیلترهای دیگه امتحان کن.', 'شروع دوباره', "navigate('/buy/country')");
    }
    if (isCustom) {
      html += customServiceCard();
    }
    box.innerHTML = html;
    if (isCustom) initCustomService();
  } catch (e) {
    document.getElementById('svcSelList').innerHTML = emptyState('alert', 'خطا', 'اتصال به سرور برقرار نشد.');
  }
});
window.selectService = function (p) {
  state.buy.service = p;
  state.buy.customService = null;
  haptic();
  navigate('/buy/confirm');
};

/* ---------------------- custom (سرویس دلخواه) service ---------------------- */
const CUSTOM_DEFAULTS = { traffic: 50, time: 30 };
function customServiceCard() {
  return `
    <div class="section-title"><h3>سرویس دلخواه</h3></div>
    <div class="custom-card">
      <div class="custom-row">
        <div class="custom-label"><span>حجم ترافیک:</span><b id="customTrafficVal">${CUSTOM_DEFAULTS.traffic}</b><span>گیگابایت</span></div>
        <input type="range" id="customTrafficSlider" min="1" max="1000" step="1" value="${CUSTOM_DEFAULTS.traffic}" />
      </div>
      <div class="custom-row">
        <div class="custom-label"><span>مدت زمان:</span><b id="customTimeVal">${CUSTOM_DEFAULTS.time}</b><span>روز</span></div>
        <input type="range" id="customTimeSlider" min="1" max="365" step="1" value="${CUSTOM_DEFAULTS.time}" />
      </div>
      <div class="custom-price-row">
        <span>قیمت</span>
        <b id="customPriceVal">···</b>
      </div>
      <button class="btn btn-primary btn-block" id="customSelectBtn" disabled onclick="selectCustomService()">${icon('box', 16)} انتخاب سرویس دلخواه</button>
    </div>
  `;
}
let customPriceTimer = null;
function initCustomService() {
  const tSlider = document.getElementById('customTrafficSlider');
  const dSlider = document.getElementById('customTimeSlider');
  if (!tSlider || !dSlider) return;
  const onChange = () => {
    document.getElementById('customTrafficVal').textContent = tSlider.value;
    document.getElementById('customTimeVal').textContent = dSlider.value;
    document.getElementById('customPriceVal').textContent = '···';
    document.getElementById('customSelectBtn').disabled = true;
    clearTimeout(customPriceTimer);
    customPriceTimer = setTimeout(fetchCustomPrice, 500);
  };
  tSlider.addEventListener('input', onChange);
  dSlider.addEventListener('input', onChange);
  fetchCustomPrice();
}
async function fetchCustomPrice() {
  const tSlider = document.getElementById('customTrafficSlider');
  const dSlider = document.getElementById('customTimeSlider');
  const priceEl = document.getElementById('customPriceVal');
  const btn = document.getElementById('customSelectBtn');
  if (!tSlider || !dSlider) return;
  const traffic_gb = Number(tSlider.value);
  const time_days = Number(dSlider.value);
  try {
    const res = await apiCall('custom_price', {
      params: {
        country_id: state.buy.country.id,
        category_id: state.buy.category?.id || 0,
        traffic_gb,
        time_days,
      },
    });
    const o = res.obj;
    if (res.status && o && o.price != null) {
      if (o.traffic_min != null) tSlider.min = o.traffic_min;
      if (o.traffic_max != null) tSlider.max = o.traffic_max;
      if (o.time_min != null) dSlider.min = o.time_min;
      if (o.time_max != null) dSlider.max = o.time_max;
      state.buy.customPrice = o.price;
      priceEl.textContent = money(o.price) + ' تومان';
      btn.disabled = false;
    } else {
      priceEl.textContent = 'محاسبه نشد';
      btn.disabled = true;
    }
  } catch (e) {
    priceEl.textContent = 'خطا در محاسبه قیمت';
    btn.disabled = true;
  }
}
window.selectCustomService = function () {
  const tSlider = document.getElementById('customTrafficSlider');
  const dSlider = document.getElementById('customTimeSlider');
  state.buy.service = null;
  state.buy.customService = {
    traffic_gb: Number(tSlider.value),
    time_days: Number(dSlider.value),
    price: state.buy.customPrice,
  };
  haptic();
  navigate('/buy/confirm');
};

route('/buy/confirm', async (app) => {
  const b = state.buy;
  if (!b.service && !b.customService) return navigate('/buy/country');
  if (!state.user) {
    try {
      const info = await apiCall('user_info');
      if (info.status) state.user = info.obj;
    } catch (e) { /* keep going, balance falls back to 0 below */ }
  }
  if (!b.phase) b.phase = 'method';
  if (!b.paymentMethod) b.paymentMethod = 'wallet';
  if (b.phase === 'details') return renderPurchaseDetails(app);
  return renderPaymentMethod(app);
});

/* -------- phase 1: choose payment method -------- */
function renderPaymentMethod(app) {
  const b = state.buy;
  const balance = state.user?.balance ?? 0;
  app.innerHTML = `
    ${pageHeader('روش پرداخت', '/buy/service')}
    ${stepper('confirm')}
    <div class="page">
      <div class="opt-card selected">
        <div class="opt-ic">${icon('creditcard',18)}</div>
        <div class="opt-body">
          <div class="opt-title">کیف پول ناویرا</div>
          <div class="opt-sub">موجودی فعلی: ${money(balance)} تومان</div>
        </div>
        <div class="opt-check"></div>
      </div>
      <div class="opt-card" style="opacity:.5; pointer-events:none;">
        <div class="opt-ic">${icon('creditcard',18)}</div>
        <div class="opt-body">
          <div class="opt-title">درگاه پرداخت آنلاین</div>
          <div class="opt-sub">غیرفعال است</div>
        </div>
        <div class="opt-check"></div>
      </div>
      <div class="opt-card" style="opacity:.5; pointer-events:none;">
        <div class="opt-ic">${icon('wallet',18)}</div>
        <div class="opt-body">
          <div class="opt-title">پرداخت با کریپتو</div>
          <div class="opt-sub">غیرفعال است</div>
        </div>
        <div class="opt-check"></div>
      </div>
      <button class="btn btn-primary btn-lg btn-block" style="margin-top:18px" onclick="buyGoToDetails()">${icon('chevronLeft',16)} ادامه</button>
    </div>
    ${bottomNav('buy')}
  `;
}
window.buyGoToDetails = function () {
  state.buy.phase = 'details';
  renderPurchaseDetails(document.getElementById('app'));
  window.scrollTo(0, 0);
};
window.buyBackToMethod = function () {
  state.buy.phase = 'method';
  renderPaymentMethod(document.getElementById('app'));
  window.scrollTo(0, 0);
};

/* -------- phase 2: order summary + discount code + config fields -------- */
function renderPurchaseDetails(app) {
  const b = state.buy;
  const price = b.service ? b.service.price : b.customService.price;
  const serviceName = b.service ? b.service.name : 'سرویس دلخواه';
  const trafficLabel = b.service
    ? (b.service.traffic_gb == 0 ? 'نامحدود' : b.service.traffic_gb + ' گیگ')
    : (b.customService.traffic_gb + ' گیگ');
  const timeLabel = b.service
    ? (b.service.time_days == 0 ? 'نامحدود' : b.service.time_days + ' روز')
    : (b.customService.time_days + ' روز');
  const balance = state.user?.balance ?? 0;
  const payable = b.discount ? b.discount.final_price : price;
  const enough = Number(balance) >= Number(payable);
  const needsUsername = !!b.country.is_username;
  const needsNote = !!b.country.is_note;
  app.innerHTML = `
    ${pageHeader('تأیید خرید', null)}
    ${stepper('confirm')}
    <div class="page">
      <div class="summary-card">
        <div class="summary-row"><span class="k">سرویس</span><span class="v">${serviceName}</span></div>
        <div class="summary-row"><span class="k">کشور</span><span class="v">${b.country.name}</span></div>
        <div class="summary-row"><span class="k">حجم</span><span class="v">${trafficLabel}</span></div>
        <div class="summary-row"><span class="k">مدت زمان</span><span class="v">${timeLabel}</span></div>
        <div class="summary-row"><span class="k">موجودی فعلی</span><span class="v">${money(balance)} ت</span></div>
        ${b.discount ? `<div class="summary-row"><span class="k">تخفیف (${b.discount.percent}%)</span><span class="v" style="color:var(--success)">−${money(b.discount.discount_amount)} ت</span></div>` : ''}
        <div class="summary-row total"><span class="k">مبلغ قابل پرداخت</span><span class="v">${money(payable)} ت</span></div>
      </div>

      <div class="section-title"><h3>کد تخفیف</h3></div>
      <div class="summary-card" style="display:flex; align-items:center; gap:8px; padding:12px;">
        <input type="text" id="discountCodeInput" placeholder="کد تخفیف را وارد کن…" value="${b.discount ? b.discount.code : ''}" ${b.discount ? 'disabled' : ''} style="flex:1; margin:0;" />
        ${b.discount
          ? `<div class="icon-btn" onclick="removeDiscountCode()" style="flex-shrink:0;">${icon('alert',15)}</div>`
          : `<button class="btn btn-primary" id="applyDiscountBtn" onclick="applyDiscountCode()" style="flex-shrink:0;">اعمال %</button>`}
      </div>
      <div id="discountMsg" style="font-size:11.5px; margin:-6px 4px 14px; min-height:14px;"></div>

      ${needsUsername || needsNote ? `
      <div class="section-title"><h3>مشخصات کانفیگ</h3></div>
      <div class="summary-card">
        ${needsUsername ? `
        <div class="field-label">نام کاربری / نام کانفیگ <span style="color:var(--danger)">*</span></div>
        <input type="text" id="customUsername" placeholder="مثلاً: navira24" oninput="clearUsernameErr()" style="margin-bottom:4px;" />
        <div id="usernameErr" style="color:var(--danger); font-size:11.5px; margin:4px 2px 14px; display:none;"></div>
        ` : ''}
        ${needsNote ? `
        <div class="field-label" style="margin-top:${needsUsername ? '14px' : '0'}">یادداشت (اختیاری)</div>
        <input type="text" id="customNote" placeholder="یادداشت دلخواه…" />
        ` : ''}
      </div>` : ''}
      ${!enough ? `<div class="empty" style="padding-top:6px"><div class="ic">${icon('wallet',22)}</div><b>موجودی کافی نیست</b><p>برای این خرید باید کیف پولت رو شارژ کنی.</p></div>` : ''}
      <div class="confirm-actions">
        <button class="btn btn-outline" style="flex:1" onclick="buyBackToMethod()">بازگشت</button>
        <button class="btn btn-primary btn-lg" style="flex:2" id="confirmBtn" ${!enough ? 'disabled' : ''} onclick="doPurchase()">${icon('check',16)} تکمیل خرید</button>
      </div>
    </div>
    ${bottomNav('buy')}
  `;
}
window.clearUsernameErr = function () {
  const el = document.getElementById('customUsername');
  const err = document.getElementById('usernameErr');
  if (el) el.classList.remove('input-error');
  if (err) err.style.display = 'none';
};
window.applyDiscountCode = async function () {
  const b = state.buy;
  const code = (document.getElementById('discountCodeInput')?.value || '').trim();
  const msgBox = document.getElementById('discountMsg');
  if (!code) { toast('کد تخفیف رو وارد کن'); return; }
  const btn = document.getElementById('applyDiscountBtn');
  btn.disabled = true;
  btn.textContent = 'بررسی…';
  try {
    const body = b.service
      ? { discount_code: code, service_id: b.service.id, country_id: b.country.id }
      : { discount_code: code, country_id: b.country.id, custom_service: { traffic_gb: b.customService.traffic_gb, time_days: b.customService.time_days } };
    const res = await apiCall('apply_discount', { method: 'POST', body });
    if (res.status) {
      b.discount = { code, percent: res.obj.percent, discount_amount: res.obj.discount_amount, final_price: res.obj.final_price };
      haptic('medium');
      renderPurchaseDetails(document.getElementById('app'));
      toast(`کد تخفیف اعمال شد (${res.obj.percent}%) ✅`);
    } else {
      if (msgBox) { msgBox.textContent = res.msg || 'کد تخفیف نامعتبر است'; msgBox.style.color = 'var(--danger)'; }
      btn.disabled = false;
      btn.textContent = 'اعمال %';
    }
  } catch (e) {
    if (msgBox) { msgBox.textContent = 'خطا در ارتباط با سرور'; msgBox.style.color = 'var(--danger)'; }
    btn.disabled = false;
    btn.textContent = 'اعمال %';
  }
};
window.removeDiscountCode = function () {
  state.buy.discount = null;
  renderPurchaseDetails(document.getElementById('app'));
};
window.doPurchase = async function () {
  const b = state.buy;
  let username = '';
  let note = '';
  if (b.country.is_username) {
    const el = document.getElementById('customUsername');
    username = (el?.value || '').trim();
    if (!username) {
      el?.classList.add('input-error');
      const err = document.getElementById('usernameErr');
      if (err) { err.textContent = 'نام کاربری / نام کانفیگ الزامی است'; err.style.display = 'block'; }
      toast('لطفاً نام کاربری دلخواه رو وارد کن');
      el?.focus();
      return;
    }
  }
  if (b.country.is_note) {
    note = (document.getElementById('customNote')?.value || '').trim();
  }
  const btn = document.getElementById('confirmBtn');
  btn.disabled = true;
  btn.textContent = 'در حال پردازش…';
  try {
    const body = b.service
      ? {
          service_id: b.service.id,
          country_id: b.country.id,
          category_id: b.category?.id || 0,
          custom_username: username,
          custom_note: note,
          discount_code: b.discount ? b.discount.code : '',
        }
      : {
          custom_service: {
            traffic_gb: b.customService.traffic_gb,
            time_days: b.customService.time_days,
            category_id: b.category?.id || 0,
          },
          country_id: b.country.id,
          custom_username: username,
          custom_note: note,
          discount_code: b.discount ? b.discount.code : '',
        };
    const res = await apiCall('purchase', {
      method: 'POST',
      body,
    });
    if (res.success || res.status) {
      haptic('medium');
      state.lastOrder = res.service || {};
      navigate('/buy/success');
    } else {
      toast(res.msg || res.message || 'خرید ناموفق بود');
      btn.disabled = false;
      btn.innerHTML = `${icon('check',16)} تکمیل خرید`;
    }
  } catch (e) {
    toast('خطا در ارتباط با سرور');
    btn.disabled = false;
    btn.innerHTML = `${icon('check',16)} تکمیل خرید`;
  }
};

route('/buy/success', async (app) => {
  const o = state.lastOrder || {};
  app.innerHTML = `
    <div class="page">
      <div class="success-wrap">
        <div class="success-badge">${icon('check', 36)}</div>
        <h2>خرید با موفقیت انجام شد 🎉</h2>
        <p>سرویس شما ساخته شد و اطلاعات اتصال از طریق ربات برات ارسال می‌شه.</p>
        <div class="summary-card" style="width:100%;text-align:right">
          <div class="summary-row"><span class="k">نام کاربری</span><span class="v">${o.username || '—'}</span></div>
          <div class="summary-row"><span class="k">وضعیت</span><span class="v">فعال</span></div>
        </div>
        <button class="btn btn-primary btn-block btn-lg" style="margin-top:18px" onclick="navigate('/services')">مشاهده سرویس‌های من</button>
        <button class="btn btn-outline btn-block btn-lg" style="margin-top:10px" onclick="navigate('/home')">بازگشت به خانه</button>
      </div>
    </div>
    ${bottomNav('buy')}
  `;
  state.buy = { country: null, category: null, timeRange: null, service: null, customService: null };
});

/* ---------------------- boot ---------------------- */
async function boot() {
  try {
    tg?.ready();
    tg?.expand();
    if (tg?.setHeaderColor) { try { tg.setHeaderColor('#0f0a1a'); } catch (e) {} }
    state.tgUser = tg?.initDataUnsafe?.user || null;
    state.userId = state.tgUser?.id || null;

    if (!tg || !tg.initData) {
      throw new Error('این صفحه فقط داخل تلگرام قابل استفاده‌ست.');
    }
    await verifySession();
    renderRoute();
  } catch (e) {
    document.getElementById('app').innerHTML = errorScreen(e.message);
  }
}
boot();
