"use client";

import { useEffect, useState } from "react";
import Link from "next/link";

interface InvitationBadgeProps {
  initialCount?: number;
  onNavigate?: () => void;
}

export default function InvitationBadge({
  initialCount = 0,
  onNavigate,
}: InvitationBadgeProps) {
  const [count, setCount] = useState(initialCount);

  // Utiliser le count initial (déjà récupéré côté serveur)
  useEffect(() => {
    setCount(initialCount);
  }, [initialCount]);

  // Écouter les événements de refresh des invitations (déclenché après acceptation/refus)
  useEffect(() => {
    const handleRefreshInvitations = async () => {
      try {
        const response = await fetch("/api/invitations/pending-count");
        const data = await response.json();
        setCount(data.count || 0);
      } catch (error) {
        console.error("Error fetching pending invitations count:", error);
      }
    };

    window.addEventListener("refreshInvitations", handleRefreshInvitations);
    return () => {
      window.removeEventListener("refreshInvitations", handleRefreshInvitations);
    };
  }, []);

  return (
    <Link
      href="/houses"
      onClick={onNavigate}
      className={`inline-flex items-center gap-1.5 transition text-xs font-normal uppercase tracking-widest ${
        onNavigate ? "py-2" : ""
      }`}
      style={{ color: "var(--foreground)" }}
      onMouseEnter={(e) =>
        (e.currentTarget.style.color = "var(--accent-color)")
      }
      onMouseLeave={(e) => (e.currentTarget.style.color = "var(--foreground)")}
      title={
        count > 0
          ? `${count} action${count > 1 ? "s" : ""} en attente (invitations et demandes)`
          : "Maisons"
      }
    >
      <span>MAISONS</span>
      {count > 0 && (
        <span
          className="flex h-5 w-5 min-w-[20px] items-center justify-center rounded-full text-[10px] font-bold leading-none"
          style={{
            backgroundColor: "var(--accent)",
            color: "var(--background)",
          }}
        >
          {count > 9 ? "9+" : count}
        </span>
      )}
    </Link>
  );
}

