/**
 * Project tabs store — per-project tab state.
 *
 * Uses a version counter to signal changes instead of Map reassignment.
 * Map reassignment (`_tabs = new Map(_tabs)`) caused infinite reactive loops
 * in Svelte 5 because each call created a new object reference.
 */

export type ProjectTab =
  | 'model' | 'docs' | 'context' | 'files'
  | 'ssh' | 'memory' | 'comms' | 'tasks';

export const ALL_TABS: ProjectTab[] = [
  'model', 'docs', 'context', 'files', 'ssh', 'memory', 'comms', 'tasks',
];

interface TabState {
  activeTab: ProjectTab;
  activatedTabs: Set<ProjectTab>;
}

// ── State ────────────────────────────────────────────────────────────────

// Plain Map — NOT reactive. We use _version to signal changes.
const _tabs = new Map<string, TabState>();
let _version = $state(0);

// ── Internal helper ──────────────────────────────────────────────────────

function ensureEntry(projectId: string): TabState {
  let entry = _tabs.get(projectId);
  if (!entry) {
    entry = { activeTab: 'model', activatedTabs: new Set(['model']) };
    _tabs.set(projectId, entry);
    // Do NOT bump version here — this is a read-path side effect
    // that would cause infinite loops when called from $derived
  }
  return entry;
}

// ── Getters (read _version to subscribe to changes) ─────────────────────

export function getActiveTab(projectId: string): ProjectTab {
  void _version; // subscribe to version counter
  return _tabs.get(projectId)?.activeTab ?? 'model';
}

export function isTabActivated(projectId: string, tab: ProjectTab): boolean {
  void _version;
  return _tabs.get(projectId)?.activatedTabs.has(tab) ?? (tab === 'model');
}

// ── Actions (bump version to notify subscribers) ────────────────────────

export function setActiveTab(projectId: string, tab: ProjectTab): void {
  const entry = ensureEntry(projectId);
  entry.activeTab = tab;
  entry.activatedTabs.add(tab);
  _version++; // signal change without creating new objects
}

export function removeProject(projectId: string): void {
  if (_tabs.delete(projectId)) {
    _version++;
  }
}
