document.addEventListener('DOMContentLoaded', async () => {
  try {
    const response = await fetch(configUrl);
    if (!response.ok) throw new Error(`Config not found at ${configUrl}`);

    const config = await response.json();
    const { widgetHTML, preamble, api } = config;

    if (!widgetHTML || !api) {
      console.error('Invalid config format. Expected widgetHTML and api.');
      return;
    }

    // Inject HTML
    document.body.insertAdjacentHTML('beforeend', widgetHTML);
    console.log("HERE!")
    document.dispatchEvent(new CustomEvent('JSsucks'));
    // DOM references
    const chatToggle = document.getElementById('cw-chatToggle');
    const chatWidget = document.getElementById('cw-chatWidget');
    const chatForm = document.getElementById('cw-chatForm');
    const chatInput = document.getElementById('cw-chatInput');
    const chatMessages = document.getElementById('cw-chatMessages');
    const statusDiv = document.getElementById('cw-status');

    const sessionId = crypto.randomUUID();
    let chatOpened = false;

    // Append a message to the chat
    function appendMessage(text, sender) {
      const msg = document.createElement('div');
      msg.classList.add('cw-message', sender === 'user' ? 'user' : 'bot');
      msg.innerHTML = text;
      chatMessages.appendChild(msg);
      chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    // Centralized function to send a message
    async function sendMessageToBot(messageText) {
      console.log(messageText)
      chatWidget.style.display = 'block';
      appendMessage(messageText, 'user');
      chatInput.value = '';
      chatInput.focus();

      try {
        const res = await fetch(api, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            action: 'sendMessage',
            sessionId,
            chatInput: messageText
          })
        });

        const data = await res.json();

        if (data.status) {
          statusDiv.innerHTML = data.status;
          requestAnimationFrame(() => {
            statusDiv.style.padding = '10px';
            statusDiv.style.maxHeight = statusDiv.scrollHeight + 'px';
          });
        } else {
          statusDiv.style.maxHeight = '0';
          statusDiv.style.padding = '0 10px';
        }

        appendMessage(data.output, 'bot');
      } catch (error) {
        appendMessage('Fehler beim Verbinden mit dem Server. Bitte versuchen Sie es später erneut.', 'bot');
        console.error(error);
      }
    }

  window.sendMessageToBot = sendMessageToBot;
    // Toggle chat widget
    chatToggle.addEventListener('click', () => {
      const isVisible = chatWidget.style.display === 'block';
      chatWidget.style.display = isVisible ? 'none' : 'block';

      if (!isVisible && !chatOpened) {
        appendMessage(preamble, 'bot');
        chatOpened = true;
      }
    });

    // Form submission
    chatForm.addEventListener('submit', (e) => {
      e.preventDefault();
      const input = chatInput.value.trim();
      if (input) {
        sendMessageToBot(input);
      }
    });

    // Attach buy button listeners

  } catch (err) {
    console.error('Failed to initialize chat widget:', err);
  }

});

