import { headers } from "next/headers";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { getDict, type dictionaries } from "@/i18n/dictionaries";
import { LoginForm } from "@/components/admin/login-form";
import { isLocale } from "@/i18n/routes";
import { verifySession } from "@/lib/auth/session";

type Dict = (typeof dictionaries)[keyof typeof dictionaries];

export default async function LoginPage({
  searchParams,
}: {
  searchParams: Promise<{ next?: string }>;
}) {
  const h = await headers();
  const locale = isLocale(h.get("x-locale") ?? "") ? (h.get("x-locale") as "de" | "en") : "de";
  const dict: Dict = getDict(locale);

  // Wenn bereits eingeloggt → direkt weiter zum Dashboard (oder zur ursprünglich
  // angeforderten Seite). Spart einen Roundtrip und verhindert UX-Reibung.
  const cookieStore = await cookies();
  const session = cookieStore.get("eldov_admin")?.value;
  if (verifySession(session)) {
    const sp = await searchParams;
    const target = sp.next && sp.next.startsWith("/admin") && !sp.next.startsWith("/admin/login")
      ? sp.next
      : "/admin/dashboard";
    redirect(target);
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-[var(--bg)] px-4">
      <div className="w-full max-w-md space-y-6">
        <div>
          <p className="font-mono text-xs uppercase tracking-wider text-muted">eldov.win</p>
          <h1 className="mt-1 text-2xl font-semibold">{dict.admin.loginTitle}</h1>
          <p className="mt-2 text-sm text-muted">{dict.admin.loginIntro}</p>
        </div>
        <LoginForm locale={locale} />
      </div>
    </div>
  );
}
