document.addEventListener("DOMContentLoaded", function () {
  if (typeof NaviaiprChat === "undefined") {
    return;
  }

  const naviaipr_history =
    JSON.parse(localStorage.getItem("naviaipr_history")) || [];
  const historyArr = naviaipr_history;

  const setHistoryLocalStorage = () => {
    localStorage.setItem("naviaipr_history", JSON.stringify(historyArr));
  };
  const restUrl = NaviaiprChat.rest_url;
  const chat_layout = NaviaiprChat.chat_layout;
  const apiNonce = NaviaiprChat.api_nonce;

  const bubble = document.createElement("button");
  bubble.style.backgroundImage = `url(${NaviaiprChat.bubble_image})`;
  bubble.className = "pb-gpt-bubble";
  document.body.appendChild(bubble);

  const panel = document.createElement("div");
  panel.className = "pb-gpt-panel";
  panel.style.display = "none";
  panel.innerHTML =
    '<div class=\"pb-gpt-header\"><div class=\"pb-gpt-row\"><div class=\"pb-gpt-header-heading\"><p>Ask product helper \u2728</p></div><div class=\"pb-gpt-header-bug-icon\">\u2922</div></div></div><div class=\"pb-gpt-messages\" id=\"pbMessages\"></div><div class=\"pb-input-wrap\"><input class=\"pb-input\" id=\"pbInput\" placeholder=\"Search: protein, pre-workout under $60...\" /><button class=\"pb-send\" id=\"pbSend\">Search</button></div>';
  document.body.appendChild(panel);

  const pbMainMsg = document.querySelector("#pbMessages");

  bubble.addEventListener("click", function () {
    panel.style.display = panel.style.display === "none" ? "block" : "none";
    pbMainMsg.scrollTop = pbMainMsg.scrollHeight;
  });

  document.getElementById("pbSend").addEventListener("click", sendMessage);
  document.getElementById("pbInput").addEventListener("keydown", function (e) {
    if (e.key === "Enter") sendMessage();
  });

  const bugIcon = document.querySelector(".pb-gpt-header-bug-icon");
  if (bugIcon && panel) {
    bugIcon.addEventListener("click", function () {
      panel.classList.toggle("full_active");
    });
  }

  function addMessage(text, who = "bot", html = false) {
    const wrap = document.getElementById("pbMessages");
    const div = document.createElement("div");
    div.className = "pb-msg " + (who === "user" ? "user" : "bot");
    html ? (div.innerHTML = text) : (div.innerText = text);
    wrap.appendChild(div);
    wrap.scrollTop = wrap.scrollHeight;
  }

  if (naviaipr_history.length > 0) {
    naviaipr_history.forEach(({ msg, who, html }) => {
      addMessage(msg, who, html);
    });
  }

  const naviaipr_isGreeted = JSON.parse(
    localStorage.getItem("naviaipr_isGreeted"),
  );
  if (!naviaipr_isGreeted) {
    localStorage.setItem("naviaipr_isGreeted", true);
    const greetingHtml = NaviaiprChat.greeting_msg;
    addMessage(greetingHtml, "bot", true);
    historyArr.push({ msg: greetingHtml, who: "bot", html: true });
    setHistoryLocalStorage();
  }

  async function sendMessage() {
    const input = document.getElementById("pbInput");
    const text = input.value.trim();
    if (!text) return;

    historyArr.push({ msg: text, who: "user", html: false });
    addMessage(text, "user");
    input.value = "";
    addMessage("Searching products...", "bot");

    let replyMsgObj = { msg: "", who: "bot", html: false };

    try {
      const res = await fetch(restUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-WP-Nonce": apiNonce,
        },
        body: JSON.stringify({ message: text }),
      });
      const data = await res.json();
      const bots = document.querySelectorAll(".pb-msg.bot");
      if (bots.length) bots[bots.length - 1].remove();

      if (data.reply_html) {
        replyMsgObj.msg = data.reply_html;
        replyMsgObj.html = true;
      } else {
        replyMsgObj.msg = data.reply || "No reply";
      }
    } catch (err) {
      replyMsgObj.msg = "Error: " + err.message;
    }

    addMessage(replyMsgObj.msg, replyMsgObj.who, replyMsgObj.html);
    historyArr.push(replyMsgObj);
    setHistoryLocalStorage();
  }

  document.addEventListener("click", function (e) {
    const span = e.target.closest(".pb-msg.bot span");
    if (!span) return;
    const value = span.textContent.trim();
    const input = document.querySelector(".pb-input");
    if (input) {
      input.value = value;
      input.focus();
    }
  });
});
