/**
 * Initializes the activity overview toggle interactions.
 *
 * @param {HTMLElement} container
 *   The dashboard root element.
 */
export default function initActivityOverview(container) {
  const wrappers = container.querySelectorAll("[data-no-activity-overview]");

  wrappers.forEach((wrapper) => {
    if (wrapper.dataset.activityOverviewReady === "true") {
      return;
    }

    const toggleButtons = wrapper.querySelectorAll("[data-no-activity-toggle]");
    const viewPanels = wrapper.querySelectorAll("[data-no-activity-view]");

    if (!toggleButtons.length || !viewPanels.length) {
      return;
    }

    const activateView = (targetView) => {
      wrapper.dataset.activeView = targetView;

      viewPanels.forEach((panel) => {
        const isActive =
          panel.getAttribute("data-no-activity-view") === targetView;
        panel.hidden = !isActive;
      });

      toggleButtons.forEach((button) => {
        const isActive =
          button.getAttribute("data-no-activity-toggle") === targetView;
        button.setAttribute("aria-pressed", isActive ? "true" : "false");
      });

      window.dispatchEvent(new Event("resize"));
    };

    toggleButtons.forEach((button) => {
      button.addEventListener("click", () => {
        activateView(button.getAttribute("data-no-activity-toggle"));
      });
    });

    const defaultButton =
      Array.from(toggleButtons).find(
        (button) => button.getAttribute("aria-pressed") === "true",
      ) || toggleButtons[0];

    activateView(defaultButton.getAttribute("data-no-activity-toggle"));
    wrapper.dataset.activityOverviewReady = "true";
  });
}
