let localUserId = '';
let messages = [];

function initCustomChat(api) {
  const chatContainer = document.createElement('div');
  chatContainer.id = 'custom-chat';
  chatContainer.innerHTML = `
    <div class="chat-header">Chat</div>
    <div class="chat-messages" id="chat-messages"></div>
    <div class="chat-input-container">
      <input type="text" id="chat-input" placeholder="Type your message..." />
      <input type="file" id="chat-image" accept="image/*" style="display:none"/>
      <button onclick="document.getElementById('chat-image').click()">📷</button>
      <button onclick="sendCustomMessage()">Send</button>
    </div>
  `;
  document.body.appendChild(chatContainer);

  api.addEventListeners({
    participantJoined: ({ id }) => { if (!localUserId) localUserId = id; },
    endpointTextMessageReceived: handleIncomingMessage
  });

  document.getElementById('chat-image').addEventListener('change', function (e) {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = function () {
        const base64 = reader.result;
        sendCustomMessage(base64, true);
      };
      reader.readAsDataURL(file);
    }
  });
}

function sendCustomMessage(content = null, isImage = false) {
  const text = content || document.getElementById('chat-input').value;
  if (!text) return;
  const messageObj = {
    type: isImage ? 'image' : 'text',
    from: localUserId,
    content: text,
    timestamp: new Date().toISOString()
  };
  api.executeCommand('sendEndpointTextMessage', '', messageObj);
  appendMessage(messageObj, true);
  document.getElementById('chat-input').value = '';
}

function handleIncomingMessage({ data }) {
  if (!data || !data.type) return;
  appendMessage(data, false);
}

function appendMessage(msg, isLocal) {
  const messagesDiv = document.getElementById('chat-messages');
  const msgDiv = document.createElement('div');
  msgDiv.className = `chat-message ${isLocal ? 'local' : 'remote'}`;
  if (msg.type === 'text') {
    msgDiv.textContent = msg.content;
  } else if (msg.type === 'image') {
    const img = document.createElement('img');
    img.src = msg.content;
    img.style.maxWidth = '150px';
    msgDiv.appendChild(img);
  }
  messagesDiv.appendChild(msgDiv);
  messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
