document.addEventListener("DOMContentLoaded", function () {
  const btn = document.getElementById("webita-chat-icon");
  const box = document.getElementById("webita-chat-container");
  const messages = document.getElementById("webita-chat-messages");
  const input = document.getElementById("webita-chat-input");
  const sendBtn = document.getElementById("webita-chat-send");
  const closeBtn = document.getElementById("webita-chat-close");

  if (!btn || !box || !messages || !input || !sendBtn || !closeBtn) {
    return;
  }

  const config = window.webitaChatConfig || {};
  const strings = config.strings || {};
  let welcomeMessageAdded = false;

  function openChat() {
    box.style.display = "flex";
    btn.style.display = "none";
    btn.setAttribute("aria-expanded", "true");
    box.setAttribute("aria-hidden", "false");
    if (!welcomeMessageAdded && config.welcomeMessage) {
      appendMessage(config.welcomeMessage, false);
      welcomeMessageAdded = true;
    }
    input.focus();
    messages.scrollTop = messages.scrollHeight;
  }

  function closeChat() {
    box.style.display = "none";
    btn.style.display = "flex";
    btn.setAttribute("aria-expanded", "false");
    box.setAttribute("aria-hidden", "true");
    btn.focus();
  }

  function buildMessageContent(text) {
    const fragment = document.createDocumentFragment();
    const safeText = text == null ? "" : String(text);
    const urlRegex = /(https?:\/\/[^\s<]+|www\.[^\s<]+)/gi;
    const lines = safeText.split(/\r?\n/);

    lines.forEach((line, lineIndex) => {
      let lastIndex = 0;
      for (const match of line.matchAll(urlRegex)) {
        const start = match.index ?? 0;
        if (start > lastIndex) {
          fragment.appendChild(document.createTextNode(line.slice(lastIndex, start)));
        }

        let rawUrl = match[0];
        let trailing = "";
        while (rawUrl.length > 0 && /[),.!?]$/.test(rawUrl)) {
          trailing = rawUrl.slice(-1) + trailing;
          rawUrl = rawUrl.slice(0, -1);
        }

        if (rawUrl.length > 0) {
          const link = document.createElement("a");
          link.href = /^www\./i.test(rawUrl) ? `https://${rawUrl}` : rawUrl;
          link.textContent = rawUrl;
          link.target = "_blank";
          link.rel = "noopener noreferrer nofollow";
          fragment.appendChild(link);
        }

        if (trailing) {
          fragment.appendChild(document.createTextNode(trailing));
        }

        lastIndex = start + match[0].length;
      }

      if (lastIndex < line.length) {
        fragment.appendChild(document.createTextNode(line.slice(lastIndex)));
      }

      if (lineIndex < lines.length - 1) {
        fragment.appendChild(document.createElement("br"));
      }
    });

    return fragment;
  }

  function appendMessage(text, isUser) {
    removeThinkingIndicator();

    const messageDiv = document.createElement("div");
    messageDiv.className = `message ${isUser ? "user" : "bot"}`;

    const bubbleDiv = document.createElement("div");
    bubbleDiv.className = "message-content";
    bubbleDiv.appendChild(buildMessageContent(text));

    messageDiv.appendChild(bubbleDiv);
    messages.appendChild(messageDiv);
    messages.scrollTop = messages.scrollHeight;
  }

  function addThinkingIndicator() {
    if (messages.querySelector("#webita-chat-thinking")) {
      return;
    }

    const thinkingDiv = document.createElement("div");
    thinkingDiv.className = "thinking-cloud";
    thinkingDiv.id = "webita-chat-thinking";
    thinkingDiv.innerHTML =
      '<span class="cloud-icon"><span class="dots"><span class="dot"></span><span class="dot"></span><span class="dot"></span></span></span>';
    messages.appendChild(thinkingDiv);
    messages.scrollTop = messages.scrollHeight;
  }

  function removeThinkingIndicator() {
    const thinkingIndicator = messages.querySelector("#webita-chat-thinking");
    if (thinkingIndicator) {
      thinkingIndicator.remove();
    }
  }

  function adjustInputHeight() {
    input.style.height = "auto";
    input.style.height = `${Math.min(input.scrollHeight, 100)}px`;
    input.style.overflowY = input.scrollHeight > 100 ? "auto" : "hidden";
  }

  async function sendMessage() {
    const message = input.value.trim();
    if (!message) {
      return;
    }

    appendMessage(message, true);
    input.value = "";
    adjustInputHeight();
    input.disabled = true;
    sendBtn.disabled = true;
    addThinkingIndicator();

    try {
      const body = new URLSearchParams({
        action: "webita_chat_send_message",
        nonce: config.nonce || "",
        message
      });

      const response = await fetch(config.ajaxurl || "/wp-admin/admin-ajax.php", {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
        },
        body: body.toString()
      });

      let data = {};
      try {
        data = await response.json();
      } catch (error) {
        data = {};
      }

      if (!response.ok || !data.success) {
        throw new Error((data.data && data.data.message) || strings.genericError || "");
      }

      appendMessage((data.data && data.data.message) || strings.emptyReply || "", false);
    } catch (error) {
      console.error("Webita Chat AJAX error:", error);
      appendMessage(error.message || strings.networkError || "", false);
    } finally {
      removeThinkingIndicator();
      input.disabled = false;
      sendBtn.disabled = false;
      input.focus();
    }
  }

  btn.addEventListener("click", openChat);
  closeBtn.addEventListener("click", closeChat);
  sendBtn.addEventListener("click", sendMessage);

  input.addEventListener("input", adjustInputHeight);
  input.addEventListener("keydown", function (event) {
    if (event.key === "Enter" && !event.shiftKey) {
      event.preventDefault();
      sendMessage();
    }
  });

  box.addEventListener("keydown", function (event) {
    if (event.key === "Escape") {
      closeChat();
    }
  });

  if (typeof config.inputPlaceholder === "string" && config.inputPlaceholder.trim() !== "") {
    input.placeholder = config.inputPlaceholder;
  }

  messages.addEventListener("click", function (event) {
    const target = event.target;
    if (!(target instanceof Element)) {
      return;
    }

    const link = target.closest("a");
    if (!link) {
      return;
    }

    event.preventDefault();
    window.open(link.href, "_blank", "noopener");
  });

  adjustInputHeight();
});
