(() => {
  'use strict';

  const root = document.querySelector('[data-android-dashboard]');
  if (!root) return;

  const get = (selector) => root.querySelector(selector);
  const set = (selector, value) => {
    const element = get(selector);
    if (element) element.textContent = String(value ?? '—');
  };
  const number = (value) => Number.isFinite(Number(value)) ? Number(value) : 0;
  const rate = (value) => {
    const amount = Math.max(0, number(value));
    return amount >= 1000 ? `${(amount / 1000).toFixed(1)} Gbps` : `${amount.toFixed(amount >= 100 ? 0 : 1)} Mbps`;
  };
  const fetchJson = async (path) => {
    const response = await fetch(`${path}${path.includes('?') ? '&' : '?'}_=${Date.now()}`, {
      credentials: 'same-origin', cache: 'no-store', headers: {Accept: 'application/json'}
    });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return JSON.parse((await response.text()).replace(/^\uFEFF/, ''));
  };

  const sourceText = (source) => {
    const label = String(source?.label || source?.iface || source?.router_name || 'مصدر غير مسمى').trim();
    const router = String(source?.router_name || source?.router_host || '').trim();
    const iface = String(source?.iface || '').trim();
    const meta = [router, iface && iface !== label ? iface : ''].filter(Boolean).join(' • ');
    return {label, meta};
  };

  const sourceState = (source) => {
    if (source?.ok) return {className: 'is-live', label: 'مباشر'};
    if (source?.stale) return {className: 'is-stale', label: 'آخر قراءة'};
    return {className: 'is-down', label: 'غير متاح'};
  };

  const createRate = (label, value) => {
    const item = document.createElement('div');
    const title = document.createElement('span');
    const amount = document.createElement('strong');
    title.textContent = label;
    amount.textContent = rate(value);
    item.append(title, amount);
    return item;
  };

  const renderTrafficSources = (sources) => {
    const list = get('[data-ad-traffic-sources]');
    const safeSources = Array.isArray(sources) ? sources : [];
    set('[data-ad-traffic-count]', `${safeSources.length} مصدر`);
    if (!list) return;
    list.replaceChildren();

    if (!safeSources.length) {
      const empty = document.createElement('p');
      empty.className = 'ad-traffic-empty';
      empty.textContent = 'لا توجد مصادر ترافيك مضافة حالياً';
      list.append(empty);
      return;
    }

    safeSources.forEach((source) => {
      const text = sourceText(source);
      const state = sourceState(source);
      const item = document.createElement('article');
      item.className = `ad-traffic-source-card ${state.className}`;

      const head = document.createElement('div');
      head.className = 'ad-traffic-source-head';
      const identity = document.createElement('div');
      const title = document.createElement('strong');
      const meta = document.createElement('small');
      const badge = document.createElement('span');
      title.textContent = text.label;
      meta.textContent = text.meta || 'مصدر الترافيك';
      badge.textContent = state.label;
      identity.append(title, meta);
      head.append(identity, badge);

      const rates = document.createElement('div');
      rates.className = 'ad-traffic-source-rates';
      rates.append(
        createRate('الرفع', source?.tx_mbps),
        createRate('التحميل', source?.rx_mbps),
        createRate('الإجمالي', source?.total_mbps)
      );
      item.append(head, rates);
      list.append(item);
    });
  };

  async function refresh() {
    const button = get('[data-ad-refresh]');
    if (button) button.classList.add('is-loading');
    const wantsCounts = !!get('[data-ad-total]');
    const wantsTraffic = !!get('[data-ad-traffic-total]');
    const wantsSecurity = !!get('[data-ad-identifying]');
    const results = await Promise.allSettled([
      wantsCounts ? fetchJson('api/noc_counts.php') : Promise.resolve(null),
      wantsTraffic ? fetchJson('api/noc_traffic_card.php') : Promise.resolve(null),
      wantsSecurity ? fetchJson('api/security_monitor.php?summary=1&warmup=0') : Promise.resolve(null)
    ]);

    if (wantsCounts && results[0].status === 'fulfilled') {
      const counts = results[0].value || {};
      set('[data-ad-total]', counts.total);
      set('[data-ad-online]', counts.online ?? counts.connected);
      set('[data-ad-offline]', counts.offline);
      set('[data-ad-disabled]', counts.disabled ?? counts.financial_cut);
    }
    if (wantsTraffic && results[1].status === 'fulfilled') {
      const traffic = results[1].value || {};
      const sum = traffic.sum || {};
      set('[data-ad-traffic-total]', rate(sum.total_mbps));
      set('[data-ad-traffic-up]', rate(sum.tx_mbps));
      set('[data-ad-traffic-down]', rate(sum.rx_mbps));
      set('[data-ad-traffic-source]', traffic.iface?.selected || `${(traffic.sources || []).length} مصادر`);
      renderTrafficSources(traffic.sources);
    }
    if (wantsSecurity && results[2].status === 'fulfilled') {
      const summary = results[2].value?.summary || {};
      set('[data-ad-identifying]', summary.identifying);
      set('[data-ad-suspect]', summary.suspect);
      set('[data-ad-pppoe]', summary.pppoe_open ?? summary.pppoe);
      set('[data-ad-confirmed]', summary.confirmed);
    }

    const requested = results.filter((result, index) => [wantsCounts, wantsTraffic, wantsSecurity][index]);
    const ok = requested.length === 0 || requested.some((result) => result.status === 'fulfilled');
    const live = get('.ad-live-state');
    if (live) live.classList.toggle('is-ok', ok);
    set('[data-ad-system-label]', ok ? 'النظام متصل ومستقر' : 'تعذر تحديث البيانات');
    set('[data-ad-updated]', new Intl.DateTimeFormat('ar', {hour:'2-digit', minute:'2-digit'}).format(new Date()));
    if (button) button.classList.remove('is-loading');
  }

  get('[data-ad-open-menu]')?.addEventListener('click', () => {
    if (typeof window.uaAndroidToggleMenu === 'function') {
      window.uaAndroidToggleMenu();
    }
  });
  get('[data-ad-refresh]')?.addEventListener('click', refresh);
  get('[data-ad-traffic-toggle]')?.addEventListener('click', () => {
    const button = get('[data-ad-traffic-toggle]');
    const details = get('[data-ad-traffic-details]');
    if (!button || !details) return;
    const expanded = button.getAttribute('aria-expanded') !== 'true';
    button.setAttribute('aria-expanded', String(expanded));
    details.hidden = !expanded;
    root.querySelector('.ad-traffic-card')?.classList.toggle('is-traffic-expanded', expanded);
    const label = button.querySelector('span');
    if (label) label.textContent = expanded ? 'إخفاء التفاصيل' : 'التفاصيل';
  });
  refresh();
  window.setInterval(refresh, 15000);
})();
