import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, act } from '@testing-library/react';
import { MemoryRouter, Route, Routes, Navigate } from 'react-router-dom';
import { ProtectedRoute } from '@/routes/ProtectedRoute';
import { useAuthStore } from '@/store/authStore';

function ProtectedTest() {
  return (
    <MemoryRouter initialEntries={['/dashboard']}>
      <Routes>
        <Route path="/login" element={<div data-testid="login-page">Login</div>} />
        <Route path="/dashboard" element={
          <ProtectedRoute>
            <div data-testid="protected-content">Protected</div>
          </ProtectedRoute>
        } />
      </Routes>
    </MemoryRouter>
  );
}

describe('Router & ProtectedRoute', () => {
  it('redirects to /login when not authenticated', () => {
    useAuthStore.setState({ isAuthenticated: false, user: null });
    render(<ProtectedTest />);
    expect(screen.getByTestId('login-page')).toBeInTheDocument();
    expect(screen.queryByTestId('protected-content')).not.toBeInTheDocument();
  });

  it('shows protected content when authenticated', () => {
    useAuthStore.setState({
      isAuthenticated: true,
      user: { id: '1', email: 'test@test.de', first_name: 'Test', last_name: 'User', role: 'admin', avatar_url: null, tenants: [{ id: 't1', name: 'Test Tenant', slug: 'test' }] },
      currentTenant: { id: 't1', name: 'Test Tenant', slug: 'test' },
    });
    render(<ProtectedTest />);
    expect(screen.getByTestId('protected-content')).toBeInTheDocument();
    expect(screen.queryByTestId('login-page')).not.toBeInTheDocument();
    useAuthStore.setState({ isAuthenticated: false, user: null });
  });
});
