import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';

function getStoreValue<T>(store: { subscribe: (run: (value: T) => void) => () => void }): T {
  let value!: T;
  const unsubscribe = store.subscribe((current) => {
    value = current;
  });
  unsubscribe();
  return value;
}

describe('period store', () => {
  beforeEach(() => {
    vi.resetModules();
    (localStorage.getItem as Mock).mockReturnValue(null);
  });

  it('initializes with current month', async () => {
    const store = await import('../../src/lib/stores/period');

    const now = new Date();
    const expected = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
    expect(getStoreValue(store.selectedPeriod)).toBe(expected);
  });

  it('previousMonth decrements correctly', async () => {
    const store = await import('../../src/lib/stores/period');

    store.setPeriod('2025-01');
    store.previousMonth();

    expect(getStoreValue(store.selectedPeriod)).toBe('2024-12');
    expect(localStorage.setItem).toHaveBeenCalledWith('headroom_selected_period', '2024-12');
  });

  it('nextMonth increments correctly', async () => {
    const store = await import('../../src/lib/stores/period');

    store.setPeriod('2025-12');
    store.nextMonth();

    expect(getStoreValue(store.selectedPeriod)).toBe('2026-01');
  });
});
