"use client";

import Link from "next/link";
import dynamic from "next/dynamic";
import { useParams, useSearchParams } from "next/navigation";
import { UI, type Lang } from "@/lib/config";
import BrandLogo from "@/components/BrandLogo";
import AuthBackButton from "@/components/auth/AuthBackButton";
import ClerkWidgetSkeleton from "@/components/auth/ClerkWidgetSkeleton";

const ClerkSignUp = dynamic(
  () => import("@clerk/nextjs").then((mod) => mod.SignUp),
  {
    ssr: false,
    loading: () => <ClerkWidgetSkeleton />,
  },
);

function resolveRedirectTarget(value: string | null, fallback: string): string {
  if (!value?.startsWith("/")) {
    return fallback;
  }

  if (value.startsWith("//")) {
    return fallback;
  }

  return value;
}

export default function ClerkSignupPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const lang = (params?.lang as Lang) || "en";
  const dir = UI[lang].dir;
  const isAr = lang === "ar";
  const redirectTarget = resolveRedirectTarget(
    searchParams.get("redirect_url"),
    `/${lang}/onboarding`,
  );

  const features = isAr
    ? [
        { icon: "⚡", text: "إعداد سريع — اشترك وابدأ في دقائق" },
        { icon: "🌍", text: "مدعوم باللغتين العربية والإنجليزية" },
        { icon: "🔒", text: "بيانات آمنة، مستضافة في منطقة الخليج" },
      ]
    : [
        { icon: "⚡", text: "Quick setup — sign up and go live in minutes" },
        { icon: "🌍", text: "Fully bilingual Arabic & English support" },
        { icon: "🔒", text: "Secure, GCC-hosted infrastructure" },
      ];

  const stats = isAr
    ? [
        { n: "١٧+", l: "قطاع" },
        { n: "٨٥٪", l: "تقليل الغياب" },
        { n: "٢٤/٧", l: "متاح دائماً" },
      ]
    : [
        { n: "17+", l: "verticals" },
        { n: "85%", l: "fewer no-shows" },
        { n: "24/7", l: "AI availability" },
      ];

  return (
    <div className="flex flex-col md:flex-row min-h-screen" dir={dir}>
      {/* ── Left Brand Panel ── */}
      <div className="hidden md:flex md:w-[52%] overflow-hidden relative">
        <div className="absolute inset-0 bg-gradient-to-br from-[#0F9972] via-[#0b8560] to-[#054f3b]" />

        <div
          className="absolute inset-0 opacity-[0.06]"
          style={{
            backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23ffffff'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/svg%3E")`,
          }}
        />

        <div className="absolute -top-20 -right-20 w-80 h-80 rounded-full bg-white/[0.05]" />
        <div className="absolute -bottom-16 -left-16 w-64 h-64 rounded-full bg-white/[0.05]" />
        <div className="absolute bottom-1/3 -right-10 w-44 h-44 rounded-full bg-white/[0.04]" />

        <div className="relative z-10 flex flex-col justify-between p-14 w-full min-h-screen">
          <BrandLogo href={`/${lang}`} size="lg" tone="light" />

          <div className="space-y-10">
            <div className="space-y-4">
              <h1 className="text-[2.6rem] font-bold text-white leading-[1.15] tracking-tight">
                {isAr ? (
                  <>
                    ابدأ رحلتك مع
                    <br />
                    موعدي اليوم
                  </>
                ) : (
                  <>
                    Start managing
                    <br />
                    appointments smarter
                  </>
                )}
              </h1>
              <p className="text-[#a7f3d0] text-[1.05rem] leading-relaxed max-w-xs">
                {isAr
                  ? "انضم إلى آلاف الأعمال في الخليج التي تعتمد على موعدي لتبسيط الحجوزات."
                  : "Join thousands of GCC businesses using Mawidi to automate bookings and reduce no-shows."}
              </p>
            </div>

            <ul className="space-y-4">
              {features.map((f, i) => (
                <li key={i} className="flex items-start gap-3.5">
                  <span className="w-10 h-10 rounded-xl bg-white/15 flex items-center justify-center text-[1.1rem] shrink-0">
                    {f.icon}
                  </span>
                  <span className="text-white/85 text-[0.9rem] leading-snug pt-2">
                    {f.text}
                  </span>
                </li>
              ))}
            </ul>

            <div className="grid grid-cols-3 gap-4 pt-6 border-t border-white/15">
              {stats.map((s, i) => (
                <div key={i} className="text-center">
                  <div className="text-2xl font-bold text-white tracking-tight">
                    {s.n}
                  </div>
                  <div className="text-[0.7rem] text-white/55 mt-0.5 uppercase tracking-wide">
                    {s.l}
                  </div>
                </div>
              ))}
            </div>
          </div>

          <p className="text-white/35 text-xs">
            {isAr ? "موعدي © ٢٠٢٦" : "© 2026 Mawidi · Made for the GCC"}
          </p>
        </div>
      </div>

      {/* Right Form Panel */}
      <div className="relative flex-1 overflow-hidden bg-[#EEF2F6] px-6 py-10 md:min-h-screen md:px-14 md:py-12">
        <div className="pointer-events-none absolute inset-x-0 top-0 h-48 bg-gradient-to-b from-white/70 to-transparent" />
        <div className="pointer-events-none absolute -right-20 top-24 h-64 w-64 rounded-full bg-[#0F9972]/10 blur-3xl" />
        <div className="pointer-events-none absolute -left-20 bottom-20 h-72 w-72 rounded-full bg-cyan-200/20 blur-3xl" />

        <div className="relative mx-auto flex min-h-full w-full max-w-[29rem] flex-col justify-center">
          <div className="mb-10">
            <div className="mb-6 flex items-center justify-between gap-4">
              <AuthBackButton fallbackHref={`/${lang}`} isAr={isAr} />
              <div className="md:hidden">
                <BrandLogo href={`/${lang}`} size="sm" />
              </div>
            </div>
            <p className="text-[0.68rem] font-semibold uppercase tracking-[0.22em] text-[#0F9972]">
              {isAr ? "إنشاء الحساب" : "Create Account"}
            </p>
            <h2 className="mt-2 text-[2.2rem] font-bold leading-[1.08] tracking-tight text-slate-900">
              {isAr ? "أنشئ حسابك" : "Create your account"}
            </h2>
            <p className="mt-2 text-[0.96rem] leading-relaxed text-slate-600">
              {isAr
                ? "انضم إلى موعدي وابدأ في دقائق"
                : "Join Mawidi and get started in minutes"}
            </p>
          </div>

          <ClerkSignUp
            forceRedirectUrl={redirectTarget}
            fallbackRedirectUrl={redirectTarget}
            signInUrl={`/${lang}/clerk-login`}
            appearance={{
              layout: {
                logoPlacement: "none",
                socialButtonsVariant: "blockButton",
                socialButtonsPlacement: "top",
              },
              variables: {
                colorPrimary: "#0F9972",
                colorText: "#1e293b",
                colorTextSecondary: "#64748b",
                colorBackground: "#ffffff",
                colorInputBackground: "#f8fafc",
                colorInputText: "#1e293b",
                borderRadius: "0.875rem",
                fontFamily: isAr
                  ? "var(--font-ar), Cairo, system-ui"
                  : "var(--font-en), Inter, system-ui",
              },
              elements: {
                rootBox: "w-full",
                cardBox: "w-full",
                card: "!w-full !rounded-[1.3rem] !border !border-slate-200/80 !bg-white !p-6 sm:!p-7 !shadow-[0_28px_48px_-32px_rgba(15,23,42,0.55)]",
                main: "!gap-5",
                header: "hidden",
                formFieldLabel: "!text-[0.78rem] !font-medium !text-slate-700",
                formFieldInput:
                  "!h-11 !rounded-xl !border-slate-300/90 !bg-slate-50 focus:!ring-2 focus:!ring-[#0F9972]/20 focus:!border-[#0F9972]",
                formButtonPrimary:
                  "!h-11 !rounded-xl !bg-gradient-to-r !from-[#0F9972] !to-[#0B7F5E] hover:!from-[#0E8D68] hover:!to-[#0A6D52] !font-semibold !tracking-[0.01em] !shadow-[0_14px_26px_-16px_rgba(15,153,114,0.95)]",
                socialButtonsBlockButton:
                  "!h-11 !rounded-xl !border-slate-300/90 !bg-white hover:!bg-slate-50 transition-colors",
                socialButtonsBlockButtonText: "!text-slate-700 !font-medium",
                dividerLine: "!bg-slate-200",
                dividerText: "!text-slate-400 !text-xs !font-medium",
                identityPreviewEditButton: "!text-[#0F9972]",
                footerActionLink: "!text-[#0F9972] hover:underline",
                footer: "hidden",
              },
            }}
          />

          <p className="mt-7 text-center text-sm text-slate-600">
            {isAr ? "لديك حساب بالفعل؟" : "Already have an account?"}{" "}
            <Link
              href={`/${lang}/clerk-login`}
              className="font-semibold text-[#0F9972] hover:underline"
            >
              {isAr ? "سجّل الدخول" : "Sign in"}
            </Link>
          </p>

          <div className="mt-4 flex items-center justify-center gap-4 text-xs text-slate-400">
            <Link
              href={`/${lang}/privacy`}
              className="transition-colors hover:text-[#0F9972]"
            >
              {isAr ? "الخصوصية" : "Privacy"}
            </Link>
            <span>·</span>
            <Link
              href={`/${lang}/terms`}
              className="transition-colors hover:text-[#0F9972]"
            >
              {isAr ? "الشروط" : "Terms"}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
