"use client"

import { useEffect, useState } from "react"
import { useRouter, usePathname } from "next/navigation"
import { Home, FolderOpen, FileText, LifeBuoy, User, Activity, LogOut, Menu, X } from "lucide-react"

const navItems = [
  { href: "/client-portal/dashboard", label: "Dashboard", icon: Home },
  { href: "/client-portal/projects", label: "Projects", icon: FolderOpen },
  { href: "/client-portal/invoices", label: "Invoices", icon: FileText },
  { href: "/client-portal/support", label: "Support", icon: LifeBuoy },
  { href: "/client-portal/activity", label: "Activity", icon: Activity },
  { href: "/client-portal/profile", label: "Profile", icon: User },
]

export default function ClientPortalLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter()
  const pathname = usePathname()
  const [auth, setAuth] = useState<boolean | null>(null)
  const [sidebarOpen, setSidebarOpen] = useState(false)

  useEffect(() => {
    fetch("/api/auth/me", { credentials: "include" })
      .then((r) => r.json())
      .then((data) => {
        if (data.role === "client") setAuth(true)
        else { setAuth(false); router.push("/client-portal/login") }
      })
      .catch(() => { setAuth(false); router.push("/client-portal/login") })
  }, [router])

  const handleLogout = async () => {
    await fetch("/api/auth/logout", { method: "POST" })
    router.push("/client-portal/login")
  }

  if (auth === null) {
    return (
      <div className="flex min-h-screen bg-[#0a0a0f] items-center justify-center">
        <div className="w-8 h-8 border-2 border-[#1BB0CE] border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  if (!auth) return null

  if (pathname === "/client-portal/login") return <>{children}</>

  return (
    <div className="flex min-h-screen bg-[#0a0a0f]">
      {/* Mobile overlay */}
      {sidebarOpen && (
        <div className="fixed inset-0 bg-black/50 z-40 lg:hidden" onClick={() => setSidebarOpen(false)} />
      )}

      {/* Sidebar */}
      <aside className={`fixed lg:static inset-y-0 left-0 z-50 w-64 bg-[#0d1117] border-r border-[#1a1a24] transform transition-transform duration-200 ${sidebarOpen ? "translate-x-0" : "-translate-x-full"} lg:translate-x-0 flex flex-col`}>
        <div className="p-5 border-b border-[#1a1a24]">
          <div className="text-lg font-bold">
            <span className="text-[#1BB0CE]">Client</span>
            <span className="text-white"> Portal</span>
          </div>
        </div>

        <nav className="flex-1 p-3 space-y-1">
          {navItems.map((item) => {
            const Icon = item.icon
            const active = pathname.startsWith(item.href)
            return (
              <button
                key={item.href}
                onClick={() => { router.push(item.href); setSidebarOpen(false) }}
                className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm transition-all ${
                  active
                    ? "bg-[#1BB0CE]/10 text-[#1BB0CE] border border-[#1BB0CE]/20"
                    : "text-[#8a8a95] hover:text-white hover:bg-[#1a1a24]"
                }`}
              >
                <Icon className="h-4 w-4" />
                {item.label}
              </button>
            )
          })}
        </nav>

        <div className="p-3 border-t border-[#1a1a24]">
          <button
            onClick={handleLogout}
            className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-[#8a8a95] hover:text-red-400 hover:bg-red-400/5 transition-all"
          >
            <LogOut className="h-4 w-4" />
            Logout
          </button>
        </div>
      </aside>

      {/* Main content */}
      <div className="flex-1 flex flex-col min-h-screen">
        <header className="sticky top-0 z-30 bg-[#0d1117]/80 backdrop-blur-md border-b border-[#1a1a24] px-4 lg:px-6 h-14 flex items-center">
          <button className="lg:hidden mr-3 text-[#8a8a95] hover:text-white" onClick={() => setSidebarOpen(true)}>
            <Menu className="h-5 w-5" />
          </button>
          <span className="text-sm text-[#6a6a75]">Client Portal</span>
        </header>

        <main className="flex-1 p-4 lg:p-6">
          {children}
        </main>
      </div>
    </div>
  )
}
