import { useState, useEffect, RefObject } from 'react';

interface UseCrushLevelActionOptions {
  containerRef: RefObject<HTMLDivElement | null>;
  userHeaderRef: RefObject<HTMLDivElement | null>;
}

export function useCrushLevelAction({
  containerRef,
  userHeaderRef,
}: UseCrushLevelActionOptions) {
  const [showCrushLevelAction, setShowCrushLevelAction] = useState(false);

  // 监听滚动位置，控制CrushLevelAction显示
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleScroll = () => {
      if (!userHeaderRef.current) return;
      
      // 获取ChatMessageUserHeader的底部位置
      const headerRect = userHeaderRef.current.getBoundingClientRect();
      const containerRect = container.getBoundingClientRect();
      
      // 计算header相对于容器的位置
      const headerBottomRelativeToContainer = headerRect.bottom - containerRect.top;
      
      // 如果header已经滚动出视野（header底部位置小于等于100），显示CrushLevelAction
      const shouldShow = headerBottomRelativeToContainer <= 100;
      
      if (shouldShow !== showCrushLevelAction) {
        setShowCrushLevelAction(shouldShow);
        if (process.env.NODE_ENV === 'development') {
          console.log('💫 CrushLevelAction显示状态:', shouldShow, '头部位置:', headerBottomRelativeToContainer);
        }
      }
    };

    // 添加滚动监听器
    container.addEventListener('scroll', handleScroll, { passive: true });
    
    // 初始检查
    handleScroll();

    return () => {
      container.removeEventListener('scroll', handleScroll);
    };
  }, [containerRef, userHeaderRef, showCrushLevelAction]);

  return {
    showCrushLevelAction,
  };
}
