import { Crisp } from "crisp-sdk-web";

const CRISP_HIDDEN_STYLE_ID = "crisp-hide-override";
const ANIMATION_DURATION_MS = 300;

let initialized = false;

/**
 * Initialize Crisp and immediately hide the default chat button.
 * Call this once on app load (e.g., in UserWrapper after user data is ready).
 */
export function initCrisp(opts: {
  websiteId: string;
  email?: string;
  nickname?: string;
  phone?: string;
  tokenId?: string;
}) {
  if (initialized) return;

  Crisp.configure(opts.websiteId);
  Crisp.session.reset();

  if (opts.email) Crisp.user.setEmail(opts.email);
  if (opts.nickname) Crisp.user.setNickname(opts.nickname);
  if (opts.phone) Crisp.user.setPhone(opts.phone);
  if (opts.tokenId) Crisp.setTokenId(opts.tokenId);

  initialized = true;

  // Hide the chat button off-screen
  injectCrispStyles();

  // Auto-hide when the user closes the chat
  Crisp.chat.onChatClosed(() => {
    hideCrispChatButton();
  });
}

/**
 * Inject base styles that keep Crisp hidden until we want it.
 * Uses opacity + visibility so Crisp keeps its default bottom-right positioning.
 */
function injectCrispStyles() {
  let style = document.getElementById(CRISP_HIDDEN_STYLE_ID);
  if (!style) {
    style = document.createElement("style");
    style.id = CRISP_HIDDEN_STYLE_ID;
    document.head.appendChild(style);
  }

  style.textContent = `
    #crisp-chatbox {
      z-index: 99999 !important;
      transition: opacity ${ANIMATION_DURATION_MS}ms ease-in-out,
                  visibility ${ANIMATION_DURATION_MS}ms ease-in-out !important;
      opacity: 0 !important;
      visibility: hidden !important;
      pointer-events: none !important;
    }
    #crisp-chatbox.crisp-visible {
      opacity: 1 !important;
      visibility: visible !important;
      pointer-events: auto !important;
    }
  `;
}

/**
 * Show the Crisp widget and open the chat window.
 * Safe to call from any onClick handler.
 */
export function openCrispChat() {
  const chatbox = document.getElementById("crisp-chatbox");
  if (chatbox) {
    chatbox.classList.add("crisp-visible");
    setTimeout(() => {
      Crisp.chat.open();
    }, ANIMATION_DURATION_MS);
  } else {
    Crisp.chat.open();
  }
}

/**
 * Close the chat window and hide the widget.
 */
export function closeCrispChat() {
  Crisp.chat.close();
  hideCrispChatButton();
}

/**
 * Show the default Crisp button without opening the chat.
 */
export function showCrispButton() {
  const chatbox = document.getElementById("crisp-chatbox");
  if (chatbox) {
    chatbox.classList.add("crisp-visible");
  }
}

/**
 * Hide the default Crisp button.
 */
export function hideCrispChatButton() {
  const chatbox = document.getElementById("crisp-chatbox");
  if (chatbox) {
    chatbox.classList.remove("crisp-visible");
  }
}