import { useState, useEffect, useMemo } from 'react';
import { useAuth } from './hooks/useAuth';
import Login from './components/Login';
import Layout from './components/Layout';
import JobList from './components/JobList';
import JobSubmission from './components/JobSubmission';
import AdminPanel from './components/AdminPanel';
import ErrorBoundary from './components/ErrorBoundary';
import LoadingSpinner from './components/LoadingSpinner';
import './styles/index.css';

function App() {
  const { user, loading, refresh } = useAuth();
  const [activeTab, setActiveTab] = useState('jobs');

  // Memoize login component to ensure it's ready immediately
  const loginComponent = useMemo(() => <Login key="login" />, []);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-900">
        <LoadingSpinner size="md" />
      </div>
    );
  }

  if (!user) {
    return loginComponent;
  }

  // Wrapper to change tabs - only check auth on mount, not on every navigation
  const handleTabChange = (newTab) => {
    setActiveTab(newTab);
  };

  return (
    <Layout activeTab={activeTab} onTabChange={handleTabChange}>
      <ErrorBoundary>
        {activeTab === 'jobs' && <JobList />}
        {activeTab === 'submit' && (
          <JobSubmission onSuccess={() => handleTabChange('jobs')} />
        )}
        {activeTab === 'admin' && <AdminPanel />}
      </ErrorBoundary>
    </Layout>
  );
}

export default App;

