// Real-time chat Echo initialization
// Requires window.USER_ID set from Blade view
(function () {
  'use strict';

  const USER_ID = window.USER_ID ?? null;

  window.chatEcho = {
    currentChannel: null,
  };

  // ----------------------------------------------------------------
  // Normalize message from backend broadcast payload
  // ----------------------------------------------------------------
  function normalizeMessage(msg) {
    // FIX — backend relationship is senderUser, not sender
    const senderName = msg.sender_name        // broadcastWith() sends sender_name directly
                    || msg.senderUser?.name
                    || msg.sender?.name
                    || 'Unknown';

    return {
      id:          msg.message_id || msg.id,
      message_id:  msg.message_id,
      chat_id:     msg.chat_id,
      sender_id:   msg.sender_id,
      text:        msg.message ?? '',
      timestamp:   msg.sent_at ? new Date(msg.sent_at) : new Date(),
      direction:   msg.sender_id === USER_ID ? 'sent' : 'received',
      sender:      senderName,
      is_read:     !!msg.is_read,
      status:      msg.sender_id === USER_ID ? 'sent' : 'received',
    };
  }

  // ----------------------------------------------------------------
  // Handle an incoming broadcast message
  // ----------------------------------------------------------------
  function handleIncomingMessage(e) {
    try {
      const raw     = e.message ?? e;   // broadcastWith() wraps in { message: {...} }
      const message = normalizeMessage(raw);

      // Ignore if not the currently open chat
      const currentChatId = window.state?.chat?.chat_id    // new blade state shape
                         ?? window.state?.currentChat?.chat_id; // old shape fallback
      if (!currentChatId || currentChatId !== message.chat_id) return;

      // Ignore own messages — already added optimistically by sendMessage()
      if (message.sender_id === USER_ID) return;

      // Push into whichever state shape is present
      const chatObj = window.state?.chat ?? window.state?.currentChat;
      if (!chatObj) return;
      chatObj.messages = chatObj.messages || [];
      chatObj.messages.push(message);

      if (typeof window.renderMessages === 'function')  window.renderMessages();
      if (typeof window.scrollToBottom === 'function')  window.scrollToBottom();

      // Update contact list preview
      if (typeof window.updateContactStatus === 'function') {
        window.updateContactStatus(message.sender_id, 'online');
      }
    } catch (err) {
      console.error('[echo] handleIncomingMessage error:', err);
    }
  }

  // ----------------------------------------------------------------
  // Subscribe to a chat channel
  // ----------------------------------------------------------------
  function switchChatChannel(chatId) {
    if (!window.Echo) return;

    // Leave previous channel cleanly
    if (window.chatEcho.currentChannel) {
      window.Echo.leave(window.chatEcho.currentChannel);
      window.chatEcho.currentChannel = null;
    }

    if (!chatId) return;

    const channelName = `chat.${chatId}`;
    window.chatEcho.currentChannel = channelName;

    window.Echo.private(channelName)
      // FIX — event name must match broadcastAs() = 'MessageSent', no dot prefix
      // (dot prefix = fully-qualified custom event; no dot = Echo maps to class name)
      .listen('MessageSent', handleIncomingMessage);

    console.log(`[echo] subscribed to ${channelName}`);
  }

  // ----------------------------------------------------------------
  // Connection health monitoring
  // ----------------------------------------------------------------
  function monitorConnection() {
    const conn = window.Echo?.connector?.pusher?.connection;
    if (!conn) return;
    conn.bind('connected',    ()  => console.log('[echo] ✅ connected'));
    conn.bind('disconnected', ()  => console.warn('[echo] ⚠️ disconnected'));
    conn.bind('error',        err => console.error('[echo] error:', err));
  }

  // ----------------------------------------------------------------
  // Init
  // ----------------------------------------------------------------
  function initEchoChat() {
    if (typeof window.Echo === 'undefined') {
      console.warn('[echo] Echo not loaded — check Vite build or bootstrap.js');
      return;
    }
    if (!USER_ID) {
      console.warn('[echo] window.USER_ID missing — user not authenticated');
      return;
    }

    monitorConnection();

    // Subscribe whenever a chat is opened
    document.addEventListener('chatSelected', (e) => {
      const chatId = e.detail?.chat_id;
      if (chatId) switchChatChannel(chatId);
    });

    console.log('[echo] 🎉 Echo chat initialized');
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initEchoChat);
  } else {
    initEchoChat();
  }

  window.initEchoChat       = initEchoChat;
  window.switchChatChannel  = switchChatChannel;

})();