"use client";

import { AuthGuard } from "@/components/AuthGuard";
import { useMe } from "@/hooks/useMe";
import { useRouter, usePathname } from "next/navigation";
import { useEffect } from "react";
import { LoadingState, ErrorState } from "@/components/ds";
import { ExperiencePortalShell } from "@/modules/experience/components/ExperiencePortalShell";

export type ExperiencePortalId = "studio";

function PortalGate({ children }: { children: React.ReactNode }) {
  const { me, loading, error, reload } = useMe();
  const router = useRouter();

  useEffect(() => {
    if (loading) return;
    if (me?.onboarding_required) router.replace("/onboarding");
  }, [me, loading, router]);

  if (loading) return <LoadingState label="در حال آماده‌سازی تربت پیجز…" />;
  if (error) {
    return (
      <ErrorState
        message={typeof error === "string" ? error : "خطا در بارگذاری نشست کاربر"}
        onRetry={reload}
      />
    );
  }
  if (!me?.current_tenant_id) {
    return <ErrorState message="برای استفاده از تربت پیجز workspace فعال لازم است." />;
  }

  return <ExperiencePortalShell>{children}</ExperiencePortalShell>;
}

export function createPortalLayout(_portalId: ExperiencePortalId) {
  return function PortalLayout({ children }: { children: React.ReactNode }) {
    return (
      <AuthGuard>
        <PortalGate>{children}</PortalGate>
      </AuthGuard>
    );
  };
}

export function ExperienceRootLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const isHub = pathname === "/experience/hub";
  const isPreview = pathname.startsWith("/experience/preview/");

  if (isHub || isPreview) {
    return <AuthGuard>{children}</AuthGuard>;
  }

  return (
    <AuthGuard>
      <PortalGate>{children}</PortalGate>
    </AuthGuard>
  );
}
