import { useEffect, useState } from "react";
import { useLocation } from "react-router";
import { t } from "@lingui/core/macro";
import { useAuth } from "../hooks/useAuth.ts";
import { useWS } from "../hooks/useWS.ts";
import { useChat } from "../hooks/useChat.ts";

/**
 * Floating chat button shown once the header has scrolled out of view, mirroring
 * {@link DumpFab}. Opens the single app-wide chat modal (owned by ChatProvider).
 * Only rendered for signed-in users.
 */
export function ChatFab() {
  const { user } = useAuth();
  const { unreadChatCount } = useWS();
  const { openChat } = useChat();
  const location = useLocation();
  const [headerHidden, setHeaderHidden] = useState(false);

  // Reveal the button once the header's bottom edge scrolls above the viewport.
  // Re-reading the header on every tick keeps this correct across navigation
  // and lazily-mounted pages, where the header element is replaced.
  useEffect(() => {
    if (!user) return;
    const update = () => {
      const header = document.querySelector(".app-header");
      setHeaderHidden(!!header && header.getBoundingClientRect().bottom <= 0);
    };
    update();
    globalThis.addEventListener("scroll", update, { passive: true });
    globalThis.addEventListener("resize", update);
    const ro = new ResizeObserver(update);
    ro.observe(document.body);
    return () => {
      globalThis.removeEventListener("scroll", update);
      globalThis.removeEventListener("resize", update);
      ro.disconnect();
    };
  }, [user, location.pathname]);

  if (!user) return null;

  return (
    <button
      type="button"
      className={`chat-fab${headerHidden ? " chat-fab--visible" : ""}`}
      aria-label={unreadChatCount > 0
        ? t`Chat (${unreadChatCount} unread)`
        : t`Chat`}
      title={t`Chat`}
      aria-hidden={!headerHidden}
      tabIndex={headerHidden ? 0 : -1}
      onClick={openChat}
    >
      <svg
        className="chat-fab-icon"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth={2}
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <path d="M21 11.5a8.38 8.38 0 0 1-8.5 8.5 8.5 8.5 0 0 1-3.8-.9L3 21l1.9-5.7a8.5 8.5 0 0 1-.9-3.8A8.38 8.38 0 0 1 12.5 3a8.38 8.38 0 0 1 8.5 8.5z" />
      </svg>
      {unreadChatCount > 0 && (
        <span className="notification-badge">
          {unreadChatCount > 99 ? "99+" : unreadChatCount}
        </span>
      )}
    </button>
  );
}
