"use client";

import { AuthGuard } from "@/components/AuthGuard";
import { AccountingShell } from "@/components/accounting/AccountingShell";
import { useMe } from "@/hooks/useMe";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { LoadingState, ErrorState } from "@/components/ds";

function AccountingGate({ 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={error} onRetry={reload} />;
  if (!me?.current_tenant_id) {
    return (
      <ErrorState message="برای استفاده از حسابداری باید یک workspace فعال داشته باشید." />
    );
  }
  return <AccountingShell>{children}</AccountingShell>;
}

export default function AccountingLayout({ children }: { children: React.ReactNode }) {
  return (
    <AuthGuard>
      <AccountingGate>{children}</AccountingGate>
    </AuthGuard>
  );
}
