import { useState, useContext, useEffect } from "react"

import Sidebar from "./components/Sidebar"

import Dashboard from "./Pages/Dashboard"
import LoginPage from "./Pages/LoginPage"
import AdminDashboard from "./Pages/AdminDashboard"
import HistoryPembelian from "./Pages/HistoryPembelian"

import { AuthContext } from "./context/AuthContext"

export default function App() {

  const { user } = useContext(AuthContext)

  const [page, setPage] = useState("dashboard")

  // 🔥 AUTO SET PAGE BERDASARKAN ROLE
  useEffect(() => {

    if (!user) return

    const role = user?.role?.toLowerCase()

    if (role === "admin") {
      setPage("admin")
    } else {
      setPage("dashboard")
    }

  }, [user])

  // 🔥 BELUM LOGIN
  if (!user) {
    return <LoginPage />
  }

  return (
    <div style={{ display: "flex" }}>

      {/* SIDEBAR */}
      <Sidebar setPage={setPage} />

      {/* CONTENT */}
      <div
        style={{
          flex: 1,
          background: "#020617",
          minHeight: "100vh",
          color: "white"
        }}
      >

        {/* USER DASHBOARD */}
        {page === "dashboard" && <Dashboard />}

        {/* HISTORY PEMBELIAN */}
        {page === "history" && <HistoryPembelian />}

        {/* ADMIN DASHBOARD */}
        {page === "admin" && <AdminDashboard />}

      </div>

    </div>
  )
}