"use client";

import { useEffect, useState } from "react";
import { useRepositories } from "@/di/repository-provider";
import { useSupportActivity } from "@/presentation/hooks/use-support-activity";

/** Conversations (mine or unassigned) with unread client messages, for the sidebar badge. */
export function useSupportUnreadCount(enabled: boolean): number {
  const container = useRepositories();
  const [count, setCount] = useState(0);
  const [tick, setTick] = useState(0);

  useEffect(() => {
    if (!enabled) return;
    let cancelled = false;
    container.ticketRepository
      .getInboxCounts()
      .then((counts) => { if (!cancelled) setCount(counts.unread); })
      .catch(() => { /* Badge only. */ });
    return () => { cancelled = true; };
  }, [container, enabled, tick]);

  // Every admin page shows the badge: poll gently when real time is unavailable.
  useSupportActivity(() => setTick((n) => n + 1), 30_000);

  return enabled ? count : 0;
}
