"use client";

import { WifiOff, RefreshCw } from "lucide-react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";

import { usePlayerBannerHeightRef } from "@/hooks/use-player-banner-height-ref";
import { playerContentColumnClass } from "@/lib/player-viewport";
import { useErrorStore, ERROR_COLORS } from "@/stores/error-store";
import { cn } from "@/lib/utils";

/**
 * 网络断开状态横幅组件
 * 当浏览器检测到离线状态 (navigator.onLine === false) 时显示
 * 使用错误颜色 #ff4d4f (红色)
 */
export function OfflineBanner(): React.ReactElement | null {
  const isOffline = useErrorStore((state) => state.isOffline);
  const bannerRef = usePlayerBannerHeightRef("offline");
  const { t } = useTranslation("player");

  const handleReconnect = useCallback(() => {
    // 尝试重新加载页面
    if (typeof window !== "undefined") {
      window.location.reload();
    }
  }, []);

  // 在线时不显示
  if (!isOffline) {
    return null;
  }

  return (
    <div ref={bannerRef} className="sticky top-0 z-[60] w-full">
      <div
        className={cn(
          playerContentColumnClass,
          "flex items-center justify-center gap-2 px-4 py-3 text-sm",
          "animate-in slide-in-from-top-full duration-300 ease-out",
        )}
        style={{
          backgroundColor: ERROR_COLORS.error,
          color: "#fff",
        }}
        role="alert"
        aria-live="assertive"
      >
        <WifiOff className="size-4 shrink-0" aria-hidden />
        <span className="font-medium">{t("network.offline")}</span>
        <button
          onClick={handleReconnect}
          className="ml-3 flex items-center gap-1.5 rounded-md bg-white/20 px-3 py-1.5 text-xs font-medium transition-colors hover:bg-white/30 focus:outline-none focus:ring-2 focus:ring-white/50 active:bg-white/25"
          aria-label={t("network.reconnect")}
        >
          <RefreshCw className="size-3.5" aria-hidden />
          {t("network.reconnect")}
        </button>
      </div>
    </div>
  );
}
