"use client";

import { useEffect } from "react";
import { SignUp } from "@clerk/nextjs";
import AuthLayout from "@/components/auth/auth-layout";

const CLERK_APPEARANCE = {
  variables: {
    colorPrimary: "#0F172A",
    colorText: "#1E293B",
    colorBackground: "#FFFFFF",
    borderRadius: "0.5rem",
    fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif",
  },
  elements: {
    formButtonPrimary: "bg-[#0F172A] hover:bg-[#1E293B] shadow-md",
    card: "shadow-none border-0 p-0 w-full",
    headerTitle: "text-xl font-bold",
    headerSubtitle: "text-slate-500",
    socialButtonsBlockButton: "border border-slate-200 hover:bg-slate-50",
    formFieldInput: "border-slate-300 focus:border-[#0F172A] focus:ring-[#0F172A] w-full",
    rootBox: "w-full",
    cardBox: "w-full shadow-none",
    header: "hidden",
    footer: "hidden",
    otpCodeFieldInputs: "gap-2",
    otpCodeFieldInput: "w-10 h-12 text-base touch-manipulation",
  },
};

export default function SignUpPage() {
  useEffect(() => {
    // iOS Safari suppresses the soft keyboard when focus comes from a
    // programmatic .focus() call rather than a user gesture. Clerk's
    // <SignUp /> auto-focuses inputs across multiple internal views
    // (email, then verification code, then any subsequent factor),
    // and the parent component does NOT unmount between view swaps.
    //
    // This effect tracks user gestures on the document with capture-
    // phase listeners (so we record intent BEFORE Clerk's own
    // listeners see the event), and only blurs when no user gesture
    // happened in the last 350ms. Programmatic auto-focus gets
    // blurred; user-tap focus is left alone so iOS opens the
    // keyboard. Mirrors the behavior in the sign-in page.
    if (typeof window === "undefined") return;
    if (!window.matchMedia("(hover: none) and (pointer: coarse)").matches) return;

    let lastUserInteractionAt = 0;
    const recordInteraction = () => { lastUserInteractionAt = Date.now(); };

    document.addEventListener("touchstart", recordInteraction, { capture: true, passive: true });
    document.addEventListener("pointerdown", recordInteraction, { capture: true, passive: true });
    document.addEventListener("click", recordInteraction, { capture: true, passive: true });

    const blurIfProgrammatic = () => {
      const el = document.activeElement;
      if (!el || el === document.body) return;
      if (!("blur" in el)) return;
      if (Date.now() - lastUserInteractionAt < 350) return;
      (el as HTMLElement).blur();
    };

    const initialTimers = [0, 50, 200, 500].map((d) =>
      window.setTimeout(blurIfProgrammatic, d),
    );

    const observer = new MutationObserver(() => {
      blurIfProgrammatic();
      window.setTimeout(blurIfProgrammatic, 50);
      window.setTimeout(blurIfProgrammatic, 200);
    });
    observer.observe(document.body, { childList: true, subtree: true });

    // OTP auto-advance fix: mirrors sign-in page. Clerk calls box[n+1].focus()
    // programmatically after each digit — iOS hides the keyboard on programmatic
    // focus. Blur the auto-advanced box 20ms after each digit so the user's next
    // tap fires a fresh focus event that iOS recognises as a gesture.
    const handleOtpDigitInput = (e: Event) => {
      const target = e.target as HTMLInputElement;
      if (target.tagName !== "INPUT" || target.maxLength !== 1) return;
      window.setTimeout(() => {
        const focused = document.activeElement as HTMLInputElement | null;
        if (focused && focused !== target && focused.maxLength === 1) {
          focused.blur();
        }
      }, 20);
    };
    document.addEventListener("input", handleOtpDigitInput, { capture: true });

    return () => {
      document.removeEventListener("touchstart", recordInteraction, { capture: true } as EventListenerOptions);
      document.removeEventListener("pointerdown", recordInteraction, { capture: true } as EventListenerOptions);
      document.removeEventListener("click", recordInteraction, { capture: true } as EventListenerOptions);
      document.removeEventListener("input", handleOtpDigitInput, { capture: true } as EventListenerOptions);
      initialTimers.forEach((t) => window.clearTimeout(t));
      observer.disconnect();
    };
  }, []);

  return (
    <AuthLayout mode="sign-up">
      <div className="w-full max-w-[320px] mx-auto">
        <SignUp
          appearance={CLERK_APPEARANCE}
          forceRedirectUrl="/website-upload"
          signInUrl="/sign-in"
        />
      </div>
    </AuthLayout>
  );
}
