import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { Sidebar } from './Sidebar'
import type { FileItem } from '../types'

describe('Sidebar', () => {
  const mockFiles: FileItem[] = [
    { id: '1', name: 'file1', content: '' },
    { id: '2', name: 'file2', content: '' },
  ]

  it('renders list of files', () => {
    render(
      <Sidebar
        files={mockFiles}
        currentFile={null}
        onCreateFile={() => {}}
        onOpenFile={() => {}}
        onDeleteFile={() => {}}
        isLoading={false}
      />
    )

    expect(screen.getByText('file1.md')).toBeInTheDocument()
    expect(screen.getByText('file2.md')).toBeInTheDocument()
  })

  it('shows loading state', () => {
    render(
      <Sidebar
        files={[]}
        currentFile={null}
        onCreateFile={() => {}}
        onOpenFile={() => {}}
        onDeleteFile={() => {}}
        isLoading={true}
      />
    )

    expect(document.querySelector('.animate-spin')).toBeInTheDocument()
  })

  it('shows empty state when no files', () => {
    render(
      <Sidebar
        files={[]}
        currentFile={null}
        onCreateFile={() => {}}
        onOpenFile={() => {}}
        onDeleteFile={() => {}}
        isLoading={false}
      />
    )

    expect(screen.getByText(/no files yet/i)).toBeInTheDocument()
  })

  it('calls onOpenFile when file is clicked', () => {
    const handleOpenFile = vi.fn()
    render(
      <Sidebar
        files={mockFiles}
        currentFile={null}
        onCreateFile={() => {}}
        onOpenFile={handleOpenFile}
        onDeleteFile={() => {}}
        isLoading={false}
      />
    )

    fireEvent.click(screen.getByText('file1.md'))
    expect(handleOpenFile).toHaveBeenCalledWith(mockFiles[0])
  })

  it('opens create file input when plus button is clicked', () => {
    render(
      <Sidebar
        files={[]}
        currentFile={null}
        onCreateFile={() => {}}
        onOpenFile={() => {}}
        onDeleteFile={() => {}}
        isLoading={false}
      />
    )

    fireEvent.click(screen.getByTitle('Create new file'))
    expect(screen.getByPlaceholderText('File name...')).toBeInTheDocument()
  })
})
