// Chat Widget Script
// modified version of: https://cdn.jsdelivr.net/gh/WayneSimpson/n8n-chatbot-template@ba944c3/chat-widget.js
(function() {
  // Create and inject styles
  const styles = `
.n8n-chat-widget {
--chat--color-primary: var(--n8n-chat-primary-color, #888B97);
--chat--color-secondary: var(--n8n-chat-secondary-color, #6b3fd4);
--chat--color-background: var(--n8n-chat-background-color, #ffffff);
--chat--color-font: var(--n8n-chat-font-color, #333333);
font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.n8n-chat-widget .chat-container {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
display: none;
width: 50vw;
max-width: 600px;
height: 80vh;
background: var(--chat--color-background);
border-radius: 12px;
box-shadow: 0 8px 32px rgba(133, 79, 255, 0.15);
border: 1px solid rgba(133, 79, 255, 0.2);
overflow: hidden;
font-family: inherit;

@media (max-width: 480px) {
  width: calc(100vw - 20px); /* PeBna szeroko[ minus po 10px z ka|dej strony */
    max-width: none;            /* Usuwa limit */
    height: 75vh;
    left: 10px;
    right: 10px;
    font-size: 14px;
    border-radius: 8px;

  .n8n-chat-widget .brand-header span,
  .n8n-chat-widget .response-text {
    font-size: 13px;
    margin-top: 2px;
  }

  .n8n-chat-widget .welcome-text {
    font-size: 16px;
    text-align: center;
  }

  .n8n-chat-widget .chat-message {
    font-size: 13px;
    padding: 10px 12px;
  }

  .n8n-chat-widget .chat-input textarea {
    font-size: 13px;
    padding: 10px;
  }

  .n8n-chat-widget .chat-input button,
  .n8n-chat-widget .new-chat-btn,
  .n8n-chat-widget .suggestion-btn {
    font-size: 13px;
    padding: 12px 16px;
  }

  .n8n-chat-widget .chat-toggle {
    width: 50px;
    height: 50px;
    bottom: 15px;
    right: 15px;
  }

  .n8n-chat-widget .chat-toggle svg {
    width: 20px;
    height: 20px;
  }

  .n8n-chat-widget .brand-header img {
    width: 24px;
    height: 24px;
    margin-top: 4px;
  }

  .n8n-chat-widget .close-button {
    top: 12px;
    right: 12px;
  }
}


@media (max-width: 768px) {
.n8n-chat-widget .chat-container {
  width: 70vw;
  height: 90vh;
  right: 10px;
  left: 10px;
}
}
}
.n8n-chat-widget .chat-container.position-left {
right: auto;
left: 20px;
}

.n8n-chat-widget .chat-container.open {
display: flex;
flex-direction: column;
}

.n8n-chat-widget .brand-header {
padding: 16px;
display: flex;
align-items: center;
gap: 12px;
border-bottom: 1px solid rgba(133, 79, 255, 0.1);
position: relative;
}

.n8n-chat-widget .brand-header img {
min-width: 30%;
height: auto;
object-fit: contain;
}

.n8n-chat-widget .close-button {
position: absolute;
right: 16px;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
color: var(--chat--color-font);
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
justify-content: center;
transition: color 0.2s;
font-size: 20px;
opacity: 0.6;
z-index: 10;
pointer-events: auto;
}

.n8n-chat-widget .close-button:hover {
opacity: 1;
}

.n8n-chat-widget .brand-header img {
width: 32px;
height: 32px;
}

.n8n-chat-widget .brand-header span {
font-size: 14px;
font-weight: 500;
color: var(--chat--color-font);
}

.n8n-chat-widget .new-conversation {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -60%);
padding: 10px;
text-align: center;
width: 100%;
max-width: 300px;
}

.n8n-chat-widget .welcome-text {
font-size: 18px;
font-weight: 600;
color: var(--chat--color-font);
margin-bottom: 20px;
line-height: 1.3;
}

.n8n-chat-widget .new-chat-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
width: 100%;
padding: 16px 24px;
background: linear-gradient(135deg, var(--chat--color-primary) 0%, var(--chat--color-secondary) 100%);
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 16px;
transition: transform 0.3s;
font-weight: 500;
font-family: inherit;
margin-bottom: 12px;
}

.n8n-chat-widget .new-chat-btn:hover {
transform: scale(1.02);
}
.suggestion-buttons {
  display: grid;
  grid-template-columns: 1fr;
  gap: 0.5rem;
  margin-top: 1rem;
}

.suggestion-btn {
  background-color: #1288A8;
  color: white;
  border: none;
  padding: 0.75rem;
  border-radius: 0.5rem;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
}

.suggestion-btn:hover {
  background-color: #6b3fd4;
}

/* Desktop: 2 kolumny */
@media (min-width: 768px) {
  .suggestion-buttons {
    grid-template-columns: 1fr 1fr;
  }
}

.n8n-chat-widget .message-icon {
width: 20px;
height: 20px;
}

.n8n-chat-widget .response-text {
font-size: 14px;
color: var(--chat--color-font);
opacity: 0.7;
margin: 0;
}

.n8n-chat-widget .chat-interface {
display: none;
flex-direction: column;
height: 100%;
}

.n8n-chat-widget .chat-interface.active {
display: flex;
}

.n8n-chat-widget .chat-messages {
flex: 1;
overflow-y: auto;
padding: 20px;
background: var(--chat--color-background);
display: flex;
flex-direction: column;
}

.n8n-chat-widget .chat-message {
padding: 12px 16px;
margin: 8px 0;
border-radius: 12px;
max-width: 80%;
word-wrap: break-word;
font-size: 14px;
line-height: 1.5;
}

.n8n-chat-widget .chat-message.user {
background: linear-gradient(135deg, var(--chat--color-primary) 0%, var(--chat--color-secondary) 100%);
color: white;
align-self: flex-end;
box-shadow: 0 4px 12px rgba(133, 79, 255, 0.2);
border: none;
}

.n8n-chat-widget .chat-message.bot {
background: var(--chat--color-background);
border: 1px solid rgba(133, 79, 255, 0.2);
color: var(--chat--color-font);
align-self: flex-start;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.n8n-chat-widget .chat-input {
padding: 16px;
background: var(--chat--color-background);
border-top: 1px solid rgba(133, 79, 255, 0.1);
display: flex;
gap: 8px;
}

.n8n-chat-widget .chat-input textarea {
flex: 1;
padding: 12px;
border: 1px solid rgba(133, 79, 255, 0.2);
border-radius: 8px;
background: var(--chat--color-background);
color: var(--chat--color-font);
resize: none;
font-family: inherit;
font-size: 14px;
}

.n8n-chat-widget .chat-input textarea::placeholder {
color: var(--chat--color-font);
opacity: 0.6;
}

.n8n-chat-widget .chat-input button {
background: linear-gradient(135deg, var(--chat--color-primary) 0%, var(--chat--color-secondary) 100%);
color: white;
border: none;
border-radius: 8px;
padding: 0 20px;
cursor: pointer;
transition: transform 0.2s;
font-family: inherit;
font-weight: 500;
}

.n8n-chat-widget .chat-input button:hover {
transform: scale(1.05);
}

.n8n-chat-widget .chat-toggle {
position: fixed;
bottom: 20px;
right: 20px;
width: 60px;
height: 60px;
border-radius: 30px;
background: linear-gradient(135deg, var(--chat--color-primary) 0%, var(--chat--color-secondary) 100%);
color: white;
border: none;
cursor: pointer;
box-shadow: 0 4px 12px rgba(133, 79, 255, 0.3);
z-index: 999;
transition: transform 0.3s;
display: flex;
align-items: center;
justify-content: center;
}

.n8n-chat-widget .chat-toggle.position-left {
right: auto;
left: 20px;
}

.n8n-chat-widget .chat-toggle:hover {
transform: scale(1.05);
}

.n8n-chat-widget .chat-toggle svg {
width: 24px;
height: 24px;
fill: currentColor;
}

.n8n-chat-widget .chat-footer {
padding: 8px;
text-align: center;
background: var(--chat--color-background);
border-top: 1px solid rgba(133, 79, 255, 0.1);
}

.n8n-chat-widget .chat-footer a {
color: var(--chat--color-primary);
text-decoration: none;
font-size: 12px;
opacity: 0.8;
transition: opacity 0.2s;
font-family: inherit;
}

.n8n-chat-widget .chat-footer a:hover {
opacity: 1;
}

/*styling for bubble*/
.typing-indicator {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 10px;
  font-size: 18px;
}

.typing-indicator span {
  display: inline-block;
  width: 6px;
  height: 6px;
  background-color: #999;
  border-radius: 50%;
  animation: blink 1.4s infinite both;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

.flags {
  font-size: 20px;
  margin: 5px;
}


@keyframes blink {
  0%, 80%, 100% {
    opacity: 0;
  }
  40% {
    opacity: 1;
  }
}


`;

  // Inject styles
  const styleSheet = document.createElement('style');
  styleSheet.textContent = styles;
  document.head.appendChild(styleSheet);

  // Default configuration
  const defaultConfig = {
    webhook: {
      url: '',
      route: ''
    },
    branding: {
      logo: '',
      name: '',
      welcomeText: '',
      langFlags: '',
      poweredBy: {
        text: 'Powered by n8n',
        link: 'https://n8n.partnerlinks.io/m8a94i19zhqq?utm_source=nocodecreative.io'
      }
    },
    style: {
      primaryColor: '',
      secondaryColor: '',
      position: 'right',
      backgroundColor: '#ffffff',
      fontColor: '#333333'
    }
  };

  // Merge user config with defaults
  const config = window.ChatWidgetConfig ?
  {
    webhook: { ...defaultConfig.webhook, ...window.ChatWidgetConfig.webhook },
    branding: { ...defaultConfig.branding, ...window.ChatWidgetConfig.branding },
    style: { ...defaultConfig.style, ...window.ChatWidgetConfig.style }
  } : defaultConfig;

  // Prevent multiple initializations
  if (window.N8NChatWidgetInitialized) return;
  window.N8NChatWidgetInitialized = true;

  let currentSessionId = '';

  // Create widget container
  const widgetContainer = document.createElement('div');
  widgetContainer.className = 'n8n-chat-widget';

  // Set CSS variables for colors
  widgetContainer.style.setProperty('--n8n-chat-primary-color', config.style.primaryColor);
  widgetContainer.style.setProperty('--n8n-chat-secondary-color', config.style.secondaryColor);
  widgetContainer.style.setProperty('--n8n-chat-background-color', config.style.backgroundColor);
  widgetContainer.style.setProperty('--n8n-chat-font-color', config.style.fontColor);

  // welcomeText nadpisany tlumaczeniem, nadpisuje standard-page.html
  (function updateWelcomeTextByLang() {
    const lang = navigator.language.slice(0, 2);
    const supported = ['pl', 'en', 'de'];
    const selectedLang = supported.includes(lang) ? lang : 'pl';

    const translationsByLang = {
      pl: {
        welcome: 'Znajdziemy dla Ciebie wymarzone miejsce do \u017cycia i biznesu'
      },
      en: {
        welcome: 'We\u2019ll find your dream space for living and business'

      },
      de: {
        welcome: 'Wir finden deinen Traumort zum Leben und Arbeiten'
      }
    };
  config.branding.welcomeText = translationsByLang[selectedLang].welcome;
  })();
    //koniec welcomeText
  const chatContainer = document.createElement('div');
  chatContainer.className = `chat-container open${config.style.position === 'left' ? ' position-left' : ''}`;

  const newConversationHTML = `
<div class="brand-header">
<img src="${config.branding.logo}" alt="${config.branding.name}">
<span>${config.branding.name}</span>
<button class="close-button">X</button>
</div>
<div class="new-conversation">
<h2 class="welcome-text">${config.branding.welcomeText}</h2>
<div class="ask-ai-container" id="ask-ai-container"></div>
<div class="suggestion-buttons" id="suggestion-buttons"></div>
<p class="flags">${config.branding.langFlags}</p>
</div>
`;

  const chatInterfaceHTML = `
<div class="chat-interface">
<div class="brand-header">
  <img src="${config.branding.logo}" alt="${config.branding.name}">
  <span>${config.branding.name}</span>
  <button class="close-button">X</button>
</div>
<div class="chat-messages"></div>
<div class="chat-input">
  <textarea id="chatTextarea" placeholder="" rows="1"></textarea>
  <button id="sendButton" type="submit"></button>
</div>
<div class="chat-footer">
  <a href="${config.branding.poweredBy.link}" target="_blank">${config.branding.poweredBy.text}</a>
</div>
</div>
`;

  // obiekty uBumaczenia przycisku oraz placeholdera w chat-input
  const translationMap = {
    pl: {
      placeholder: "Zapytaj tutaj......",
      sendLabel: "Wy&#347;lij"
    },
    en: {
      placeholder: "Ask your question here......",
      sendLabel: "Send"
    },
    de: {
      placeholder: "Frag hier......",
      sendLabel: "Senden"
    }
  };
  // koniec obiektow tlumaczenia do chat-input
  // jezyk przegladarki
  function getLanguage() {
    const lang = navigator.language || navigator.userLanguage;
    if (lang.startsWith("en")) return "en";
    if (lang.startsWith("de")) return "de";
    return "pl"; // domyslnie j.polski
  }
  // Renderuj tBumaczenia
  function renderTranslatedText() {
    const lang = getLanguage();
    const textarea = document.getElementById("chatTextarea");
    const sendButton = document.getElementById("sendButton");

    if (textarea) {
      textarea.placeholder = translationMap[lang].placeholder;
    }
    if (sendButton) {
      sendButton.textContent = translationMap[lang].sendLabel;
    }
  }
  // koniec mapy tlumaczen do chat-input i wyslij

  chatContainer.innerHTML = newConversationHTML + chatInterfaceHTML;

  const toggleButton = document.createElement('button');
  toggleButton.className = `chat-toggle${config.style.position === 'left' ? ' position-left' : ''}`;
  toggleButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12 2C6.477 2 2 6.477 2 12c0 1.821.487 3.53 1.338 5L2.5 21.5l4.5-.838A9.955 9.955 0 0012 22c5.523 0 10-4.477 10-10S17.523 2 12 2zm0 18c-1.476 0-2.886-.313-4.156-.878l-3.156.586.586-3.156A7.962 7.962 0 014 12c0-4.411 3.589-8 8-8s8 3.589 8 8-3.589 8-8 8z"/>
</svg>`;

  widgetContainer.appendChild(chatContainer);
  widgetContainer.appendChild(toggleButton);
  document.body.appendChild(widgetContainer);



  const chatInterface = chatContainer.querySelector('.chat-interface');
  const messagesContainer = chatContainer.querySelector('.chat-messages');
  const textarea = chatContainer.querySelector('textarea');
  const sendButton = chatContainer.querySelector('button[type="submit"]');

  function generateUUID() {
    return crypto.randomUUID();
  }
  // funkcja do ask AI w 3 jezykach
  const translationsByLang = {
    pl: {
      askButton: 'Zapytaj AI',
    },
    en: {
      askButton: 'Ask AI',
    },
    de: {
      askButton: 'Frag die KI',
    }
  };
  //funkcja wybierajaca jezyk
  function getLanguage() {
    const browserLang = navigator.language.slice(0, 2);
    return ['pl', 'en', 'de'].includes(browserLang) ? browserLang : 'pl';
  }
  function renderAskButton() {
    const lang = getLanguage();
    const container = document.querySelector('.ask-ai-container'); // Twój kontener w HTML
    if (!container) return;

    const button = document.createElement('button');
    button.className = 'new-chat-btn';
    button.innerHTML = `
    <svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" fill="white" viewBox="0 0 24 24">
    <path d="M12 2c1.1 0 2 .9 2 2h2v2h-1v2h-1V6h-4v2H9V6H8V4h2c0-1.1.9-2 2-2Zm-7 8h14v9c0 1.1-.9 2-2 2H7c-1.1 0-2-.9-2-2v-9Zm3 2v2h2v-2H8Zm6 0v2h2v-2h-2Z"/>
  </svg>
    ${translationsByLang[lang].askButton}
  `;
    container.appendChild(button);
  }
  renderAskButton();
  const newChatBtn = chatContainer.querySelector('.new-chat-btn');
  //koniec 'ask AI button'

  // wykrycie jezyka przegladarki, 'pl' domyslnie
  const userLang = navigator.language || navigator.userLanguage;
  function getSupportedLang(lang) {
    const shortLang = lang.slice(0, 2);
    const supported = ['pl', 'en', 'de'];
    return supported.includes(shortLang) ? shortLang : 'pl';
  }
  const selectedLang = getSupportedLang(userLang);

  // informacje z przyciskow na froncie-3 jezyki
  const suggestionsByLang = {
    pl: [
      { text: 'Jak to dziaBa?', aiPrompt: 'Wyt\u0142umacz u\u017cytkownikowi, jak dzia\u0142a system czatu AI.' +
        'Powiedz, \u017ce mo\u017cna zadawa\u0107 pytania dotycz\u0105ce nieruchomo\u015bci i \u017ce najlepiej podawa\u0107 sprecyzowane pytania, czyli z parametrami nieruchomo\u015bci, a AI odpowiada na podstawie swojej wiedzy uzyskanej z bazy ofert biura nieruchomo\u015bci.' +
        'Podkre\u015bl, \u017ce to inteligentne narz\u0119dzie wspieraj\u0105ce komunikacj\u0119 i pomoc."Poinformuj uzytkownika, \u017ce w ka\u017cd\u0065j chwili mo\u017ce poprosi\u0107 Agenta AI o t\u0142umaczenie odpowiedzi na j\u0119zyk angielski lub niemiecki.'
      },
      { text: 'Kontakt z biurem', aiPrompt: 'Podaj informacje, jak skontaktowa\u0107 si\u0119 z biurem. Biuro znajduje si\u0119 w Szczecinie, przy Alei Piast\u00f3w 64, telefon stacjonarny do biura: +48 91 433 59 85, email: arka@arka.szczecin.pl'
      },
    ],
    en: [
      { text: 'How does it work?', aiPrompt: 'Explain to the user how the AI chat system works. Say that they can ask questions about real estate and that it is best to provide specific questions, meaning with property parameters.' +
        'The AI responds based on knowledge obtained from the real estate agency\'s listing database. Emphasize that it is an intelligent tool that supports communication and assistance.Inform the user that at any time, they can ask the AI Agent to translate the response into English or German.'
      },
      { text: 'Contact the office', aiPrompt: 'Provide information on how to contact the office. The office is located in Szczecin, at Aleja Piastów 64. Landline phone: +48 91 433 59 85, email: arka@arka.szczecin.pl'
      },
    ],
    de: [
      { text: 'Wie funktioniert es?', aiPrompt: 'Erkl\u00e4re dem Benutzer, wie das KI-Chat-System funktioniert. Sage, dass man Fragen zu Immobilien stellen kann und dass es am besten ist, spezifische Fragen mit Immobilienparametern zu stellen.' +
        ' Die KI antwortet auf Grundlage ihres Wissens aus der Datenbank der Immobilienangebote des B\u00fcros. Betone, dass es sich um ein intelligentes Werkzeug handelt, das die Kommunikation und Hilfe unterst\u00fctzt. Informiere den Benutzer, dass er jederzeit den KI-Agenten bitten kann, die Antwort ins Englische oder Deutsche zu \u00fcbersetzen.'
      },
      { text: 'Kontakt zum Büro', aiPrompt: 'Gib Informationen dar\u00fcber, wie man das B\u00fcro kontaktieren kann. Das B\u00fcro befindet sich in Stettin, in der Aleja Piast\u00f3w 64. Festnetznummer: +48 91 433 59 85, E-Mail: arka@arka.szczecin.pl'
      },
    ],
  };
 // przyciski informacyjne powyzej - tutaj generowanie przyciskow
  function renderSuggestions() {
    const container = document.getElementById('suggestion-buttons');
    if (!container) return;
    const selectedLang = getSupportedLang(userLang);
    const suggestions = suggestionsByLang[selectedLang]; // U|yj tablicy dla danego kzyka
    suggestions.forEach((suggestion) => {
      const button = document.createElement('button');
      button.className = 'suggestion-btn';
      button.textContent = suggestion.text;
      button.addEventListener('click', async () => {
        //await sendMessage(suggestion.text); raczej przy suggestion niepotrzebne
        // ponizej uruchm odpowiedz na predefiniowane przyciski
        await startSuggestedConversation(suggestion.aiPrompt);
        await sendMessage(suggestion.aiPrompt, { showInChat: false });
      });
      container.appendChild(button);
    });
  }
  renderSuggestions();
  //koniec generowania przyciskow informacji-podpowiedzi

  async function startSuggestedConversation(promptText, options = {}) {
    // domyslnie nie pokazuj powitania przy suggestions
    const suppressWelcome = options.suppressWelcome || true;
    currentSessionId = generateUUID();

    const initPayload = [{
      action: "loadPreviousSession",
      sessionId: currentSessionId,
      route: config.webhook.route,
      metadata: {
        userId: ""
      }
    }];

    try {
      // Zainicjuj czat bez wiadomosci powitalnej
      const initResponse = await fetch(config.webhook.url, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(initPayload)
      });

      const responseData = await initResponse.json();

      chatContainer.querySelector('.brand-header').style.display = 'none';
      chatContainer.querySelector('.new-conversation').style.display = 'none';
      chatInterface.classList.add('active');

      // logika do usuniecia welcomeMessage
      if (!suppressWelcome) {
        const welcome = document.createElement('div');
        welcome.className = 'chat-message bot';
        welcome.textContent = userLang.startsWith('pl') ? 'Witaj! Jakiej nieruchomo[ci szukasz?' :
          userLang.startsWith('en') ? 'Hello! What kind of property are you looking for?' :
          'Hallo! Nach welcher Art von Immobilie suchen Sie?';
        messagesContainer.appendChild(welcome);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
      }

      renderTranslatedText();//for placeholder.....

      // bubble przy obsludze zapytania przez AI
      const typingBubble = showTypingIndicator(messagesContainer);

      const promptResponse = await fetch(config.webhook.url, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          prompt: promptText,
          lang: selectedLang,
          sessionId: currentSessionId
        })
      });

      const promptData = await promptResponse.json();
            console.log("Odpowiedz z backendu:", promptDataata);
      removeTypingIndicator(typingBubble);

      const botReply = document.createElement('div');
      botReply.className = 'chat-message bot';
      botReply.textContent = promptData.output || 'Brak odpowiedzi';
      messagesContainer.appendChild(botReply);
      messagesContainer.scrollTop = messagesContainer.scrollHeight;

    } catch (error) {
      console.error("Error in suggested conversation:", error);
    }
  }

  async function startNewConversation() {
    currentSessionId = generateUUID();
    const data = [{
      action: "loadPreviousSession",
      sessionId: currentSessionId,
      route: config.webhook.route,
      metadata: {
        userId: ""
      }
    }];
    // Funkcja do obslugi odpowiedzi
    async function handleBotResponse(promptText) {
      const typingBubble = showTypingIndicator(messagesContainer);

      const response = await fetch(config.webhook.url, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          prompt: promptText,
          lang: selectedLang,
          sessionId: currentSessionId
        })
      });

      const data = await response.json();
      removeTypingIndicator(typingBubble);
      const botBubble = document.createElement('div');
      botBubble.className = 'chat-message bot';
      botBubble.textContent = data.output || 'Brak odpowiedzi';
      messagesContainer.appendChild(botBubble);
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
    //koniec funkcji do obslugi odpowiedzi
    try {
      const response = await fetch(config.webhook.url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });

      const responseData = await response.json();
      chatContainer.querySelector('.brand-header').style.display = 'none';
      chatContainer.querySelector('.new-conversation').style.display = 'none';
      chatInterface.classList.add('active');

        const initialBotMessage = document.createElement('div');
        initialBotMessage.className = 'chat-message bot';
        initialBotMessage.textContent = 'Witaj! Jakiej nieruchomo\u015bci szukasz?';
          if (userLang.startsWith('pl')) {
            initialBotMessage.textContent = initialBotMessage.textContent;
          } else if (userLang.startsWith('en')) {
            initialBotMessage.textContent = 'Hello! What kind of property are you looking for?';
          } else if(userLang.startsWith('de')){
            initialBotMessage.textContent = 'Hallo! Nach welcher Art von Immobilie suchen Sie?';
        }
      messagesContainer.appendChild(initialBotMessage);
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
      renderTranslatedText();

    } catch (error) {
      console.error('Error:', error);
    }
  }

  async function sendMessage(message, options = {}) {
    const messageData = {
      action: "sendMessage",
      sessionId: currentSessionId,
      route: config.webhook.route,
      chatInput: message,
      metadata: {
        userId: ""
      }
    };

    //pokaz wiadomosc uzytkownika tylko jesli tylko showInChat !== false
    if (options.showInChat !== false) {
      const userMessageDiv = document.createElement('div');
      userMessageDiv.className = 'chat-message user';
      userMessageDiv.textContent = message;
      messagesContainer.appendChild(userMessageDiv);
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    function showTypingIndicator(container) {
      const typingBubble = document.createElement('div');
      typingBubble.className = 'chat-message bot typing';
      typingBubble.innerHTML = `
    <div class="typing-indicator">
      <span></span><span></span><span></span>
    </div>
  `;
      container.appendChild(typingBubble);
      container.scrollTop = container.scrollHeight;
      return typingBubble;
    }

    function removeTypingIndicator(indicatorElement) {
      if (indicatorElement && indicatorElement.parentNode) {
        indicatorElement.parentNode.removeChild(indicatorElement);
      }
    }

    const typing = showTypingIndicator(messagesContainer);
    try {
      const response = await fetch(config.webhook.url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(messageData)
      });

      const data = await response.json();
      removeTypingIndicator(typing);

      const botMessageDiv = document.createElement('div');
      botMessageDiv.className = 'chat-message bot';
      botMessageDiv.textContent = Array.isArray(data) ? data[0].output : data.output;
      messagesContainer.appendChild(botMessageDiv);
      messagesContainer.scrollTop = messagesContainer.scrollHeight;

    } catch (error) {
      console.error('Error:', error);
    }
  }

  newChatBtn.addEventListener('click', startNewConversation);

  sendButton.addEventListener('click', () => {
    const message = textarea.value.trim();
    if (message) {
      sendMessage(message);
      textarea.value = '';
    }
  });

  textarea.addEventListener('keypress', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      const message = textarea.value.trim();
      if (message) {
        sendMessage(message);
        textarea.value = '';
      }
    }
  });

  toggleButton.addEventListener('click', () => {
    chatContainer.classList.toggle('open');
  });

  // Add close button handlers
  const closeButtons = chatContainer.querySelectorAll('.close-button');
  closeButtons.forEach(button => {
    button.addEventListener('click', () => {
      chatContainer.classList.remove('open');
    });
  });
})();

<!-- Widget Configuration -->

<script>
  window.ChatWidgetConfig = {
    webhook: {
      url: 'http://localhost:5678/webhook/9c58a6d0-8254-4e94-9c39-3c20368a1143/chat',
      route: 'general'
    },
    branding: {
      logo: 'https://arka.szczecin.pl/wp-content/uploads/2023/12/Logo_Arka_Nieruchomosci.svg',
      name: 'ARKA Nieruchomo\u015bci Szczecin', // Your company name
      welcomeText: 'Znajdziemy dla Ciebie wymarzone miejsce do \u017cycia i biznesu', //Welcome message
      langFlags: '\u{1F1F5}\u{1F1F1} \u{1F1EC}\u{1F1E7} \u{1F1E9}\u{1F1EA}'
    },
    style: {
      primaryColor: '#10B981', //Primary color
      secondaryColor: '#1288A8', //Secondary color
      position: 'right', //Position of the widget (left or right)
      backgroundColor: '#ffffff', //Background color of the chat widget
      fontColor: '#333333' //Text color for messages and interface
    }
  };
</script>
<script src="_/theme/chat/n8n-chat.js"></script>