"use client";

import { useQuery } from "@tanstack/react-query";
import { useTenantId } from "@/hooks/useTenantId";
import { useMe } from "@/hooks/useMe";

/** Permission checks — backend is authoritative; owner gets full access in UI. */
export function useExperiencePermissions() {
  const { tenantId } = useTenantId();
  const { me } = useMe();

  const membership = me?.memberships.find((m) => m.tenant_id === tenantId);
  const isOwner = membership?.is_owner ?? false;
  const isPlatformAdmin = me?.platform_role === "platform_admin";

  const can = (permission?: string) => {
    if (!permission) return true;
    if (isOwner || isPlatformAdmin) return true;
    if (permission.endsWith(".view") || permission === "experience.view") return !!tenantId;
    return false;
  };

  const canManage = (viewPerm?: string, managePerm?: string) => {
    if (isOwner || isPlatformAdmin) return true;
    if (managePerm) return can(managePerm);
    if (viewPerm) return can(viewPerm.replace(".view", ".manage"));
    return can("experience.manage");
  };

  return {
    can,
    canManage,
    isOwner,
    isLoading: false,
  };
}
