import { render } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';

const { mockTrackProductEvent } = vi.hoisted(() => ({ mockTrackProductEvent: vi.fn() }));
vi.mock('@/lib/analytics', () => ({ trackProductEvent: mockTrackProductEvent }));

import PipelineIndex from './Index';

vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    usePage: vi.fn(() => ({
      props: {
        auth: { user: { name: 'Test User', email: 'test@example.com' } },
        features: { billing: false, notifications: false },
        sites: [],
        limits: null,
        ai_defaults: { model: 'gpt-4o-mini', temperature: 0.7 },
      },
    })),
    Head: ({ title }: { title: string }) => <title>{title}</title>,
    Link: ({ children, href }: { children: React.ReactNode; href: string }) => (
      <a href={href}>{children}</a>
    ),
  };
});

vi.mock('@/Layouts/DashboardLayout', () => ({
  default: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="dashboard-layout">{children}</div>
  ),
}));

vi.mock('@/Components/Navigation/SiteNav', () => ({
  default: () => <div data-testid="site-nav" />,
}));

vi.mock('@/Components/ui/scroll-area', () => ({
  ScrollArea: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

const emptyCounts = {
  opportunity: 0,
  brief: 0,
  draft: 0,
  editing: 0,
  review: 0,
  published: 0,
  tracking: 0,
};

const emptyStages = {
  opportunity: [],
  brief: [],
  draft: [],
  editing: [],
  review: [],
  published: [],
  tracking: [],
};

const defaultProps = {
  site: { id: 2, name: 'Pipeline Site', domain: 'https://pipeline.com' },
  stages: emptyStages,
  counts: emptyCounts,
};

describe('Pipeline/Index', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  describe('analytics', () => {
    it('fires pipeline_viewed with site_id and total_items on mount', () => {
      render(<PipelineIndex {...defaultProps} />);
      expect(mockTrackProductEvent).toHaveBeenCalledWith('pipeline_viewed', {
        site_id: '2',
        total_items: 0,
      });
    });

    it('fires feature_used with pipeline on mount', () => {
      render(<PipelineIndex {...defaultProps} />);
      expect(mockTrackProductEvent).toHaveBeenCalledWith('feature_used', {
        feature: 'pipeline',
      });
    });
  });
});
