"use client"

import { useEffect, useState, useRef } from "react"
import { useRouter, usePathname } from "next/navigation"
import { Sidebar } from "./Sidebar"
import Topbar from "./Topbar"
import { SessionExpiryBanner } from "@/src/components/app/SessionExpiryBanner"
import { hasValidAccessToken } from "@/src/lib/api/session"
import { FullPageLoader } from "@/src/components/app/FullPageLoader"

export function AdminShell({ children }: { children: React.ReactNode }) {
  const router  = useRouter()
  const pathname = usePathname()
  const [ready, setReady] = useState(false)
  const checked = useRef(false)

  // Vérification auth une seule fois au montage — pas à chaque navigation
  useEffect(() => {
    if (checked.current) return
    checked.current = true

    const locale = pathname.split("/")[1] || "fr"

    if (!hasValidAccessToken()) {
      router.replace(`/${locale}/admin/login`)
      return
    }
    try {
      const me = JSON.parse(localStorage.getItem("acx_me") ?? "null")
      if (!me?.is_superuser) {
        router.replace(`/${locale}/admin/login`)
        return
      }
    } catch {}
    setReady(true)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  if (!ready) return <FullPageLoader />

  return (
    <div className="h-screen overflow-hidden flex" style={{ background: "#f1f5f9" }}>
      <Sidebar />

      <div className="flex-1 min-w-0 flex flex-col overflow-hidden">
        {/* Topbar */}
        <header className="shrink-0 z-20">
          <div
            className="flex items-center px-6 py-3"
            style={{
              background: "#fff",
              borderBottom: "1px solid rgba(15,23,42,0.07)",
              boxShadow: "0 1px 8px rgba(26,53,120,0.05)",
            }}
          >
            <Topbar />
          </div>
          {/* Accent line */}
          <div
            className="h-[2px] w-full"
            style={{ background: "linear-gradient(90deg, #1a3578 0%, #2655b0 40%, #4dba96 100%)" }}
          />
        </header>

        <main className="flex-1 min-h-0 p-6 overflow-y-auto">
          {children}
        </main>
      </div>

      <SessionExpiryBanner />
    </div>
  )
}
