/* Al Moasis · Dashboard v3 — Telegram tab
   Bot token paste + connect/disconnect, live status pill. */

'use strict';

(function () {
  const $ = (s) => document.querySelector(s);
  const api = () => window.__moasis?.api;
  const esc = (s) => String(s ?? '').replace(/[&<>"']/g,(c)=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));

  function setStatus(state, label, botUsername) {
    const dot = $('[data-bind="tg-status-dot"]');
    const lbl = $('[data-bind="tg-status-label"]');
    const card = $('[data-bind="tg-connected-card"]');
    const uname = $('[data-bind="tg-bot-username"]');
    if (dot) {
      dot.classList.remove('bg-emerald-500','bg-rose-500','bg-amber-500','bg-muted','dot-pulse-emerald');
      dot.classList.add(
        state === 'connected' ? 'bg-emerald-500 dot-pulse-emerald'
        : state === 'pending'  ? 'bg-amber-500'
        : state === 'disconnected' ? 'bg-rose-500'
        : 'bg-muted'
      );
    }
    if (lbl) lbl.textContent = label;
    if (card) card.classList.toggle('hidden', state !== 'connected');
    if (uname && botUsername) uname.textContent = '@' + String(botUsername).replace(/^@/, '');
  }

  async function fetchStatus() {
    try {
      const r = await api()('/api/channels/telegram/status');
      const d = r?.data || r || {};
      const state = d.status || (d.connected ? 'connected' : 'disconnected');
      const label = state === 'connected' ? 'متصل'
        : state === 'pending' ? 'جارٍ الاتصال…'
        : state === 'disconnected' ? 'غير متصل'
        : 'غير معروف';
      setStatus(state, label, d.username || d.bot_username);
    } catch {
      setStatus('disconnected', 'غير متصل');
    }
  }

  async function connect() {
    const input = $('#tg-token-input');
    const err   = $('[data-bind="tg-error"]');
    const token = (input?.value || '').trim();
    if (!/^\d{6,12}:[A-Za-z0-9_-]{30,}$/.test(token)) {
      if (err) { err.textContent = 'توكن غير صالح. تأكد من نسخه كاملاً من @BotFather.'; err.classList.remove('hidden'); }
      return;
    }
    if (err) err.classList.add('hidden');
    try {
      await api()('/api/channels/telegram/connect', {
        method: 'POST',
        body: JSON.stringify({ bot_token: token }),
      });
      if (input) input.value = '';
      await fetchStatus();
    } catch (e) {
      if (err) { err.textContent = `فشل الاتصال: ${e.message}`; err.classList.remove('hidden'); }
    }
  }

  async function disconnect() {
    try {
      await api()('/api/channels/telegram/disconnect', { method: 'POST' });
      await fetchStatus();
    } catch (e) {
      const err = $('[data-bind="tg-error"]');
      if (err) { err.textContent = `فشل القطع: ${e.message}`; err.classList.remove('hidden'); }
    }
  }

  function wire() {
    document.addEventListener('click', (ev) => {
      if (ev.target.closest?.('[data-action="tg-connect"]')) connect();
      else if (ev.target.closest?.('[data-action="tg-disconnect"]')) disconnect();
    });
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', wire);
  else wire();

  function onShow() { fetchStatus(); }
  window.__moasisTelegram = { onShow };
})();
