import type { ReactNode } from "react";
import { Navigate, Outlet } from "react-router";

import { useAuth } from "@/context/auth-context";

function AuthLogo() {
  return (
    <div className="mx-auto grid size-12 place-items-center rounded-2xl bg-primary text-primary-foreground shadow-lg shadow-primary/20">
      <div className="relative size-8 overflow-hidden rounded-lg bg-primary-foreground/20">
        <span className="absolute left-1.5 top-2 h-1 w-6 rounded-full bg-white" />
        <span className="absolute left-1 top-3.5 h-1 w-7 rounded-full bg-white/90" />
        <span className="absolute left-2 top-5 h-1 w-6 rounded-full bg-white/80" />
      </div>
    </div>
  );
}

export function AuthPanel({ children }: { children: ReactNode }) {
  return (
    <section className="relative z-10 w-full max-w-[460px] rounded-2xl border border-border/50 bg-card px-6 py-8 shadow-xl shadow-primary/[0.04] sm:px-9">
      <div className="pointer-events-none absolute inset-x-0 top-0 h-32 overflow-hidden rounded-t-2xl">
        <div className="absolute inset-0 bg-[linear-gradient(var(--border)_1px,transparent_1px),linear-gradient(90deg,var(--border)_1px,transparent_1px)] bg-[size:38px_38px] opacity-40 [mask-image:linear-gradient(to_bottom,black,transparent)]" />
        <div className="absolute inset-x-10 top-0 h-24 bg-primary/10 blur-2xl" />
      </div>
      {children}
    </section>
  );
}

export function AuthHeader({
  title,
  description,
}: {
  title: string;
  description: string;
}) {
  return (
    <header className="relative text-center">
      <AuthLogo />
      <h1 className="mt-6 text-2xl font-heading font-semibold tracking-normal text-foreground">
        {title}
      </h1>
      <p className="mt-2 text-base text-muted-foreground">{description}</p>
    </header>
  );
}

export default function AuthLayout() {
  const { isAuthenticated, isLoading } = useAuth();

  if (isAuthenticated) {
    return <Navigate replace to="/" />;
  }

  return (
    <main className="min-h-svh bg-background px-4 py-6 text-foreground">
      <div className="relative mx-auto grid min-h-[calc(100svh-3rem)] w-full max-w-5xl place-items-center overflow-hidden">
        <div className="pointer-events-none absolute inset-0 bg-[linear-gradient(var(--border)_1px,transparent_1px),linear-gradient(90deg,var(--border)_1px,transparent_1px)] bg-[size:72px_72px] opacity-35 [mask-image:radial-gradient(circle_at_center,black,transparent_70%)]" />
        <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_center,var(--primary),transparent_55%)] opacity-10" />
        {isLoading ? (
          <div className="relative z-10 text-sm font-mono font-medium text-muted-foreground">
            Loading…
          </div>
        ) : (
          <Outlet />
        )}
      </div>
    </main>
  );
}