import { lexend } from '@/app/fonts';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { ServerUnavailable } from '@/components/crm/ServerUnavailable';
import { ToastProvider } from '@/components/crm/ToastProvider';
import { SESSION_COOKIE } from '@/config/constants';
import { CurrentUserProvider } from '@/features/auth/CurrentUser';
import { getMyProfile } from '@/features/settings/api.server';
import { UserPrefsProvider } from '@/features/settings/UserPrefs';
import { isApiError } from '@/lib/api/errors';
import '@/styles/crm-app.css';
import { getMeOnceMore, isServerTrouble, meErrorCode } from '@/lib/auth/load-me';

/**
 * B12 Manage views: a full-window page with its own top bar, opened in a new tab from a list's
 * Add view menu. The 28 Oct design draws it without the sidebar and top bar (`$layout` other than
 * `app`, includes/header.php:41, :109), so this layout has the `(app)` layout's sign-in, user,
 * preferences and toasts, but not `AppShell`. The sequence editor (`/sequences/new/edit`,
 * `/sequences/[id]`) uses it too: HubSpot draws that one full-screen (DYN-02, EDT-44).
 */
export default async function ManageLayout({ children }: { children: React.ReactNode }) {
  const profileLoad = getMyProfile().catch(() => null);
  let me;
  try {
    me = await getMeOnceMore();
  } catch (err) {
    if (isApiError(err) && err.isUnauthenticated) {
      // A session cookie the API no longer accepts: the session expired (QA #585).
      const hadSession = Boolean((await cookies()).get(SESSION_COOKIE)?.value);
      redirect(hadSession ? '/login?error=session_expired' : '/login');
    }
    // HUB-746 (940): the server's trouble says nothing about the session. Stay on this address
    // and offer to try again, rather than send a signed-in user to the login page.
    if (isServerTrouble(err)) return <ServerUnavailable />;
    redirect(`/login?error=${meErrorCode(err)}`);
  }

  if (!me.onboarding.completed) {
    redirect('/onboarding/role');
  }

  const profile = await profileLoad;

  return (
    <div className={lexend.className}>
      <CurrentUserProvider key={me.business.id} me={me}>
        <UserPrefsProvider initialProfile={profile}>
          <ToastProvider>{children}</ToastProvider>
        </UserPrefsProvider>
      </CurrentUserProvider>
    </div>
  );
}
