'use client';

import { ReactNode } from 'react';
import { usePathname } from 'next/navigation';
import { PermissionGuard } from '@/components/common/PermissionGuard';
import { useAuthGuard } from '@/hooks/useAuthGuard';
import { useTranslation } from '@/hooks/useTranslation';
import { MeetingAttendanceNavbar } from '@/features/meeting-attendance/components/MeetingAttendanceNavbar';
import { MEETING_ATTENDANCE_ROLES } from '@/features/meeting-attendance/constants/roles';
import { getEnvBannerVariant } from '@/lib/env-banner';

interface MeetingAttendanceLayoutProps {
  children: ReactNode;
}

export default function MeetingAttendanceLayout({ children }: MeetingAttendanceLayoutProps) {
  const pathname = usePathname();
  const { t } = useTranslation();
  const isGuestPath = pathname.startsWith('/meetingattendance/checkin/guest');
  // 议程查看页全屏：/meetingattendance/{id}/agenda（不含 /edit）
  const isAgendaFullscreen = /^\/meetingattendance\/[^/]+\/agenda$/.test(pathname);
  const hideNavbar =
    isGuestPath || pathname.startsWith('/meetingattendance/teams') || isAgendaFullscreen;
  const { isReady } = useAuthGuard({ enabled: !isGuestPath });
  const envBannerVariant = getEnvBannerVariant();
  const showUatBanner = envBannerVariant === 'uat' && pathname === '/meetingattendance/dashboard';

  if (!isGuestPath && !isReady) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">{t.common.loading}</p>
        </div>
      </div>
    );
  }

  const content = (
    <div className="min-h-screen bg-gray-50">
      {showUatBanner && (
        <div
          className="h-7 px-6 flex items-center justify-center text-xs font-medium"
          style={{ backgroundColor: '#FF7D00', color: '#FFFFFF' }}
          data-testid="env-banner"
        >
          <span className="mr-2">{t.common.envBannerUatTitle}</span>
          <span className="opacity-90">{t.common.envBannerUatDesc}</span>
        </div>
      )}
      {!hideNavbar && <MeetingAttendanceNavbar />}
      <main className={isAgendaFullscreen ? '' : 'py-6'}>
        {isAgendaFullscreen ? (
          children
        ) : (
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">{children}</div>
        )}
      </main>
    </div>
  );

  if (isGuestPath) {
    return content;
  }

  return (
    <PermissionGuard roles={MEETING_ATTENDANCE_ROLES}>
      {content}
    </PermissionGuard>
  );
}
