/* ═══════════════════════════════════════════════════════════════════
   Al Moasis · Dashboard v3 — Settings tab
   ═══════════════════════════════════════════════════════════════════

   Sections:
   1. Business identity — read from /api/auth/my-tenant
   2. License — /api/license/status (state, plan, expires_at, days_remaining)
   3. AI providers (BYOK) — /api/models/keys (paste + persist to .env)
   4. App info — version, data dir, machine fingerprint

   Strictly follows the v3 design language: emerald cards, Lucide icons,
   Sora/Inter/Noto Arabic, no fake data — empty states everywhere a real
   value isn't available yet.
*/

'use strict';

(function () {
  const $ = (sel) => document.querySelector(sel);
  const api = () => window.__moasis?.api;
  const applyIcons = () => window.__moasis?.applyIcons?.();

  // ─── Business identity ────────────────────────────────────────────
  function renderTenant() {
    const t = window.CURRENT_TENANT || {};
    const set = (key, val) => {
      const el = $(`[data-bind="${key}"]`);
      if (el) el.textContent = val || '—';
    };
    set('settings-name-ar',        t.business_name_ar);
    set('settings-name-en',        t.business_name);
    set('settings-agent-name',     t.agent_name);
    set('settings-whatsapp-phone', t.whatsapp_phone);
  }

  // ─── License ──────────────────────────────────────────────────────
  const LICENSE_STATE_LABELS = {
    active:      'مفعّل',
    unactivated:'غير مفعّل',
    expired:    'منتهي',
    revoked:    'ملغى',
  };
  const LICENSE_PLAN_LABELS = {
    monthly:    'شهري',
    six_months: '٦ أشهر',
    yearly:     'سنوي',
    individual: 'دائم',
    enterprise: 'مؤسسات',
  };

  async function refreshLicense() {
    const dot   = $('[data-bind="settings-license-dot"]');
    const lbl   = $('[data-bind="settings-license-state"]');
    const plan  = $('[data-bind="settings-license-plan"]');
    const exp   = $('[data-bind="settings-license-expires"]');
    const days  = $('[data-bind="settings-license-days"]');

    try {
      const r = await api()('/api/license/status');
      const state = r?.state || 'unactivated';
      // pill color
      if (dot) {
        dot.classList.remove('bg-emerald-500','bg-rose-500','bg-amber-500','bg-muted');
        dot.classList.add(
          state === 'active' ? 'bg-emerald-500'
          : state === 'expired' || state === 'revoked' ? 'bg-rose-500'
          : 'bg-amber-500'
        );
      }
      if (lbl) lbl.textContent = LICENSE_STATE_LABELS[state] || state;
      if (plan) plan.textContent = LICENSE_PLAN_LABELS[r?.plan] || r?.plan || '—';
      if (exp) {
        exp.textContent = r?.expires_at
          ? new Date(r.expires_at).toLocaleDateString('ar-SA', { year:'numeric', month:'short', day:'numeric' })
          : (r?.plan === 'individual' ? 'دائم' : '—');
      }
      if (days) {
        if (typeof r?.days_remaining === 'number') {
          days.textContent = `${r.days_remaining} يوم`;
          days.style.color = r.days_remaining < 7  ? '#E11D48'
                          : r.days_remaining < 30 ? '#D97706'
                          : '#0E9A6F';
        } else {
          days.textContent = r?.plan === 'individual' ? '∞' : '—';
        }
      }
    } catch (err) {
      if (lbl) lbl.textContent = `خطأ: ${err.message}`;
    }
  }

  // ─── BYOK (AI provider keys) ──────────────────────────────────────
  async function renderByokKeys() {
    const list = $('[data-bind="byok-list"]');
    if (!list) return;
    try {
      const r = await api()('/api/models/keys');
      const keys = r?.keys || [];
      if (keys.length === 0) {
        list.innerHTML = `<div class="p-5 text-center text-[13px] text-muted">لا توجد مزوّدات مُعرّفة في النظام.</div>`;
        return;
      }
      list.innerHTML = keys.map((k) => byokRow(k)).join('');
      applyIcons();
      // Wire each row's paste button
      list.querySelectorAll('[data-byok-save]').forEach((btn) => {
        btn.addEventListener('click', () => saveByokKey(btn.dataset.byokSave));
      });
      list.querySelectorAll('[data-byok-delete]').forEach((btn) => {
        btn.addEventListener('click', () => deleteByokKey(btn.dataset.byokDelete));
      });
    } catch (err) {
      list.innerHTML = `<div class="p-5 text-center text-[13px] text-rose-600">تعذّر تحميل قائمة المزوّدين: ${escapeHtml(err.message)}</div>`;
    }
  }

  function byokRow(k) {
    const setStatus = k.set
      ? `<span class="pill" style="background:#ECFDF5;border-color:#D1FAE5;color:#0E9A6F;">
           <i data-lucide="check" class="w-3.5 h-3.5"></i>
           <span>مُفعّل · …${escapeHtml(k.last4 || '')}</span>
         </span>`
      : `<span class="pill" style="background:#F9FAFB;border-color:#E5E7EB;color:#94A3B8;">
           <i data-lucide="x" class="w-3.5 h-3.5"></i>
           <span>غير مُفعّل</span>
         </span>`;
    return `
      <div class="p-5">
        <div class="flex items-center gap-3 mb-3">
          <div class="flex-1">
            <div class="font-semibold text-[14px] text-ink">${escapeHtml(k.display || k.provider)}</div>
            <div class="text-[11px] text-muted font-num" dir="ltr">${escapeHtml(k.env)}</div>
          </div>
          ${setStatus}
        </div>
        <div class="flex gap-2">
          <input type="password" placeholder="${escapeHtml(k.prefix || 'sk-…')}xxxxxxxx"
            dir="ltr" data-byok-input="${escapeHtml(k.env)}"
            class="flex-1 px-3 py-2 bg-white border border-line rounded-lg outline-none text-[13px] font-num focus:border-emerald-600 transition" />
          <button class="btn-primary" data-byok-save="${escapeHtml(k.env)}">
            <i data-lucide="save" class="w-4 h-4"></i>
            <span>حفظ</span>
          </button>
          ${k.set ? `
            <button class="btn-outline" data-byok-delete="${escapeHtml(k.env)}">
              <i data-lucide="trash-2" class="w-4 h-4"></i>
            </button>` : ''}
        </div>
        ${k.get_url ? `<a href="#" data-open-url="${escapeHtml(k.get_url)}" class="text-[11px] text-emerald-600 hover:underline mt-2 inline-block">احصل على مفتاح من ${escapeHtml(k.get_url)}</a>` : ''}
      </div>
    `;
  }

  async function saveByokKey(env) {
    const input = document.querySelector(`[data-byok-input="${env}"]`);
    if (!input) return;
    const value = input.value.trim();
    if (!value || value.length < 10) {
      alert('المفتاح قصير جداً. الصق المفتاح الكامل من لوحة المزوّد.');
      return;
    }
    try {
      await api()('/api/models/keys', {
        method: 'POST',
        body: JSON.stringify({ env, value }),
      });
      input.value = '';
      await renderByokKeys();
    } catch (err) {
      alert(`فشل الحفظ: ${err.message}`);
    }
  }

  async function deleteByokKey(env) {
    if (!confirm('سيتم حذف المفتاح من المؤسس. متابعة؟')) return;
    try {
      await api()(`/api/models/keys?env=${encodeURIComponent(env)}`, { method: 'DELETE' });
      await renderByokKeys();
    } catch (err) {
      alert(`فشل الحذف: ${err.message}`);
    }
  }

  // ─── App info ─────────────────────────────────────────────────────
  async function renderAppInfo() {
    try {
      const r = await fetch('/health').then((x) => x.json());
      const v = $('[data-bind="settings-app-version"]');
      if (v) v.textContent = `v${r?.version || '—'}`;
    } catch { /* ignore */ }

    try {
      const r = await api()('/api/license/status');
      const fp = $('[data-bind="settings-machine-fp"]');
      const hb = $('[data-bind="settings-heartbeat"]');
      if (fp) fp.textContent = r?.fingerprint ? `…${r.fingerprint.slice(-12)}` : '—';
      if (hb) {
        hb.textContent = r?.last_heartbeat_at
          ? new Date(r.last_heartbeat_at).toLocaleString('ar-SA', { dateStyle: 'short', timeStyle: 'short' })
          : 'لم يُنفّذ بعد';
      }
    } catch { /* ignore */ }

    try {
      const r = await api()('/api/system/data-dir');
      const dd = $('[data-bind="settings-data-dir"]');
      if (dd && r?.data?.path) {
        dd.textContent = r.data.path;
        dd.title = r.data.path;
      }
    } catch {
      // Endpoint may not exist — leave the dash placeholder
    }
  }

  // ─── Misc helpers ─────────────────────────────────────────────────
  function escapeHtml(s) {
    return String(s ?? '').replace(/[&<>"']/g, (c) => ({
      '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
    }[c]));
  }

  // Open external URLs via the system browser (Tauri opener plugin)
  document.addEventListener('click', (e) => {
    const a = e.target.closest?.('[data-open-url]');
    if (!a) return;
    e.preventDefault();
    const url = a.dataset.openUrl;
    if (window.__TAURI__?.opener?.openUrl) window.__TAURI__.opener.openUrl(url);
    else window.open(url, '_blank', 'noopener');
  });

  // ─── License refresh button ──────────────────────────────────────
  document.addEventListener('click', (e) => {
    if (e.target.closest?.('[data-action="settings-license-refresh"]')) refreshLicense();
  });

  function onShow() {
    renderTenant();
    refreshLicense();
    renderByokKeys();
    renderAppInfo();
  }

  window.__moasisSettings = { onShow };
})();
