import { useEffect, useMemo } from 'react';
import { where } from 'firebase/firestore';
import { useLiveParticleChildren } from '@/hooks/use-particle';
import { useAuthStore } from '@/stores/auth-store';
import { particlePath } from '@/lib/particle-path';
import type { Particle, StreamProperties } from '@/api/types';
import { platform } from '@/lib/platform';

type StreamParticle = Particle & {
  type: 'stream';
  properties: StreamProperties;
};

const openStatusFilter = where('status', '==', 'open');

/**
 * Self-contained hook that syncs the macOS dock badge with the count of
 * unseen open streams the current user is involved in.
 *
 * Sets up its own Firestore listener so it works independently of
 * whatever stream list is rendered on screen.
 */
export function useDockBadge(networkId: string | undefined) {
  const user = useAuthStore((s) => s.user);
  const userId = user?.id;

  const visibilityScopes = useMemo(() => {
    const scopes: string[] = [];
    if (userId) scopes.push(`human:${userId}`);
    if (networkId) scopes.push(`network:${networkId}`);
    return scopes;
  }, [userId, networkId]);

  const path = networkId ? particlePath(networkId, []) : undefined;

  const { children } = useLiveParticleChildren(path, {
    orderByField: 'last_child_created_at',
    orderDirection: 'desc',
    visibilityScopes,
    whereFilter: openStatusFilter,
  });

  const unseenCount = useMemo(() => {
    if (!userId) return 0;
    return children.filter((c): c is StreamParticle => {
      if (c.type !== 'stream') return false;
      const lastActivity = c.last_child_created_at?.getTime();
      if (!lastActivity) return false;
      const marker = c.playback_markers?.[userId]?.getTime();
      if (marker === undefined) return false;
      return lastActivity > marker;
    }).length;
  }, [children, userId]);

  useEffect(() => {
    platform.app.setDockBadge(unseenCount);
  }, [unseenCount]);
}
