'use client';

// Subscribe to the global active-player id. Reads from activePlayerBus, which
// already coordinates same-tab + cross-tab via BroadcastChannel.

import { useSyncExternalStore } from 'react';
import {
  getActivePlayer,
  getLastActivePlayer,
  subscribeActivePlayer,
} from '../store/activePlayerBus';

const getServerSnapshot = (): string | null => null;

/** Currently active player id. `null` when nothing plays. */
export function useActivePlayer(): string | null {
  return useSyncExternalStore(subscribeActivePlayer, getActivePlayer, getServerSnapshot);
}

/** Most recently active player id. Stays set after pause; useful for "last
 * played" UIs where you want to keep showing a track even when paused. */
export function useLastActivePlayer(): string | null {
  return useSyncExternalStore(subscribeActivePlayer, getLastActivePlayer, getServerSnapshot);
}

/** True when the given id is currently active. Convenience for conditional
 * styling without comparing strings inline. */
export function useIsActivePlayer(id: string | null | undefined): boolean {
  const active = useActivePlayer();
  return Boolean(id) && active === id;
}
