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

  const USER_ID = window.USER_ID ?? null;

  // Echo state manager
  window.chatEcho = {
    currentChannel: null,
    presenceChannel: null
  };

  // Ensure basic globals exist
  if (!window.state) {
    window.state = {
      currentChat: null,
      messages: []
    };
  }
  if (!window.contacts) {
    window.contacts = [];
  }

  // Normalize message from backend payload
  function getInitialsFromName(name) {
    if (!name) return '';
    return name
      .split(' ')
      .filter(Boolean)
      .map(part => part[0].toUpperCase())
      .slice(0, 2)
      .join('');
  }

  function normalizeMessage(msg) {
    const senderName = msg.sender?.name || 'Unknown';
    return {
      id: msg.message_id || msg.id,
      chatId: msg.chat_id,
      text: msg.message,
      senderId: msg.sender_id,
      senderName,
      sender: senderName,
      senderInitials: getInitialsFromName(senderName),
      timestamp: new Date(msg.sent_at),
      direction: msg.sender_id === USER_ID ? 'sent' : 'received'
    };
  }

  // Dedicated message handler
  function handleIncomingMessage(e) {
    try {
      const message = normalizeMessage(e.message);
      if (!window.state?.currentChat || window.state.currentChat?.chat_id !== message.chatId) {
        return;
      }
      window.state.currentChat.messages = window.state.currentChat.messages || [];
      window.state.currentChat.messages.push(message);
      if (typeof window.renderMessages === 'function') {
        window.renderMessages();
      }
      if (typeof window.scrollToBottom === 'function') {
        window.scrollToBottom();
      }
    } catch (err) {
      console.error('Message handling error:', err);
    }
  }

  // Safe channel switching
  function switchChatChannel(chatId) {
    if (window.chatEcho.currentChannel) {
      Echo.leave(window.chatEcho.currentChannel);
    }
    const channelName = `chat.${chatId}`;
    window.chatEcho.currentChannel = channelName;
    Echo.private(channelName)
      .listen('.message.sent', handleIncomingMessage);
  }

  // Connection monitoring
  function monitorConnection() {
    if (!Echo?.connector?.pusher?.connection) return;
    const connection = Echo.connector.pusher.connection;
    connection.bind('connected', () => {
      console.log('✅ Echo connected successfully');
    });
    connection.bind('disconnected', () => {
      console.warn('❌ Echo disconnected - attempting reconnect...');
    });
    connection.bind('error', (err) => {
      console.error('Echo error:', err);
    });
  }

  // Main initialization
  function initEchoChat() {
    if (typeof Echo === 'undefined') {
      console.warn('Echo not loaded - check Vite/build');
      return;
    }
    if (!USER_ID) {
      console.warn('No authenticated user for Echo (window.USER_ID missing)');
      return;
    }
    monitorConnection();

    // Listen for chat selection
    document.addEventListener('chatSelected', (e) => {
      const chatId = e.detail?.chat_id;
      if (chatId) {
        switchChatChannel(chatId);
      }
    });

    console.log('🎉 Echo chat fully initialized');
  }

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

  // Expose globally
  window.initEchoChat = initEchoChat;
  window.switchChatChannel = switchChatChannel;

})();

