(function () {
  const { chatbotId, domain } =
    window.chatpilotIframeConfig || window.newoaksIframeConfig || {};
  if (!chatbotId) {
    console.error(
      'Unable to find chat iframe configuration: window.chatpilotIframeConfig.chatbotId'
    );
  }
  const apiHost = `${domain || 'https://api.newoaks.ai'}/chat`;
  const chatbotsMemoryKey = 'NEWOAKS_CHATBOTS_STORE';
  const chatbotsSessionIdKey = 'NEWOAKS_CHATBOTS_IFRAME_SESSION_ID';

  function getCurrentTime() {
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = ('0' + (currentDate.getMonth() + 1)).slice(-2); // 月份从 0 开始,需要加 1
    const day = ('0' + currentDate.getDate()).slice(-2);
    const hours = ('0' + currentDate.getHours()).slice(-2);
    const minutes = ('0' + currentDate.getMinutes()).slice(-2);
    const seconds = ('0' + currentDate.getSeconds()).slice(-2);
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return formattedDate;
  }

  // get chatbot config
  (async function () {
    const currentChatbot = (window[chatbotsMemoryKey] ?? {})[chatbotId];
    if (currentChatbot || !chatbotId) {
      return null;
    }
    const result = await fetch(apiHost + '/Chatbot/GetConfig', {
      method: 'POST',
      body: JSON.stringify({
        serialNumber: chatbotId,
        clientTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        clientCurrentTime: getCurrentTime()
      }),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        ['X-Referer']: location.host,
        ReferrerInfo:
          typeof window !== 'undefined'
            ? JSON.stringify({
                url: window.location.href,
                agent: navigator.userAgent
              })
            : ''
      }
    });
    const data = await result.json();
    if (data.Code === 200) {
      const config = data.Data;
      window[chatbotsMemoryKey] = {
        ...(window[chatbotsMemoryKey] ?? {}),
        [chatbotId]: config
      };
      const localSessionIDs = JSON.parse(
        localStorage.getItem(chatbotsSessionIdKey) || '{}'
      );
      localStorage.setItem(
        chatbotsSessionIdKey,
        JSON.stringify({
          ...localSessionIDs,
          [chatbotId]: localSessionIDs[chatbotId] || config.SessionID
        })
      );
    } else {
      alert(data.Message);
    }
  })();

  window.addEventListener(
    'message',
    (e) => {
      if (e.data === 'init-chatbot-iframe') {
        const currentChatbot = (window[chatbotsMemoryKey] ?? {})[chatbotId];
        document.getElementById('chatbot-iframe').contentWindow.postMessage(
          'config:' +
            JSON.stringify({
              ...currentChatbot,
              SessionID:
                JSON.parse(localStorage.getItem(chatbotsSessionIdKey) || '{}')[
                  chatbotId
                ] || currentChatbot.SessionID
            }),
          '*'
        );
      }
    },
    false
  );
})();