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 './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">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-500"></div>
      </div>
    );
  }

  if (!user) {
    return loginComponent;
  }

  // Wrapper to check auth before changing tabs
  const handleTabChange = async (newTab) => {
    // Check auth before allowing navigation
    try {
      await refresh();
      // If refresh succeeds, user is still authenticated
      setActiveTab(newTab);
    } catch (error) {
      // Auth check failed, user will be set to null and login will show
      console.error('Auth check failed on navigation:', error);
    }
  };

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

export default App;

