"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { AdminShell } from "@/components/admin/admin-shell";
import { apiFetch } from "@/lib/admin-api";

type SessionUser = {
  id: string;
  name: string;
  email: string;
  role: string;
  avatar?: string | null;
};

export default function AdminDashboardLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const [user, setUser] = useState<SessionUser | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const me = await apiFetch<SessionUser>("/api/auth/me");
        if (!alive) return;
        const adminRoles = ["SUPER_ADMIN", "ADMIN", "EDITOR", "STAFF"];
        if (!adminRoles.includes(me.role)) {
          await apiFetch("/api/auth/logout", { method: "POST" }).catch(() => undefined);
          router.replace("/admin/login");
          return;
        }
        setUser(me);
      } catch {
        if (!alive) return;
        router.replace("/admin/login");
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => {
      alive = false;
    };
  }, [router]);

  if (loading || !user) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-bg text-muted">
        Loading admin…
      </div>
    );
  }

  return <AdminShell user={user}>{children}</AdminShell>;
}
