/* Al Moasis · Dashboard v3 — Conversations tab
   Multi-customer inbox. Lists every customer with last message + unread
   count + channel pill, sorted by last_contact. Click → switches to chat
   tab pre-loaded with that customer (future iteration). */

'use strict';

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

  const CHANNEL_BADGE = {
    whatsapp: { label: 'واتساب', cls: 'bg-emerald-50 text-emerald-700' },
    telegram: { label: 'تيليجرام', cls: 'bg-sky-50 text-sky-700' },
    web:      { label: 'ويب', cls: 'bg-slate-100 text-slate-700' },
    discord:  { label: 'ديسكورد', cls: 'bg-violet-50 text-violet-700' },
    slack:    { label: 'سلاك', cls: 'bg-amber-50 text-amber-700' },
  };

  async function load() {
    const root = $('[data-bind="conv-list"]');
    if (!root) return;
    try {
      const tid = window.CURRENT_TENANT_ID;
      const r = await api()(`/api/tenants/${tid}/conversations`);
      // Show every customer except the system-cron pseudo-customer.
      // total_messages on the customers table isn't being incremented
      // reliably; the real signal is "did this customer ever exchange
      // messages" — for now we trust the conversations endpoint to only
      // return rows that have any activity.
      const rows = (r?.data || r || []).filter((c) =>
        c && c.phone !== 'system-cron'
      );
      if (rows.length === 0) {
        root.innerHTML = `<div class="text-center text-[13px] text-muted py-12">لا توجد محادثات نشطة بعد. ستظهر هنا كل محادثة حقيقية مع عميل عبر واتساب أو تيليجرام أو الويب.</div>`;
        return;
      }
      // Sort by last_contact desc
      rows.sort((a, b) => new Date(b.last_contact || 0) - new Date(a.last_contact || 0));
      root.innerHTML = `
        <div class="bg-white rounded-2xl border border-line shadow-card divide-y divide-soft overflow-hidden">
          ${rows.map(row).join('')}
        </div>`;
      applyIcons();
    } catch (err) {
      root.innerHTML = `<div class="text-center text-[13px] text-rose-600 py-12">تعذّر التحميل: ${esc(err.message)}</div>`;
    }
  }

  function row(c) {
    const initial = (c.name || c.phone || '?').trim().charAt(0).toUpperCase();
    const channel = c.metadata?.channel || (c.phone?.startsWith('web-') ? 'web' : 'whatsapp');
    const badge = CHANNEL_BADGE[channel] || { label: channel, cls: 'bg-slate-100 text-slate-700' };
    const last = c.last_contact ? new Date(c.last_contact).toLocaleString('ar-SA', { dateStyle: 'short', timeStyle: 'short' }) : '';
    const name = c.name || c.phone || '—';
    const phoneHint = c.phone && c.phone !== name ? c.phone : '';
    return `
      <div class="px-5 py-4 flex items-center gap-3 hover:bg-page transition cursor-pointer" data-conv-id="${esc(c.id)}">
        <div class="msg-avatar bg-emerald-100 text-emerald-700 shrink-0">${esc(initial)}</div>
        <div class="flex-1 min-w-0">
          <div class="flex items-center gap-2">
            <div class="font-semibold text-[14px] text-ink truncate">${esc(name)}</div>
            <span class="px-2 py-0.5 rounded-full text-[10px] font-medium ${badge.cls}">${esc(badge.label)}</span>
          </div>
          ${phoneHint ? `<div class="text-[11px] text-muted font-num truncate" dir="ltr">${esc(phoneHint)}</div>` : ''}
        </div>
        <div class="text-end shrink-0">
          <div class="text-[11px] text-muted">${esc(last)}</div>
          <div class="text-[11px] text-muted">${esc(c.total_messages || 0)} رسالة</div>
        </div>
      </div>`;
  }

  function wire() {
    document.addEventListener('click', (ev) => {
      const row = ev.target.closest?.('[data-conv-id]');
      if (!row) return;
      // Future: open that customer's thread in the chat pane.
      // For now switch back to chat — most users want to see Moasis's main thread.
      if (window.__moasis?.switchPane) window.__moasis.switchPane('chat');
    });
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', wire);
  else wire();

  function onShow() { load(); }
  window.__moasisConversations = { onShow };
})();
