"use client";
/**
 * Glassmorphism + 3D auth backdrop: floating frosted dashboard tiles in a perspective scene that tilts with the pointer
 * (or device orientation), glowing blue orbs and a soft grid. Pure CSS 3D transforms — no WebGL, light on mobile.
 */
import { useEffect, useRef, type ReactNode } from "react";
import { ArrowUpRight, BarChart3, Bot, MessageCircle, ShieldCheck, Users } from "lucide-react";

export function AuthLayout({ children, title, subtitle, wide = false }: { children: ReactNode; title: string; subtitle?: string; wide?: boolean }) {
  const scene = useRef<HTMLDivElement>(null);
  const card = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) return;
    let raf = 0;
    const apply = (x: number, y: number) => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        scene.current?.style.setProperty("--rx", `${(-y * 10).toFixed(2)}deg`);
        scene.current?.style.setProperty("--ry", `${(x * 14).toFixed(2)}deg`);
        card.current?.style.setProperty("--crx", `${(-y * 3).toFixed(2)}deg`);
        card.current?.style.setProperty("--cry", `${(x * 4).toFixed(2)}deg`);
      });
    };
    const onMove = (e: PointerEvent) => apply(e.clientX / window.innerWidth - 0.5, e.clientY / window.innerHeight - 0.5);
    const onTilt = (e: DeviceOrientationEvent) => apply(Math.max(-1, Math.min(1, (e.gamma ?? 0) / 45)) / 2, Math.max(-1, Math.min(1, ((e.beta ?? 45) - 45) / 45)) / 2);
    window.addEventListener("pointermove", onMove);
    window.addEventListener("deviceorientation", onTilt);
    return () => { window.removeEventListener("pointermove", onMove); window.removeEventListener("deviceorientation", onTilt); cancelAnimationFrame(raf); };
  }, []);

  const productName = process.env.NEXT_PUBLIC_PRODUCT_NAME ?? "Tempest Pulse";
  return (
    <div className="relative min-h-dvh overflow-hidden bg-[#EAF1FF] text-ink dark:bg-[#060B1A]">
      {/* glow field */}
      <div className="pointer-events-none absolute inset-0" aria-hidden>
        <div className="absolute -left-40 -top-40 h-[620px] w-[620px] animate-[float_14s_ease-in-out_infinite] rounded-full bg-[#3B82F6]/35 blur-[120px]" />
        <div className="absolute -right-40 top-1/4 h-[560px] w-[560px] animate-[float_18s_ease-in-out_infinite_reverse] rounded-full bg-[#8B7CF6]/30 blur-[120px]" />
        <div className="absolute bottom-[-220px] left-1/3 h-[520px] w-[520px] animate-[float_16s_ease-in-out_infinite] rounded-full bg-[#38BDF8]/25 blur-[120px]" />
        <div className="absolute inset-0 opacity-[.35] [background-image:linear-gradient(rgb(37_99_235/.08)_1px,transparent_1px),linear-gradient(90deg,rgb(37_99_235/.08)_1px,transparent_1px)] [background-size:44px_44px] [mask-image:radial-gradient(ellipse_at_center,black,transparent_75%)]" />
      </div>

      <div className="relative mx-auto grid min-h-dvh max-w-[1280px] items-center gap-10 px-4 py-8 lg:grid-cols-[1.1fr_1fr] lg:px-10">
        {/* 3D scene */}
        <div className="relative hidden h-[620px] lg:block" style={{ perspective: "1400px" }} aria-hidden>
          <div ref={scene} className="absolute inset-0 transition-transform duration-300 ease-out [transform-style:preserve-3d]" style={{ transform: "rotateX(calc(8deg + var(--rx, 0deg))) rotateY(calc(-14deg + var(--ry, 0deg)))" }}>
            {/* main dashboard tile */}
            <div className="glass-3d absolute left-[6%] top-[12%] w-[440px] rounded-[28px] p-5" style={{ transform: "translateZ(40px)" }}>
              <div className="flex items-center gap-2"><span className="h-2.5 w-2.5 rounded-full bg-[#ff5f57]" /><span className="h-2.5 w-2.5 rounded-full bg-[#febc2e]" /><span className="h-2.5 w-2.5 rounded-full bg-[#28c840]" /><span className="ml-3 text-[12px] font-semibold text-ink-2">Overview</span></div>
              <div className="mt-4 text-[22px] font-extrabold tracking-tight">Good morning 👋</div>
              <div className="mt-4 grid grid-cols-2 gap-3">
                <div className="hero-blue rounded-[20px] p-4"><div className="text-[11px] opacity-80">Revenue won</div><div className="mt-1 text-[26px] font-extrabold">৳2.4 Cr</div><div className="mt-2 inline-flex rounded-full bg-white/20 px-2 py-0.5 text-[10.5px]">▲ 18% this month</div></div>
                <div className="rounded-[20px] bg-white/70 p-4 dark:bg-white/5"><div className="text-[11px] text-ink-3">New leads</div><div className="mt-1 text-[26px] font-extrabold">976</div><div className="mt-2 flex h-8 items-end gap-1">{[30, 55, 40, 70, 50, 85, 65].map((h, i) => <span key={i} className="flex-1 rounded-t bg-gradient-to-t from-brand to-[#8B7CF6]" style={{ height: `${h}%` }} />)}</div></div>
              </div>
              <div className="mt-3 flex h-24 items-end gap-2 rounded-[20px] bg-white/60 p-3 dark:bg-white/5">{[45, 62, 38, 80, 58, 92, 70, 84].map((h, i) => <span key={i} className={`flex-1 rounded-t-[6px] ${i % 2 ? "bg-[#8B7CF6]/80" : "bg-ink/80 dark:bg-white/70"}`} style={{ height: `${h}%` }} />)}</div>
            </div>
            {/* floating chips */}
            <div className="glass-3d absolute left-[58%] top-[6%] flex w-[220px] items-center gap-3 rounded-[20px] p-3.5 animate-[bob_6s_ease-in-out_infinite]" style={{ transform: "translateZ(140px)" }}>
              <span className="grid h-10 w-10 place-items-center rounded-full bg-[#22c55e]/15 text-[#16a34a]"><MessageCircle className="h-5 w-5" /></span>
              <div><div className="text-[12.5px] font-bold">New WhatsApp lead</div><div className="text-[11px] text-ink-3">Replied in 42 sec</div></div>
            </div>
            <div className="glass-3d absolute left-[64%] top-[44%] w-[230px] rounded-[20px] p-4 animate-[bob_7s_ease-in-out_infinite_1s]" style={{ transform: "translateZ(110px)" }}>
              <div className="flex items-center gap-2 text-[12px] font-bold"><Bot className="h-4 w-4 text-violet" />AI assistant</div>
              <p className="mt-2 rounded-[12px] bg-violet/10 px-3 py-2 text-[11.5px] text-ink-2">“3 hot leads need a call today. Want me to create the tasks?”</p>
            </div>
            <div className="glass-3d absolute left-[50%] top-[66%] flex w-[250px] items-center gap-3 rounded-[20px] p-3.5 animate-[bob_8s_ease-in-out_infinite_.5s]" style={{ transform: "translateZ(90px)" }}>
              <span className="grid h-10 w-10 place-items-center rounded-full bg-brand/15 text-brand"><ShieldCheck className="h-5 w-5" /></span>
              <div><div className="text-[12.5px] font-bold">Protected sign-in</div><div className="text-[11px] text-ink-3">Passkeys · 2FA · encryption</div></div>
            </div>
            <div className="glass-3d absolute left-[20%] top-[66%] flex items-center gap-2 rounded-full px-4 py-2.5 animate-[bob_6.5s_ease-in-out_infinite_2s]" style={{ transform: "translateZ(160px)" }}>
              <BarChart3 className="h-4 w-4 text-brand" /><span className="text-[12px] font-bold">Win rate 22.5%</span><ArrowUpRight className="h-3.5 w-3.5 text-ok" />
            </div>
            <div className="absolute left-[38%] top-[-2%] h-24 w-24 rounded-full bg-gradient-to-br from-white/90 to-[#93C5FD]/50 shadow-[inset_-8px_-10px_24px_rgb(37_99_235/.35),0_20px_40px_-10px_rgb(37_99_235/.45)] animate-[bob_9s_ease-in-out_infinite]" style={{ transform: "translateZ(200px)" }} />
            <div className="absolute left-[88%] top-[70%] h-14 w-14 rounded-full bg-gradient-to-br from-white/90 to-[#C4B5FD]/60 shadow-[inset_-6px_-8px_18px_rgb(124_108_240/.4),0_16px_30px_-10px_rgb(124_108_240/.5)] animate-[bob_7s_ease-in-out_infinite_1.5s]" style={{ transform: "translateZ(180px)" }} />
          </div>
          <div className="absolute bottom-0 left-[6%] max-w-[460px]">
            <div className="text-[34px] font-extrabold leading-[1.1] tracking-tight [font-family:var(--font-syne)]">Every lead, campaign and conversation — <span className="bg-gradient-to-r from-brand to-[#8B7CF6] bg-clip-text text-transparent">one beautiful workspace.</span></div>
            <div className="mt-3 flex items-center gap-4 text-[12.5px] text-ink-2"><span className="inline-flex items-center gap-1.5"><Users className="h-4 w-4 text-brand" />Built for teams</span><span className="inline-flex items-center gap-1.5"><Bot className="h-4 w-4 text-violet" />AI & voice assistant</span></div>
          </div>
        </div>

        {/* form card */}
        <div className="relative mx-auto w-full" style={{ perspective: "1600px", maxWidth: wide ? 560 : 440 }}>
          <div ref={card} className="glass-3d relative animate-sheet rounded-[30px] p-6 transition-transform duration-300 ease-out sm:p-8" style={{ transform: "rotateX(var(--crx, 0deg)) rotateY(var(--cry, 0deg))" }}>
            <div className="pointer-events-none absolute inset-x-8 -top-px h-px bg-gradient-to-r from-transparent via-white to-transparent" />
            <div className="mb-6 flex items-center gap-3">
              <span className="grid h-11 w-11 place-items-center rounded-[14px] bg-gradient-to-br from-[#4F8BFF] to-[#1D3FBF] shadow-[0_10px_24px_-8px_rgb(37_99_235/.7)]"><img src="/icon.svg" alt="" className="h-7 w-7 brightness-0 invert" /></span>
              <div><div className="text-[16px] font-extrabold leading-none [font-family:var(--font-syne)]">{productName}</div><div className="mt-1 text-[11.5px] text-ink-3">by Brand Tempest</div></div>
            </div>
            <h1 className="text-[26px] font-extrabold leading-tight tracking-tight">{title}</h1>
            {subtitle && <p className="mt-1.5 text-[13.5px] text-ink-2">{subtitle}</p>}
            <div className="mt-6">{children}</div>
          </div>
        </div>
      </div>
    </div>
  );
}
