import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest';
import { useTerminalStore } from '../../src/state/terminalStore';

describe('terminalStore', () => {
  beforeEach(() => setActivePinia(createPinia()));

  it('starts in idle right-panel mode with no active card', () => {
    const store = useTerminalStore();

    expect(store.contextPanelMode).toBe('idle');
    expect(store.activeCard).toBeNull();
  });

  it('switches to task mode when a card is active', () => {
    const store = useTerminalStore();

    store.setActiveCard({
      cardInstanceId: 'card_001',
      cardKey: 'department-selection',
      status: 'active',
      cardData: { departments: [] },
      actions: [{ actionName: 'select_department', label: '选择科室' }]
    });

    expect(store.contextPanelMode).toBe('task');
  });

  it('switches to completed mode for appointment-success card', () => {
    const store = useTerminalStore();

    store.setActiveCard({
      cardInstanceId: 'card_005',
      cardKey: 'appointment-success',
      status: 'completed',
      cardData: { appointmentNo: 'A023', mock: true },
      actions: []
    });

    expect(store.contextPanelMode).toBe('completed');
  });

  it('switches to error mode when error message is set', () => {
    const store = useTerminalStore();

    store.setError('网络连接失败', 'trace_abc123');

    expect(store.contextPanelMode).toBe('error');
    expect(store.errorMessage).toBe('网络连接失败');
    expect(store.currentTraceId).toBe('trace_abc123');
  });

  it('resets to idle clears task, card and error', () => {
    const store = useTerminalStore();

    store.setActiveCard({
      cardInstanceId: 'card_001',
      cardKey: 'department-selection',
      status: 'active',
      cardData: {},
      actions: []
    });
    store.setError('something went wrong');

    store.resetToIdle();

    expect(store.contextPanelMode).toBe('idle');
    expect(store.activeCard).toBeNull();
    expect(store.task).toBeNull();
    expect(store.errorMessage).toBe('');
  });

  it('appends assistant delta correctly', () => {
    const store = useTerminalStore();

    store.appendAssistantDelta('你好');
    expect(store.messages).toHaveLength(1);
    expect(store.messages[0].content).toBe('你好');
    expect(store.messages[0].streaming).toBe(true);

    store.appendAssistantDelta('，世界');
    expect(store.messages).toHaveLength(1);
    expect(store.messages[0].content).toBe('你好，世界');
  });

  it('completes assistant message marks streaming false', () => {
    const store = useTerminalStore();

    store.appendAssistantDelta('测试');
    store.completeAssistantMessage();

    expect(store.messages[0].streaming).toBe(false);
  });
});
