'use client';
import { FunctionComponent, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';

import { APP_ROLES, ROUTES, type AppRole } from '@/constants';
import { useMe } from '@/services/auth';
import { resolvePostLoginDestination } from '@/services/auth/routing';
import AuthSplash from './AuthSplash';

interface RoleRouterProps {
  /** The role the user logged in as (A1 vs B1); disambiguates a multi-role user and pre-selects on SelectRole. */
  intendedRole?: AppRole;
  /** The `?next=` deep link carried from middleware.ts's redirect-to-login, if any. */
  next?: string | null;
}

/**
 * Runs after authentication (never re-implements the auth gate — the middleware owns that) and
 * sends the user to the right app: a validated `next` deep link when the session's roles permit
 * it, else customer → family, nurse → nurse app, no role → SelectRole, admin → admin console.
 * Shows the branded splash while `/me` is in flight so the wrong shell never flashes.
 * @component RoleRouter
 */
const RoleRouter: FunctionComponent<RoleRouterProps> = ({ intendedRole, next }) => {
  const router = useRouter();
  const locale = useLocale();
  const t = useTranslations('auth');
  const { data: me, isError } = useMe();

  useEffect(() => {
    if (isError) {
      router.replace(`/${locale}${ROUTES.LOGIN}`);
      return;
    }
    if (!me) return;

    let destination = resolvePostLoginDestination(me, intendedRole, next);
    // Carry the login intent into role selection so it can pre-select the right role.
    if (destination === ROUTES.SELECT_ROLE && intendedRole === APP_ROLES.NURSE) {
      destination = `${destination}?role=${APP_ROLES.NURSE}`;
    }
    router.replace(`/${locale}${destination}`);
  }, [me, isError, intendedRole, next, router, locale]);

  return <AuthSplash message={t('routing_title')} />;
};

export default RoleRouter;
