import { useEffect, useState } from 'react';
import type { WorkspacePaneKind } from '@/api/types';

export interface ActivePaneSnapshot {
  sessionId: string | null;
  paneId: string | null;
  kind: WorkspacePaneKind | null;
  activeFile: string | null;
}

const EMPTY: ActivePaneSnapshot = {
  sessionId: null,
  paneId: null,
  kind: null,
  activeFile: null,
};

let current: ActivePaneSnapshot = EMPTY;
const subs = new Set<() => void>();

function notify(): void {
  for (const sub of subs) {
    try {
      sub();
    } catch {
      // swallow — one bad listener shouldn't break others
    }
  }
}

function isSame(a: ActivePaneSnapshot, b: ActivePaneSnapshot): boolean {
  return (
    a.sessionId === b.sessionId &&
    a.paneId === b.paneId &&
    a.kind === b.kind &&
    a.activeFile === b.activeFile
  );
}

export function setActivePaneInfo(next: ActivePaneSnapshot): void {
  if (isSame(current, next)) return;
  current = next;
  notify();
}

export function clearActivePane(): void {
  setActivePaneInfo(EMPTY);
}

export function useActivePane(): ActivePaneSnapshot {
  const [snap, setSnap] = useState<ActivePaneSnapshot>(current);
  useEffect(() => {
    const sub = () => setSnap(current);
    subs.add(sub);
    sub();
    return () => {
      subs.delete(sub);
    };
  }, []);
  return snap;
}
