import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import LogHabitModal from '../components/LogHabitModal'

describe('LogHabitModal', () => {
  const mockHabit = { id: 1, name: 'Exercise', color: '#6366f1', icon: '🏃' }
  const mockOnClose = vi.fn()
  const mockOnLogDate = vi.fn()

  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('does not render when open=false', () => {
    render(
      <LogHabitModal
        open={false}
        onClose={mockOnClose}
        habit={mockHabit}
        completedDates={[]}
        onLogDate={mockOnLogDate}
      />
    )
    expect(screen.queryByText('Exercise')).not.toBeInTheDocument()
  })

  it('renders modal when open=true', () => {
    render(
      <LogHabitModal
        open={true}
        onClose={mockOnClose}
        habit={mockHabit}
        completedDates={[]}
        onLogDate={mockOnLogDate}
      />
    )
    expect(screen.getByText('Exercise')).toBeInTheDocument()
  })

  it('renders calendar', () => {
    render(
      <LogHabitModal
        open={true}
        onClose={mockOnClose}
        habit={mockHabit}
        completedDates={[]}
        onLogDate={mockOnLogDate}
      />
    )
    // Calendar days should be present
    const dayButtons = screen.getAllByRole('button')
    expect(dayButtons.length).toBeGreaterThan(1)
  })

  it('renders prev/next month navigation', () => {
    render(
      <LogHabitModal
        open={true}
        onClose={mockOnClose}
        habit={mockHabit}
        completedDates={[]}
        onLogDate={mockOnLogDate}
      />
    )
    // Check navigation arrows
    const buttons = screen.getAllByRole('button')
    expect(buttons.length).toBeGreaterThan(2)
  })

  it('calls onClose when backdrop clicked', () => {
    const { container } = render(
      <LogHabitModal
        open={true}
        onClose={mockOnClose}
        habit={mockHabit}
        completedDates={[]}
        onLogDate={mockOnLogDate}
      />
    )
    // Click backdrop (first child overlay)
    const backdrop = container.querySelector('.fixed.inset-0')
    fireEvent.click(backdrop)
    expect(mockOnClose).toHaveBeenCalled()
  })

  it('calls onClose when X button clicked', () => {
    render(
      <LogHabitModal
        open={true}
        onClose={mockOnClose}
        habit={mockHabit}
        completedDates={[]}
        onLogDate={mockOnLogDate}
      />
    )
    // Find close button (X icon)
    const closeBtn = screen.getAllByRole('button')[0]
    fireEvent.click(closeBtn)
    // Some button should trigger close
    expect(mockOnClose).toHaveBeenCalled()
  })
})
