"use client";

/**
 * Copyright (c) 2023-present Plane Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import { useEffect, useState } from "react";
import type { ReactNode } from "react";
import { createPortal } from "react-dom";
import { observer } from "mobx-react";
import { Breadcrumbs } from "@plane/ui";
import { useUserProfile } from "@/hooks/store/user";

type TExpandedToolbarBreadcrumbsProps = {
  children: ReactNode;
  isLoading?: boolean;
  onBack?: () => void;
};

export const ExpandedToolbarBreadcrumbs = observer(function ExpandedToolbarBreadcrumbs(
  props: TExpandedToolbarBreadcrumbsProps
) {
  const { children, isLoading = false, onBack } = props;
  const { data: userProfile } = useUserProfile();
  const [target, setTarget] = useState<HTMLElement | null>(null);

  const isCompactToolbar = userProfile?.theme?.nodedcCompactToolbar === true;

  useEffect(() => {
    if (isCompactToolbar || typeof document === "undefined") {
      setTarget(null);
      return;
    }

    const animationFrame = window.requestAnimationFrame(() => {
      setTarget(document.querySelector<HTMLElement>("[data-nodedc-expanded-breadcrumbs-slot]"));
    });

    return () => window.cancelAnimationFrame(animationFrame);
  }, [isCompactToolbar]);

  const content = (
    <div className="flex min-w-0 items-center gap-2.5 overflow-visible">
      <Breadcrumbs
        onBack={onBack}
        isLoading={isLoading}
        className={isCompactToolbar ? "flex-grow-0" : "nodedc-expanded-breadcrumbs flex-grow-0"}
      >
        {children}
      </Breadcrumbs>
    </div>
  );

  if (!isCompactToolbar && target) return createPortal(content, target);

  return content;
});
