import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'

import { ProtectedRoute } from '../ProtectedRoute'
import { useAuthStore } from '@/store/authStore'

/**
 * Probe component: surfaces the current pathname and `location.state.from` so
 * the test can assert both the redirect target and that the original
 * destination is preserved for post-login return.
 */
function LocationProbe() {
  const loc = useLocation()
  const from =
    (loc.state as { from?: { pathname?: string } } | null)?.from?.pathname ?? ''
  return (
    <>
      <div data-testid="probe-pathname">{loc.pathname}</div>
      <div data-testid="probe-from">{from}</div>
    </>
  )
}

describe('ProtectedRoute — unauthenticated redirect', () => {
  beforeEach(() => {
    useAuthStore.setState({
      user: null,
      token: null,
      isAuthenticated: false,
      isLoading: false,
    })
  })

  it('redirects unauthenticated visits to /home → / and preserves origin in state.from', () => {
    render(
      <MemoryRouter initialEntries={['/home']}>
        <Routes>
          <Route
            path="/home"
            element={
              <ProtectedRoute>
                <div data-testid="home-content">home</div>
              </ProtectedRoute>
            }
          />
          <Route path="/" element={<LocationProbe />} />
        </Routes>
      </MemoryRouter>,
    )

    // The protected page should not render.
    expect(screen.queryByTestId('home-content')).not.toBeInTheDocument()

    // We landed on / (the public landing route), not /landing.
    expect(screen.getByTestId('probe-pathname')).toHaveTextContent('/')
    expect(screen.getByTestId('probe-from')).toHaveTextContent('/home')
  })
})
