import { useMemo } from 'react';
import type { GhostNote, GhostVisibilityState } from '../types/research';

const visibilityRank: Record<GhostVisibilityState, number> = {
  pinned: 3,
  visible: 2,
  collapsed: 1,
  hidden: 0,
};

export const useResearchGhosts = (ghosts: GhostNote[]) => {
  const visibleGhosts = useMemo(
    () =>
      ghosts
        .filter((ghost) => visibilityRank[ghost.visibilityState] > 0)
        .sort((left, right) => {
          const visibilityDelta =
            visibilityRank[right.visibilityState] - visibilityRank[left.visibilityState];
          if (visibilityDelta !== 0) {
            return visibilityDelta;
          }
          const leverageDelta = (right.leverageScore ?? 0) - (left.leverageScore ?? 0);
          if (leverageDelta !== 0) {
            return leverageDelta;
          }
          return right.confidence - left.confidence;
        }),
    [ghosts],
  );

  const railGhosts = visibleGhosts.slice(0, 3);
  const hiddenGhostCount = Math.max(ghosts.length - visibleGhosts.length, 0);

  return {
    visibleGhosts,
    railGhosts,
    hiddenGhostCount,
  };
};
