"use client";

import { useEffect, useState } from "react";

/**
 * 计算浮动按钮为避让 <footer> 需要额外上推的像素数。
 *
 * 返回值 push (px):
 * - footer 未进视口 → 0,按钮保持原位
 * - footer 部分/完全在视口 → 等于 footer 顶部进入视口的深度 + gap,
 *   让按钮始终漂浮在 footer 顶部上方 gap 像素处
 *
 * 用法:
 *   const push = useFooterPush();
 *   <button style={{ transform: `translateY(-${push}px)` }} ... />
 *
 * 实现:scroll + resize 事件 + rAF 节流;比 IntersectionObserver 灵敏,
 * 能给出连续的 push 数值(IO 只能给二值)。
 */
export function useFooterPush(gap = 16): number {
  const [push, setPush] = useState(0);

  useEffect(() => {
    const footer = document.querySelector("footer");
    if (!footer) return;

    let raf = 0;
    const update = () => {
      const rect = footer.getBoundingClientRect();
      // overlap = footer 顶部进入视口的深度。footer 未入视口时为负数,clamp 到 0
      const overlap = window.innerHeight - rect.top + gap;
      setPush(Math.max(0, overlap));
    };

    const schedule = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        update();
        raf = 0;
      });
    };

    update();
    window.addEventListener("scroll", schedule, { passive: true });
    window.addEventListener("resize", schedule);
    return () => {
      window.removeEventListener("scroll", schedule);
      window.removeEventListener("resize", schedule);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [gap]);

  return push;
}
