"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ChevronLeft } from "lucide-react";
import { cn } from "@/lib/cn";
import { useFooterPush } from "@/hooks/useFooterPush";

interface FloatingBackButtonProps {
  /** 显示前的滚动阈值(px),默认 300 与投票按钮一致 */
  threshold?: number;
  /** 备用 href:历史栈为空时(直接进入详情页)回退到该地址 */
  fallbackHref?: string;
  className?: string;
}

/**
 * 左下角浮动返回按钮。
 * - 用户滚到第一屏以下才显示,避免与顶部面包屑视觉冗余
 * - 优先用 router.back() 回到浏览器历史的上一页(会触发上页 scroll restore)
 * - 检测 sessionStorage 标记:如果是直接打开/刷新本页,history.back() 不安全,改用 fallbackHref
 * - 玻璃化样式,与导航栏吸顶后的玻璃配方对齐
 */
export default function FloatingBackButton({
  threshold = 300,
  fallbackHref = "/",
  className,
}: FloatingBackButtonProps) {
  const router = useRouter();
  const [visible, setVisible] = useState(false);
  const [hasInternalHistory, setHasInternalHistory] = useState(false);
  // footer 进视口时按钮向上平移,始终漂浮在 footer 顶部上方
  const footerPush = useFooterPush();

  useEffect(() => {
    // Navigation 组件每次路由变化会把 nav:count +1。
    // count > 1 → 当前会话内已经经过至少一次跳转,router.back() 安全。
    // count <= 1 → 直接打开/刷新本页,history 栈外是站外,改用 fallbackHref。
    const count = parseInt(sessionStorage.getItem("nav:count") || "0", 10);
    setHasInternalHistory(count > 1);

    const handler = () => setVisible(window.scrollY > threshold);
    handler();
    window.addEventListener("scroll", handler, { passive: true });
    return () => window.removeEventListener("scroll", handler);
  }, [threshold]);

  const goBack = () => {
    if (hasInternalHistory) {
      router.back();
    } else {
      router.push(fallbackHref);
    }
  };

  return (
    <button
      type="button"
      onClick={goBack}
      aria-label="返回上一页"
      style={{
        // 隐藏态:下移 12px;显示态:基础位置 - footerPush(避让 footer)
        transform: visible
          ? `translateY(-${footerPush}px)`
          : "translateY(12px)",
      }}
      className={cn(
        "fixed bottom-6 left-6 sm:bottom-8 sm:left-8 z-40 w-14 h-14 rounded-full",
        "bg-surface/55 backdrop-blur-xl backdrop-saturate-150 border border-white/[0.08]",
        "shadow-[0_8px_28px_rgba(0,0,0,0.55)] text-white/85 hover:text-white hover:bg-surface/75",
        "flex items-center justify-center transition-all duration-300",
        visible ? "opacity-100 pointer-events-auto" : "opacity-0 pointer-events-none",
        "hover:scale-105 active:scale-95",
        className,
      )}
    >
      <ChevronLeft size={22} strokeWidth={2.2} />
    </button>
  );
}
