(function () {
  function initAdminChat(root) {
    const chatEndpoint = root.dataset.chatEndpoint;
    const resetEndpoint = root.dataset.resetEndpoint;
    const businessModeAvailable = root.dataset.businessModeAvailable === "true";
    const stringsNode = document.getElementById("ai-admin-chat-strings");
    const strings = stringsNode ? JSON.parse(stringsNode.textContent) : {};
    const form = root.querySelector("[data-ai-admin-chat-form]");
    const input = root.querySelector("[data-ai-admin-chat-input]");
    const submitButton = root.querySelector("[data-ai-admin-chat-submit]");
    const messages = root.querySelector("[data-ai-admin-chat-messages]");
    const emptyState = root.querySelector("[data-ai-admin-chat-empty]");
    const typing = root.querySelector("[data-ai-admin-chat-typing]");
    const errorBox = root.querySelector("[data-ai-admin-chat-error]");
    const errorText = root.querySelector("[data-ai-admin-chat-error-text]");
    const retryButton = root.querySelector("[data-ai-admin-chat-retry]");
    const resetButton = root.querySelector("[data-ai-admin-chat-reset]");
    const counter = root.querySelector("[data-ai-admin-chat-counter]");
    const businessModeToggle = root.querySelector("[data-ai-admin-business-mode]");
    const maxLength = 4000;

    if (!form || !input || !submitButton || !messages || !emptyState || !typing) {
      return;
    }

    let sessionId = null;
    let retryPayload = null;
    let isSending = false;

    function getCookie(name) {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      if (parts.length === 2) {
        return parts.pop().split(";").shift();
      }
      return "";
    }

    function setEmptyStateVisible(visible) {
      emptyState.hidden = !visible;
    }

    function scrollToBottom() {
      messages.scrollTop = messages.scrollHeight;
    }

    function setTypingVisible(visible) {
      typing.hidden = !visible;
      if (visible) {
        scrollToBottom();
      }
    }

    function setError(message, retryable) {
      if (!message) {
        errorBox.hidden = true;
        errorText.textContent = "";
        retryButton.hidden = true;
        return;
      }

      errorText.textContent = message;
      retryButton.hidden = !retryable;
      errorBox.hidden = false;
    }

    function setSubmittingState(active) {
      isSending = active;
      input.disabled = active;
      submitButton.disabled = active;
      submitButton.querySelector("[data-ai-admin-chat-submit-text]").textContent = active
        ? strings.sending
        : strings.send;
      setTypingVisible(active);
    }

    function renderBubble(role, text, options) {
      const isAssistant = role === "assistant";
      const row = document.createElement("div");
      row.className = `ai-assistant-admin__bubble-row ai-assistant-admin__bubble-row--${isAssistant ? "assistant" : "user"}`;

      const bubble = document.createElement("div");
      bubble.className = `ai-assistant-admin__bubble ai-assistant-admin__bubble--${isAssistant ? "assistant" : "user"}`;

      const label = document.createElement("div");
      label.className = "ai-assistant-admin__bubble-label";
      label.textContent = isAssistant
        ? strings.assistantLabel
        : strings.userLabel;

      const content = document.createElement("div");
      content.className = "ai-assistant-admin__bubble-content";
      content.textContent = text;

      bubble.appendChild(label);
      bubble.appendChild(content);

      if (isAssistant && options && options.copyable) {
        const actions = document.createElement("div");
        actions.className = "ai-assistant-admin__bubble-actions";

        const copyButton = document.createElement("button");
        copyButton.type = "button";
        copyButton.className = "button button-small button-secondary";
        copyButton.textContent = strings.copy;
        copyButton.setAttribute("aria-label", strings.copyAriaLabel);
        copyButton.addEventListener("click", async function () {
          try {
            await navigator.clipboard.writeText(text);
            copyButton.textContent = strings.copied;
            window.setTimeout(function () {
              copyButton.textContent = strings.copy;
            }, 1600);
          } catch (error) {
            copyButton.textContent = strings.unavailable;
            window.setTimeout(function () {
              copyButton.textContent = strings.copy;
            }, 1600);
          }
        });

        actions.appendChild(copyButton);
        bubble.appendChild(actions);
      }

      row.appendChild(bubble);
      messages.appendChild(row);
      setEmptyStateVisible(false);
      scrollToBottom();
    }

    function updateCounter() {
      counter.textContent = `${input.value.length} / ${maxLength}`;
    }

    function clearConversationUi() {
      messages.replaceChildren();
      messages.appendChild(emptyState);
      setEmptyStateVisible(true);
      setError("", false);
      retryPayload = null;
      sessionId = null;
    }

    function buildPayload(message) {
      const payload = {
        message: message,
        session_id: sessionId,
        path: window.location.pathname
      };
      if (businessModeAvailable && businessModeToggle && businessModeToggle.checked) {
        payload.business_mode = true;
      }
      return payload;
    }

    function mapErrorMessage(payload) {
      if (!payload || !payload.error) {
        return strings.genericError;
      }
      if (payload.error === "message_required") {
        return strings.emptyMessageError;
      }
      if (payload.error === "message_too_long") {
        return strings.tooLongError;
      }
      if (payload.error === "admin_assistant_disabled") {
        return strings.disabledError;
      }
      if (payload.error === "rate_limited") {
        return strings.rateLimitedError.replace(
          "{retry_after}",
          String(payload.retry_after || "")
        );
      }
      return strings.requestError;
    }

    async function postJson(url, payload) {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRFToken": getCookie("csrftoken")
        },
        body: JSON.stringify(payload)
      });

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

    async function sendMessage(payload) {
      setError("", false);
      setSubmittingState(true);

      try {
        const result = await postJson(chatEndpoint, payload);
        if (!result.response.ok) {
          retryPayload = payload;
          setError(mapErrorMessage(result.data), true);
          return false;
        }

        sessionId = result.data.session_id;
        renderBubble("assistant", result.data.message.content, { copyable: true });
        retryPayload = null;
        return true;
      } catch (error) {
        retryPayload = payload;
        setError(strings.networkError, true);
        return false;
      } finally {
        setSubmittingState(false);
        input.disabled = false;
        input.focus();
      }
    }

    form.addEventListener("submit", async function (event) {
      event.preventDefault();
      if (isSending) {
        return;
      }

      const message = (input.value || "").trim();
      if (!message) {
        setError(strings.emptyMessageError, false);
        input.focus();
        return;
      }

      const payload = buildPayload(message);
      renderBubble("user", message, {});
      input.value = "";
      updateCounter();

      const success = await sendMessage(payload);
      if (!success) {
        input.value = message;
        updateCounter();
      }
    });

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

    input.addEventListener("input", updateCounter);

    retryButton.addEventListener("click", async function () {
      if (!retryPayload || isSending) {
        return;
      }
      await sendMessage(retryPayload);
    });

    resetButton.addEventListener("click", async function () {
      if (isSending) {
        return;
      }

      const payload = { session_id: sessionId };
      clearConversationUi();

      try {
        await postJson(resetEndpoint, payload);
      } catch (error) {
        setError(strings.resetConfirmError, false);
      }

      input.focus();
    });

    updateCounter();
  }

  document.addEventListener("DOMContentLoaded", function () {
    const root = document.querySelector("[data-ai-admin-chat-root]");
    if (root) {
      initAdminChat(root);
    }
  });
})();
