"use client";

import { useEffect, useState, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import AdminSidebar from "./components/admin-sidebar";

export default function AdminLayout({ children }: { children: ReactNode }) {
  const router = useRouter();
  const [checked, setChecked] = useState(false);
  const [allowed, setAllowed] = useState(false);

  useEffect(() => {
    fetch("/api/admin/health")
      .then((r) => { setAllowed(r.ok); if (!r.ok) router.replace("/dashboard"); })
      .catch(() => { setAllowed(false); router.replace("/dashboard"); })
      .finally(() => setChecked(true));
  }, [router]);

  if (!checked) return <div className="flex items-center justify-center h-screen bg-slate-50"><div className="w-8 h-8 border-4 border-slate-200 border-t-slate-600 rounded-full animate-spin" /></div>;
  if (!allowed) return null;

  return (
    <div className="flex min-h-screen bg-slate-100">
      <AdminSidebar />
      <main className="flex-1 p-6 overflow-auto">{children}</main>
    </div>
  );
}
