import React, { useState } from 'react';
import axios from 'axios';
import Sidebar from './components/sidebar';
import Login from './pages/login';
import Dashboard from './pages/Dashboard'; // Newly Integrated Analytics view layer
import Product from './pages/product';
import Sales from './pages/sales';
import StockStatus from './pages/stockStatus'; // Kept consistently lower-case matching file frameworks
import Report from './pages/report';

// Ensure cookie-based sessions pass through cross-origin calls
axios.defaults.withCredentials = true;

function App() {
  const [user, setUser] = useState(null);
  // Default user view path routed straight into the newly created dashboard
  const [activePage, setPage] = useState('dashboard');

  const handleLoginSuccess = (username) => {
    setUser(username);
  };

  const handleLogout = async () => {
    if (window.confirm("Are you sure you want to log out of the management system?")) {
      try {
        await axios.post('http://localhost:5000/api/auth/logout');
        setUser(null);
        setPage('dashboard'); // Reset back to default view state on exit
      } catch (err) {
        alert('Error clearing backend session parameters.');
      }
    }
  };

  // If user is not logged in, render the login layout component
  if (!user) {
    return <Login onLoginSuccess={handleLoginSuccess} />;
  }

  // Once authenticated successfully, display the core enterprise dashboard layout workspace
  return (
    <div className="min-h-screen bg-slate-100 flex flex-col md:flex-row antialiased">
      {/* Structural Sidebar Navigation */}
      <Sidebar 
        activePage={activePage} 
        setPage={setPage} 
        handleLogout={handleLogout} 
        username={user} 
      />
      
      {/* Workspace Area mapping active layout view state */}
      <main className="flex-1 p-4 sm:p-6 md:p-8 w-full max-w-7xl mx-auto overflow-y-auto">
        {activePage === 'dashboard' ? (
          // Render dashboard without a card background for beautiful, componentized sections
          <Dashboard />
        ) : (
          // Wrapped core management tools within standard data workspace sheet containers
          <div className="bg-white rounded-2xl border border-slate-200/60 p-5 md:p-8 shadow-sm transition-all duration-200 min-h-[calc(100vh-4rem)] md:min-h-0">
            {activePage === 'products' && <Product />}
            {activePage === 'sales' && <Sales />}
            {activePage === 'stockstatus' && <StockStatus />}
            {activePage === 'reports' && <Report />}
          </div>
        )}
      </main>
    </div>
  );
}

export default App;