"use client";

import { useEffect, useState } from "react";
import { Link } from "@/i18n/navigation";
import { fetchConversations } from "@/app/lib/chat";
import { resolveAuthUser } from "@/app/lib/api-client";

export default function ChatNavLink() {
  const [unread, setUnread] = useState(0);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      const session = await resolveAuthUser();
      if (!session?.user?.id) {
        if (!cancelled) {
          setVisible(false);
          setUnread(0);
        }
        return;
      }
      try {
        const data = await fetchConversations();
        if (!cancelled) {
          setVisible(true);
          setUnread(data.unread || 0);
        }
      } catch {
        if (!cancelled) setVisible(false);
      }
    };
    load();
    const timer = window.setInterval(load, 15000);
    const onAuth = () => load();
    window.addEventListener("auth:updated", onAuth);
    return () => {
      cancelled = true;
      window.clearInterval(timer);
      window.removeEventListener("auth:updated", onAuth);
    };
  }, []);

  if (!visible) return null;

  return (
    <Link
      href="/chat"
      className="relative inline-flex items-center justify-center rounded-lg p-2 text-gray-600 transition hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800"
      aria-label="私信"
      title="私信"
    >
      <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M8 10h8M8 14h5m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      {unread > 0 ? (
        <span className="absolute -right-0.5 -top-0.5 min-w-[18px] rounded-full bg-[#ff4d4f] px-1 text-center text-[10px] font-bold leading-[18px] text-white">
          {unread > 9 ? "9+" : unread}
        </span>
      ) : null}
    </Link>
  );
}
