import { redirect } from "next/navigation";
import { getTranslations, setRequestLocale } from "next-intl/server";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { AccountSidebar, type AccountNavItem } from "@/components/account/AccountSidebar";

export const dynamic = "force-dynamic";

// Geteiltes Sidebar-Dashboard-Layout für den gesamten Konto-Bereich:
// links Avatar/Name + Navigation (klebt beim Scrollen), rechts der
// wechselnde Seiteninhalt. Feste 1080px-Spalte, kein vw-Rand.
export default async function AccountLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  setRequestLocale(locale);

  const clientId = await getSessionClientId();
  if (!clientId) redirect(`/${locale}/login`);

  await connectDB();
  const [client, isStaff] = await Promise.all([
    Client.findById(clientId).select("firstName nickname name avatarPath").lean(),
    isAdminSession(),
  ]);
  if (!client) redirect(`/${locale}/login`);

  const t = await getTranslations({ locale });
  const isEn = locale === "en";

  const nav: AccountNavItem[] = [
    { href: "/account", label: isEn ? "Overview" : "Übersicht", exact: true },
    { href: "/account/orders", label: t("orders.allOrdersTitle") },
    { href: "/account/photos", label: t("photos.myPhotos") },
    { href: "/account/wishlist", label: t("characterWishes.myWishlist") },
    { href: "/account/conventions", label: t("conventionWaitlist.myWaitlists") },
    { href: "/account/invoices", label: t("orders.myInvoices") },
    { href: "/account/vouchers", label: t("orders.myVouchers") },
    { href: "/account/profile", label: isEn ? "Profile" : "Profil" },
    ...(isStaff ? [{ href: "/account/qm", label: "QM / Personal" }] : []),
  ];

  const name = client.nickname || client.firstName || client.name;
  const avatarUrl = client.avatarPath ? `/api/avatars/${String(client._id)}/${client.avatarPath}` : null;

  return (
    <main className="min-h-screen bg-[var(--rk-bg)] pt-28 pb-20">
      <div className="mx-auto grid max-w-[1080px] gap-x-10 gap-y-8 px-5 sm:px-8 lg:grid-cols-[15rem_1fr]">
        <AccountSidebar
          name={name}
          avatarUrl={avatarUrl}
          nav={nav}
          adminHref={isStaff ? `/${locale}/admin/orders` : undefined}
          adminLabel={isEn ? "Admin area" : "Admin-Bereich"}
          locale={locale}
          logoutLabel={t("auth.logout")}
        />
        <div className="min-w-0">{children}</div>
      </div>
    </main>
  );
}
