import React from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, Routes, Route } from 'react-router-dom'
import ProjectLayout from './ProjectLayout.jsx'

vi.mock('../api', () => ({ getProject: vi.fn() }))
vi.mock('../context/DeploymentProvider', () => ({
  useDeployment: () => ({ defaultProjectId: 'default', name: 'Dep', projects: [] }),
}))
import { getProject } from '../api'

function renderAt(path) {
  return render(
    <MemoryRouter initialEntries={[path]}>
      <Routes>
        <Route path="/p/:projectId/*" element={
          <ProjectLayout><div data-testid="corpus">CORPUS</div></ProjectLayout>
        } />
      </Routes>
    </MemoryRouter>,
  )
}

describe('ProjectLayout', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    document.documentElement.style.removeProperty('--c-accent')
  })

  it('renders the corpus children for the corpus-served default project', async () => {
    getProject.mockResolvedValue({ id: 'default', name: 'OHM', type: 'document', theme: {} })
    renderAt('/p/default/')
    expect(await screen.findByTestId('corpus')).toBeInTheDocument()
  })

  it('applies the project theme to :root and resets it on unmount', async () => {
    getProject.mockResolvedValue({ id: 'default', name: 'OHM', type: 'document', theme: { accent: '#123456' } })
    const { unmount } = renderAt('/p/default/')
    await waitFor(() =>
      expect(document.documentElement.style.getPropertyValue('--c-accent')).toBe('#123456'))
    unmount()
    expect(document.documentElement.style.getPropertyValue('--c-accent')).toBe('')
  })

  it('shows the not-served placeholder for a non-default (Plan-B) project', async () => {
    getProject.mockResolvedValue({ id: 'other', name: 'Ecomm', type: 'bdd', theme: {} })
    renderAt('/p/other/')
    expect(await screen.findByText(/isn.t being served here yet/i)).toBeInTheDocument()
    expect(screen.queryByTestId('corpus')).not.toBeInTheDocument()
  })

  it('shows a not-found message when the project 404s', async () => {
    getProject.mockRejectedValue(Object.assign(new Error('nope'), { status: 404 }))
    renderAt('/p/ghost/')
    expect(await screen.findByText(/Not found/i)).toBeInTheDocument()
  })
})