import { notFound } from 'next/navigation'
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import ResponsiveIframe from '@/app/components/responsive-iframe';
import { redirect } from 'next/navigation';

// Use environment variables for real service URLs
const menuItems: Record<string, string> = {
  parole: process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL || '',
  alma: process.env.NEXT_PUBLIC_IFRAME_AI_ASSISTANT_URL || '',
  crm: process.env.NEXT_PUBLIC_IFRAME_MEDIATIONS_URL || '',
  vision: process.env.NEXT_PUBLIC_IFRAME_CONFERENCE_URL || '',
  showcase: process.env.NEXT_PUBLIC_IFRAME_SHOWCASE_URL || '',
  agilite: process.env.NEXT_PUBLIC_IFRAME_AGILITY_URL || '',
  dossiers: process.env.NEXT_PUBLIC_IFRAME_DRIVE_URL || '',
  'the-message': process.env.NEXT_PUBLIC_IFRAME_THEMESSAGE_URL || '',
  qg: process.env.NEXT_PUBLIC_IFRAME_MISSIONVIEW_URL || '',
  // Use environment variables for these items too
  board: process.env.NEXT_PUBLIC_IFRAME_BOARD_URL || '',
  chapter: process.env.NEXT_PUBLIC_IFRAME_CHAPTER_URL || '',
  flow: process.env.NEXT_PUBLIC_IFRAME_FLOW_URL || '',
  design: process.env.NEXT_PUBLIC_IFRAME_DESIGN_URL || '',
  artlab: process.env.NEXT_PUBLIC_IFRAME_DESIGN_URL || '',
  // External URLs
  gitlab: "https://gitlab.com",
  missions: process.env.NEXT_PUBLIC_IFRAME_MISSIONSBOARD_URL || ''
}

// Using a different approach for metadata that doesn't directly access params.section
export async function generateMetadata({ params }: { params: { section: string } }) {
  // Safely handle params
  const paramsObj = await Promise.resolve(params);
  const sectionName = paramsObj?.section || '';
  
  // Capitalize first letter
  const title = sectionName ? 
    sectionName.charAt(0).toUpperCase() + sectionName.slice(1) : 
    'Section';
    
  return { title };
}

export default async function SectionPage(props: { params: { section: string } }) {
  // Ensure authentication first
  const session = await getServerSession(authOptions);
  if (!session) {
    redirect("/signin");
  }

  // Safely extract section using await Promise.resolve
  const params = await Promise.resolve(props.params);
  const section = params?.section || '';
  
  // Check if section exists in our menu items
  if (!section || !(section in menuItems)) {
    notFound();
  }

  // Get the direct URL for this section
  const directUrl = menuItems[section];

  return (
    <div className="w-full h-[calc(100vh-8rem)]">
      <ResponsiveIframe 
        src={directUrl}
        className="w-full h-full border-none"
        allowFullScreen={true}
      />
    </div>
  )
}

