"use client";

import { useLayoutEffect, useRef } from "react";

import type { PlayerTopBannerKind } from "@/stores/player-top-banner-store";
import { usePlayerTopBannerStore } from "@/stores/player-top-banner-store";

/** 测量顶栏横幅高度，供 PlayerPanel sticky offset 使用 */
export function usePlayerBannerHeightRef(kind: PlayerTopBannerKind) {
  const setBannerHeight = usePlayerTopBannerStore((state) => state.setBannerHeight);
  const ref = useRef<HTMLDivElement>(null);

  useLayoutEffect(() => {
    const element = ref.current;
    if (!element) {
      return;
    }

    const sync = () => {
      setBannerHeight(kind, element.offsetHeight);
    };

    sync();
    const observer = new ResizeObserver(sync);
    observer.observe(element);

    return () => {
      observer.disconnect();
      setBannerHeight(kind, 0);
    };
  }, [kind, setBannerHeight]);

  return ref;
}
