"use client";

import React, { useEffect, useRef, useState } from "react";
import { ShieldCheck, X } from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { AuthForm } from "./AuthForm";

interface AuthModalProps {
  isOpen: boolean;
  onClose: () => void;
  initialMode?: "login" | "signup";
}

/**
 * Landing-page auth dialog. The body is the same `AuthForm` the /auth routes
 * render, so validation, states and copy never drift between the two surfaces.
 */
export function AuthModal({ isOpen, onClose, initialMode = "login" }: AuthModalProps) {
  const { language } = useI18n();
  const isDe = language === "de";
  const [mode, setMode] = useState<"login" | "signup">(initialMode);
  const dialogRef = useRef<HTMLDivElement>(null);
  const restoreFocusRef = useRef<HTMLElement | null>(null);

  useEffect(() => {
    if (isOpen) setMode(initialMode);
  }, [isOpen, initialMode]);

  useEffect(() => {
    if (!isOpen) return;

    restoreFocusRef.current = document.activeElement as HTMLElement | null;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    // Land focus inside the dialog so the next Tab stays in context.
    dialogRef.current?.focus();

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.stopPropagation();
        onClose();
        return;
      }
      if (event.key !== "Tab") return;

      // Minimal focus trap: wrap between the first and last focusable element.
      const focusable = dialogRef.current?.querySelectorAll<HTMLElement>(
        'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])'
      );
      if (!focusable || focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];

      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      document.body.style.overflow = previousOverflow;
      restoreFocusRef.current?.focus?.();
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-start sm:items-center justify-center overflow-y-auto p-4 sm:p-6 bg-black/60 backdrop-blur-sm auth-fade"
      onClick={onClose}
      role="presentation"
    >
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-label={
          mode === "login"
            ? isDe
              ? "Anmeldung"
              : "Sign in"
            : isDe
            ? "Konto erstellen"
            : "Create account"
        }
        tabIndex={-1}
        onClick={(event) => event.stopPropagation()}
        className="relative w-full max-w-[440px] my-auto bg-white border border-[#E2E8F0] shadow-2xl p-6 sm:p-8 font-sans focus:outline-none auth-pop"
      >
        <button
          type="button"
          onClick={onClose}
          className="absolute top-3 right-3 w-9 h-9 flex items-center justify-center text-[#747779] hover:text-black hover:bg-[#F8FAFC] transition-colors"
          aria-label={isDe ? "Schließen" : "Close"}
        >
          <X className="w-5 h-5" aria-hidden="true" />
        </button>

        <AuthForm
          mode={mode}
          compact
          onBeforeNavigate={onClose}
          onSwitchMode={() => setMode(mode === "login" ? "signup" : "login")}
        />

        <p className="mt-5 pt-4 border-t border-[#F1F5F9] flex items-center justify-center gap-1.5 text-[11.5px] text-[#64748B]">
          <ShieldCheck className="w-3.5 h-3.5 text-emerald-600 shrink-0" aria-hidden="true" />
          {isDe
            ? "Sicher gespeichert • von jedem Gerät abrufbar"
            : "Stored securely • accessible from any device"}
        </p>
      </div>
    </div>
  );
}
