import { shellApi } from "../../../api/api";
import { BROKER_EVENTS } from "../../../api/broker/broker-events";
import { renderNavigationTooltip } from "./navigation-tooltip";

const scrollToNavItem = (
  navItemMenuKey: string,
): Promise<{ scrollTop: number; containerTop: number; itemIndex: number; itemAbsoluteY: number }> => {
  return new Promise((resolve) => {
    const subscription = shellApi.broker.subscribe(
      BROKER_EVENTS.shell.scrollToNavItemCompleted,
      (data: { scrollTop: number; containerTop: number; itemIndex: number; itemAbsoluteY: number }) => {
        subscription.dispose();
        resolve(data);
      },
    );

    shellApi.broker.publish(BROKER_EVENTS.shell.scrollToNavItemRequested, navItemMenuKey);

    // Fallback timeout in case the event doesn't arrive
    setTimeout(() => {
      subscription.dispose();
      resolve({ scrollTop: 0, containerTop: 0, itemIndex: -1, itemAbsoluteY: window.innerHeight / 2 });
    }, 1000);
  });
};

export const showNavItemTooltip = async (navItemMenuKey: string, text: string) => {
  const scrollData = await scrollToNavItem(navItemMenuKey);

  renderNavigationTooltip(text, scrollData.itemAbsoluteY);
};
