"use client";

import { useState, useCallback } from "react";
import { Users, Share2 } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

interface TopNavProps {
  roomId: string;
  userCount: number;
}

export default function TopNav({ roomId, userCount }: TopNavProps) {
  const [toast, setToast] = useState("");

  const showToast = useCallback((msg: string) => {
    setToast(msg);
    setTimeout(() => setToast(""), 2200);
  }, []);

  const handleInvite = useCallback(async () => {
    const url = window.location.href;
    const shareData = {
      title: "别说随便啦，来滑卡片决定吃什么！",
      text: "我建好房间了，快点开链接一起选餐厅，滑中同一家就去吃！",
      url,
    };

    try {
      if (navigator.share && navigator.canShare?.(shareData)) {
        await navigator.share(shareData);
        return;
      }
    } catch (e) {
      if (e instanceof Error && e.name === "AbortError") return;
    }

    try {
      await navigator.clipboard.writeText(url);
      showToast("邀请链接已复制，快去发给朋友吧！");
    } catch {
      showToast("复制失败，请手动复制链接");
    }
  }, [showToast]);

  return (
    <>
      <nav className="relative z-10 flex h-14 items-center justify-between px-4">
        <div className="w-24">
          <button
            onClick={handleInvite}
            className="flex items-center gap-1 rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-semibold text-emerald-600 transition-colors active:bg-emerald-100"
          >
            <Share2 size={13} />
            邀请饭搭子
          </button>
        </div>

        <h1 className="text-center text-base font-bold tracking-tight text-zinc-900">
          <span className="block leading-tight">NoWhatever</span>
          <span className="block text-[10px] font-medium tracking-widest text-zinc-400">
            别说随便
          </span>
        </h1>

        <div className="flex w-24 items-center justify-end gap-1.5 text-xs text-zinc-500">
          <span className="rounded-full bg-zinc-100 px-2 py-0.5 font-medium">
            {roomId}
          </span>
          <div className="flex items-center gap-0.5">
            <Users size={13} />
            <span className="font-semibold text-emerald-500">{userCount}</span>
          </div>
        </div>
      </nav>

      <AnimatePresence>
        {toast && (
          <motion.div
            className="fixed left-1/2 top-16 z-50 -translate-x-1/2 rounded-xl bg-zinc-900 px-4 py-2.5 text-xs font-medium text-white shadow-lg"
            initial={{ opacity: 0, y: -12, x: "-50%" }}
            animate={{ opacity: 1, y: 0, x: "-50%" }}
            exit={{ opacity: 0, y: -12, x: "-50%" }}
            transition={{ type: "spring", stiffness: 400, damping: 25 }}
          >
            {toast}
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
