import { render, screen, fireEvent } from '@testing-library/react'
import { CalendarView, type CalendarEvent } from '../calendar/calendar-view'

const FIXED_DATE = new Date('2026-04-15T12:00:00Z')

const sampleEvents: CalendarEvent[] = [
  {
    id: 'meet-1',
    title: 'Investor Sync — Sequoia',
    start: new Date('2026-04-15T16:00:00Z'),
    end: new Date('2026-04-15T16:30:00Z'),
  },
  {
    id: 'meet-2',
    title: 'Demo with Acme',
    start: '2026-04-16T17:00:00Z',
    end: '2026-04-16T17:45:00Z',
  },
]

describe('CalendarView', () => {
  it('renders without crashing in month view', () => {
    render(
      <CalendarView
        events={sampleEvents}
        defaultDate={FIXED_DATE}
        defaultView="month"
      />
    )
    // The toolbar's "Today" button is always rendered by react-big-calendar
    expect(screen.getByText('Today')).toBeInTheDocument()
  })

  it('renders event titles on the grid', () => {
    render(
      <CalendarView
        events={sampleEvents}
        defaultDate={FIXED_DATE}
        defaultView="month"
      />
    )
    expect(screen.getByText(/Investor Sync — Sequoia/)).toBeInTheDocument()
    expect(screen.getByText(/Demo with Acme/)).toBeInTheDocument()
  })

  it('fires onEventClick with the original event when an event is clicked', () => {
    const onEventClick = jest.fn()
    render(
      <CalendarView
        events={sampleEvents}
        defaultDate={FIXED_DATE}
        defaultView="month"
        onEventClick={onEventClick}
      />
    )
    fireEvent.click(screen.getByText(/Investor Sync — Sequoia/))
    expect(onEventClick).toHaveBeenCalledTimes(1)
    expect(onEventClick.mock.calls[0][0].id).toBe('meet-1')
    expect(onEventClick.mock.calls[0][0].title).toBe('Investor Sync — Sequoia')
  })

  it('accepts string dates in events and normalizes them', () => {
    // Verifies the toDate / normalizeEvent path
    render(
      <CalendarView
        events={[
          { id: 'x', title: 'Stringy', start: '2026-04-15T16:00:00Z' },
        ]}
        defaultDate={FIXED_DATE}
        defaultView="month"
      />
    )
    expect(screen.getByText(/Stringy/)).toBeInTheDocument()
  })

  it('passes through resource payload to onEventClick', () => {
    interface MyMeeting {
      uuid: string
      attendees: number
    }
    const meeting: MyMeeting = { uuid: 'abc-123', attendees: 5 }
    const onEventClick = jest.fn()
    render(
      <CalendarView<MyMeeting>
        events={[
          { id: 'r1', title: 'WithResource', start: FIXED_DATE, resource: meeting },
        ]}
        defaultDate={FIXED_DATE}
        defaultView="month"
        onEventClick={onEventClick}
      />
    )
    fireEvent.click(screen.getByText(/WithResource/))
    expect(onEventClick).toHaveBeenCalledTimes(1)
    expect(onEventClick.mock.calls[0][0].resource).toEqual(meeting)
  })
})
