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

import { useEffect, useRef, useState } from "react";
import type { CSSProperties, ReactNode } from "react";
import { observer } from "mobx-react";
// plane imports
import { Row } from "@plane/ui";
// components
import { cn } from "@plane/utils";
import { ExtendedAppHeader } from "@/plane-web/components/common/extended-app-header";

export interface AppHeaderProps {
  header: ReactNode;
  mobileHeader?: ReactNode;
  className?: string;
  rowClassName?: string;
}

export const AppHeader = observer(function AppHeader(props: AppHeaderProps) {
  const { header, mobileHeader, className, rowClassName } = props;
  const containerRef = useRef<HTMLDivElement>(null);
  const [dockStyle, setDockStyle] = useState<CSSProperties | undefined>(undefined);

  useEffect(() => {
    if (typeof window === "undefined") return;

    const container = containerRef.current;
    const main = container?.closest("main");
    if (!(main instanceof HTMLElement)) return;

    const updateDockBounds = () => {
      const { left, width } = main.getBoundingClientRect();

      setDockStyle({
        left,
        width,
      });
    };

    updateDockBounds();

    const resizeObserver = new ResizeObserver(updateDockBounds);
    resizeObserver.observe(main);
    window.addEventListener("resize", updateDockBounds);

    return () => {
      resizeObserver.disconnect();
      window.removeEventListener("resize", updateDockBounds);
    };
  }, []);

  return (
    <div ref={containerRef} className={cn("fixed right-0 bottom-0 z-[18]", className)} style={dockStyle}>
      <Row className={cn("nodedc-bottom-dock flex h-11 w-full items-center gap-2", rowClassName)}>
        <ExtendedAppHeader header={header} />
      </Row>
      {mobileHeader && mobileHeader}
    </div>
  );
});
