/* ============================================================
   MyKollectOr® — chat.js — Polling 5s
   ============================================================ */

const Chat = (() => {
  let intervalId = null;
  let conversationId = null;
  let lastTimestamp = null;
  let currentUser = null;

  const init = (convId) => {
    conversationId = convId;
    currentUser = Auth.getUser();
    lastTimestamp = new Date().toISOString();
  };

  const renderMessage = (msg) => {
    const isMine = currentUser && msg.auteur_id === currentUser.id;
    const side = isMine ? 'msg-right' : 'msg-left';
    const time = new Date(msg.created_at).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
    const date = new Date(msg.created_at).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit' });

    return `
      <div class="msg ${side}">
        <div class="msg-author">${msg.auteur_nom || 'Inconnu'}</div>
        <div class="msg-bubble">${escapeHtml(msg.message || msg.contenu)}</div>
        <div class="msg-time">${date} ${time}</div>
      </div>`;
  };

  const loadInitial = async () => {
    if (!conversationId) return;
    try {
      const data = await Api.get(`/api/chat/${conversationId}/messages`);
      const container = document.getElementById('chat-messages');
      if (!container) return;
      container.innerHTML = '';
      (data.messages || data || []).forEach(m => {
        container.insertAdjacentHTML('beforeend', renderMessage(m));
      });
      scrollToBottom();
      if (data.messages && data.messages.length > 0) {
        lastTimestamp = data.messages[data.messages.length - 1].created_at;
      }
    } catch { /* silent */ }
  };

  const poll = async () => {
    if (!conversationId) return;
    try {
      const ts = encodeURIComponent(lastTimestamp || '');
      const data = await Api.get(`/api/chat/${conversationId}/messages?since=${ts}`);
      const msgs = data.messages || (Array.isArray(data) ? data : []);
      if (msgs.length === 0) return;
      const container = document.getElementById('chat-messages');
      if (!container) return;
      msgs.forEach(m => {
        container.insertAdjacentHTML('beforeend', renderMessage(m));
      });
      lastTimestamp = msgs[msgs.length - 1].created_at;
      scrollToBottom();
    } catch { /* silent */ }
  };

  const send = async (contenu) => {
    if (!conversationId || !contenu.trim()) return;
    await Api.post(`/api/chat/${conversationId}/messages`, { message: contenu.trim() });
    await poll(); // refresh immediately
  };

  const start = () => {
    intervalId = setInterval(poll, 5000);
  };

  const stop = () => {
    if (intervalId) { clearInterval(intervalId); intervalId = null; }
  };

  const scrollToBottom = () => {
    const c = document.getElementById('chat-messages');
    if (c) c.scrollTop = c.scrollHeight;
  };

  const escapeHtml = (str) => str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');

  return { init, loadInitial, poll, send, start, stop };
})();
