"use client";

import type { AumCalcMode } from "@/app/customer/[tenant]/settings/_lib/aum-mode-api";
import { canAccessSettingsSection } from "@/app/customer/[tenant]/settings/_lib/settings-section-permissions";
import { HeaderPreferenceBadge } from "@/app/customer/_components/header-preference-badge";
import { useAumCalcMode } from "@/app/customer/_lib/use-aum-calc-mode";

export { AUM_MODE_CHANGED_EVENT, dispatchAumModeChanged } from "@/app/customer/_lib/aum-mode-events";

type AumModeHeaderBadgeProps = {
  tenant: string;
  allowedRoutes?: readonly string[];
  className?: string;
  /** When provided (batched shell loader), skip the standalone hook fetch. */
  mode?: AumCalcMode | null;
  loading?: boolean;
};

export function AumModeHeaderBadge({
  tenant,
  allowedRoutes,
  className,
  mode: modeProp,
  loading: loadingProp,
}: AumModeHeaderBadgeProps) {
  const canSee = canAccessSettingsSection("general", allowedRoutes ?? []);
  const standalone = useAumCalcMode(canSee && modeProp === undefined);
  const mode = modeProp !== undefined ? modeProp : standalone.mode;
  const loading = loadingProp !== undefined ? loadingProp : standalone.loading;

  if (!canSee || loading || !mode) return null;

  const isNet = mode === "net";

  return (
    <HeaderPreferenceBadge
      tenant={tenant}
      hrefPath="/settings?section=general"
      title="AUM calculation mode — open Settings"
      className={className}
      toneClassName={
        isNet
          ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-400"
          : undefined
      }
    >
      {isNet ? "AUM: Net" : "AUM: Gross"}
    </HeaderPreferenceBadge>
  );
}
