"use client";

import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useProfile } from "@/lib/profile/context";
import { SKIP_SIGNUP_KEY } from "@/lib/site";
import { addAnalyticsEvent } from "@/lib/profile/db";

const PUBLIC_PATHS = [
  "/account",
  "/setup/ui",
  "/privacy",
  "/terms",
  "/cookies",
  "/dmca",
  "/about",
  "/contact",
];

function isPublicPath(pathname: string | null): boolean {
  if (!pathname) return true;
  return PUBLIC_PATHS.some(
    (p) => pathname === p || pathname.startsWith(`${p}/`),
  );
}

/**
 * First visit → force account creation (then theme picker via signup flow).
 * Guests can opt out once via Skip; legal pages stay reachable.
 */
export function OnboardingGate() {
  const { ready, account, profile } = useProfile();
  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    if (!ready || isPublicPath(pathname)) return;
    if (account) return;
    try {
      if (localStorage.getItem(SKIP_SIGNUP_KEY) === "1") return;
    } catch {
      return;
    }
    router.replace("/account?welcome=1");
  }, [ready, account, pathname, router]);

  useEffect(() => {
    if (!ready || !pathname || isPublicPath(pathname)) return;
    void addAnalyticsEvent({
      type: "page_view",
      accountId: account?.id,
      profileId: profile?.id,
      label: pathname,
      at: Date.now(),
    });
  }, [ready, pathname, account?.id, profile?.id]);

  return null;
}
