"use client";

import React, { useEffect, useState } from "react";
import { useParams, usePathname, useRouter } from "next/navigation";
import DataService from "@/config/axios";
import { isLimitedClientPersona, workspacePersonaFromMe } from "@/lib/workspace-persona";

/**
 * Restricts `/client/*` and `/property/*` for occupants and management staff to
 * complaints and profile only. Owners and super admins keep full navigation.
 */
export default function ClientWorkspaceRouteGuard({
  children,
}: {
  children: React.ReactNode;
}) {
  const params = useParams();
  const app = params?.app as string | undefined;
  const pathname = usePathname() || "";
  const router = useRouter();
  const [checked, setChecked] = useState(false);

  useEffect(() => {
    if (app !== "client" && app !== "property") {
      setChecked(true);
      return;
    }

    let cancelled = false;
    (async () => {
      try {
        const res = await DataService.get("/user/me");
        const me = res.data?.data;
        if (cancelled) return;
        const persona = workspacePersonaFromMe(me);

        if (!isLimitedClientPersona(persona)) {
          setChecked(true);
          return;
        }

        const prefix = `/${app}`;
        if (!pathname.startsWith(prefix)) {
          setChecked(true);
          return;
        }

        const rest = pathname.slice(prefix.length) || "/";
        if (rest.startsWith("/chat")) {
          router.replace(`${prefix}/complaints`);
          setChecked(true);
          return;
        }

        if (rest === "/dashboard" || rest === "/") {
          router.replace(`${prefix}/complaints`);
          setChecked(true);
          return;
        }

        const allowed = rest.startsWith("/complaints") || rest.startsWith("/profile");
        if (!allowed) {
          router.replace(`${prefix}/complaints`);
          setChecked(true);
          return;
        }

        setChecked(true);
      } catch {
        if (!cancelled) setChecked(true);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [app, pathname, router]);

  if ((app === "client" || app === "property") && !checked) {
    return (
      <div className="rounded-md border bg-white p-8 text-center text-sm text-muted-foreground">
        Loading…
      </div>
    );
  }

  return <>{children}</>;
}
