
import * as ActionIcons from '@/components/Icons';
import Link from 'next/link';
import { redirect } from 'next/navigation';
import { api, isStaff, me } from '@/lib/api';
import { Sidebar } from '@/components/Nav';
import { KeyIcon } from '@/components/Icons';
import { logout } from '../actions';
import { PUBLIC_SITE } from '@/lib/format';

export const dynamic = 'force-dynamic';

export default async function StaffLayout({ children }: { children: React.ReactNode }) {
  const user = await me();
  if (user.mustChangePassword) redirect('/change-password');
  if (!isStaff(user.role)) redirect('/portal');
  const ov = await api<{ queues: Record<string, number> }>('/admin/overview').catch(() => ({ queues: {} as Record<string, number> }));
  return (
    <div className="min-h-screen lg:grid lg:grid-cols-[16rem_1fr]">
      <Sidebar counts={{ ...ov.queues, notifications: user.unreadNotifications }}user={{ email: user.email, name: user.name, role: user.role, mfa: user.mfa }} publicSite={PUBLIC_SITE} logout={logout} />
      <main className="min-w-0 px-4 py-6 sm:px-8 sm:py-8">
        <div className="mx-auto max-w-[90rem]">
          {!user.mfaEnabled && (
            <div className="mb-6 flex flex-wrap items-center gap-3 rounded-lg border border-brass/40 bg-brass-soft px-4 py-3 text-sm">
              <KeyIcon className="h-4 w-4 text-brass" />
              <span className="flex-1 text-ink-2">Staff accounts should use two-factor authentication.</span>
              <Link href="/settings" className="btn btn-quiet btn-xs">
                <ActionIcons.ShieldCheckIcon />Turn it on
              </Link>
            </div>
          )}
          {children}
        </div>
      </main>
    </div>
  );
}
