"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from "react";
import { AuthModal, type AuthModalView } from "@/components/landing/auth-modal";

type AuthModalContextValue = {
  openAuth: (view?: AuthModalView) => void;
  closeAuth: () => void;
};

const AuthModalContext = createContext<AuthModalContextValue | null>(null);

export function useAuthModal() {
  const ctx = useContext(AuthModalContext);
  if (!ctx) {
    throw new Error("useAuthModal must be used within LandingAuthProvider");
  }
  return ctx;
}

export function LandingAuthProvider({
  children,
  initialAuth = null,
}: {
  children: ReactNode;
  initialAuth?: AuthModalView | null;
}) {
  const [open, setOpen] = useState(Boolean(initialAuth));
  const [view, setView] = useState<AuthModalView>(initialAuth ?? "register");

  const openAuth = useCallback((next: AuthModalView = "register") => {
    setView(next);
    setOpen(true);
  }, []);

  const closeAuth = useCallback(() => {
    setOpen(false);
  }, []);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const auth = params.get("auth");
    if (auth === "login" || auth === "register") {
      openAuth(auth);
    }
  }, [openAuth]);

  const value = useMemo(
    () => ({ openAuth, closeAuth }),
    [openAuth, closeAuth],
  );

  return (
    <AuthModalContext.Provider value={value}>
      {children}
      <AuthModal
        open={open}
        view={view}
        onViewChange={setView}
        onClose={closeAuth}
      />
    </AuthModalContext.Provider>
  );
}
