import { describe, expect, it } from 'bun:test';
import { useResearchUiStore } from './researchUiStore';

const resetResearchUiStore = () => {
  useResearchUiStore.setState({
    viewByWorkspaceId: {},
    filtersByWorkspaceId: {},
    memoDraftByWorkspaceId: {},
    density: 'comfortable',
    sidebarCollapsed: false,
    inspectorPinned: true,
    memoPreview: true,
    activeWorkspaceId: null,
    selectionByWorkspaceId: {},
    captureModal: {
      isOpen: false,
      draft: {
        rawText: '',
        bodyHtml: '',
        embeds: [],
        fileIds: [],
        ticker: '',
        workspaceId: '',
        sourceUrl: '',
        sourceTitle: '',
        sourceKind: 'manual',
        userNoteTypeOverride: undefined,
        includeCurrentContext: true,
        captureMode: 'standard',
        linkUrlDraft: '',
      },
      seedToken: null,
      contextLabel: undefined,
    },
    createWorkspaceModal: {
      isOpen: false,
      tickerDraft: '',
    },
    mobilePane: 'none',
    lastNavigationIntentToken: null,
    mutationStateByKey: {},
  });
};

describe('researchUiStore', () => {
  it('does not overwrite an existing workspace view during later initialization', () => {
    resetResearchUiStore();
    const store = useResearchUiStore.getState();
    store.initializeWorkspaceState('workspace-1', 'canvas');
    store.setWorkspaceView('workspace-1', 'graph');
    store.initializeWorkspaceState('workspace-1', 'timeline');

    expect(useResearchUiStore.getState().viewByWorkspaceId['workspace-1']).toBe('graph');
  });

  it('replaces the capture modal draft when reopened with a new seed', () => {
    resetResearchUiStore();
    const store = useResearchUiStore.getState();
    store.setActiveWorkspaceId('workspace-1');
    store.openCaptureModal({
      seedToken: 'old-seed',
      draft: {
        workspaceId: 'workspace-1',
        rawText: 'Old draft',
        ticker: 'NVDA',
      },
      contextLabel: 'Old context',
    });
    store.closeCaptureModal();

    store.openCaptureModal({
      seedToken: 'new-seed',
      draft: {
        workspaceId: 'workspace-1',
        rawText: 'New draft',
        ticker: 'AAPL',
      },
      contextLabel: 'New context',
    });

    const modal = useResearchUiStore.getState().captureModal;
    expect(modal.seedToken).toBe('new-seed');
    expect(modal.draft.rawText).toBe('New draft');
    expect(modal.draft.ticker).toBe('AAPL');
    expect(modal.contextLabel).toBe('New context');
  });

  it('clears capture draft file ids when the workspace changes', () => {
    resetResearchUiStore();
    const store = useResearchUiStore.getState();
    store.openCaptureModal({
      draft: {
        workspaceId: 'workspace-1',
        fileIds: ['file-1'],
      },
    });

    store.updateCaptureDraft({ workspaceId: 'workspace-2' });

    expect(useResearchUiStore.getState().captureModal.draft.fileIds).toEqual([]);
  });
});
