import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { trackProductEvent } from '@/shared/analytics/productAnalytics';

describe('productAnalytics', () => {
  beforeEach(() => {
    vi.spyOn(window, 'dispatchEvent');
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('dispatches analytics custom event', () => {
    trackProductEvent('timeline_view_opened');

    expect(window.dispatchEvent).toHaveBeenCalledTimes(1);
    const event = vi.mocked(window.dispatchEvent).mock.calls[0][0] as CustomEvent;
    expect(event.type).toBe('mvhd:product-analytics');
    expect(event.detail).toEqual({ event: 'timeline_view_opened', properties: undefined });
  });

  it('includes optional properties', () => {
    trackProductEvent('portfolio_view_switched', { from: 'executive', to: 'gantt' });

    const event = vi.mocked(window.dispatchEvent).mock.calls[0][0] as CustomEvent;
    expect(event.detail).toEqual({
      event: 'portfolio_view_switched',
      properties: { from: 'executive', to: 'gantt' },
    });
  });

  it('supports portfolio enterprise analytics events', () => {
    trackProductEvent('portfolio_view_opened');
    trackProductEvent('portfolio_filter_applied', { filter: 'blocked', type: 'project' });
    trackProductEvent('project_row_opened', { view: 'executive', project_id: 'p1' });

    expect(window.dispatchEvent).toHaveBeenCalledTimes(3);
  });
});
