"use client";

import { useChatWidgetStore } from "@/hooks/useChatWidgetStore";
import { ChatWidget } from "./ChatWidget";
import { MessageCircle, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";

export default function TeamChatWidget() {
  const { isMinimized, toggleMinimized, unreadCount } = useChatWidgetStore();

  return (
    <>
      {/* Chat Toggle Bubble - Always visible */}
      <Tooltip>
        <TooltipTrigger asChild>
          <button
            onClick={toggleMinimized}
            aria-label={
              isMinimized
                ? unreadCount > 0
                  ? `Open chat (${unreadCount} unread messages)`
                  : "Open team chat"
                : "Close team chat"
            }
            className={cn(
              "fixed bottom-6 right-6 z-[9999] w-14 h-14 rounded-md bg-primary text-primary-foreground flex items-center justify-center cursor-pointer hover:bg-primary/90 shadow-lg transition-all active:scale-95",
              !isMinimized &&
                "rotate-90 bg-secondary text-secondary-foreground hover:bg-secondary/80"
            )}
          >
            {!isMinimized ? (
              <X className="h-6 w-6" />
            ) : (
              <MessageCircle className="h-6 w-6" />
            )}

            {isMinimized && unreadCount > 0 && (
              <Badge
                variant="destructive"
                className="absolute -top-1 -right-1 h-5 w-5 p-0 flex items-center justify-center text-[10px] rounded-full"
              >
                {unreadCount > 9 ? "9+" : unreadCount}
              </Badge>
            )}
          </button>
        </TooltipTrigger>
        <TooltipContent side="left" sideOffset={8}>
          <p>{isMinimized ? "Team Chat" : "Close"}</p>
        </TooltipContent>
      </Tooltip>

      {/* Chat Window - Visible when not minimized */}
      {!isMinimized && (
        <ChatWidget />
      )}
    </>
  );
}
