import initializeListeners from "../handlers/initializeListeners";
import createBubbleHtml from "../html/bubble";
import createWidgetHtml from "../html/widget";
import loadProducts from "./products/loadProducts";
import initializeCounter from "./timer/counter";
import {
  getSessionStorage,
  setSessionStorage,
} from "../service/sessionStorage";

export default function renderWidgetWithBubble(
  shadowRoot,
  config,
  theme,
  content
) {
  const containerDiv = document.createElement("div");
  const containerName = "firevert-widget-container";
  containerDiv.classList.add(containerName);

  const { type, position, expandOnMobile } = config;

  const isBubbleOpen = getSessionStorage("firevert-bubble-open");

  if (!isBubbleOpen) {
    setSessionStorage("firevert-bubble-open", false);
  }

  containerDiv.innerHTML = `
    ${createBubbleHtml(theme, position)}
    ${createWidgetHtml(theme, content, type, config)}
  `;

  shadowRoot.innerHTML = "";
  shadowRoot.appendChild(containerDiv);

  const productsTab = content.powerwidget.tabs.productsTab;

  loadProducts(shadowRoot, productsTab.products, theme);

  initializeCounter(shadowRoot, config);

  const containerElement = shadowRoot.querySelector(`.${containerName}`);

  const paginationState = {
    currentPage: productsTab.pagination.currentPage,
    totalPages: productsTab.pagination.totalPages,
    hasMore: productsTab.pagination.hasMore,
  };

  initializeListeners(
    containerElement,
    shadowRoot,
    theme,
    paginationState,
    expandOnMobile
  );
}
