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 || '',
  // Keep any existing custom ones, but use environment variables when available
  board: "https://example.com/board",
  chapter: "https://example.com/chapter",
  flow: "https://example.com/flow",
  design: process.env.NEXT_PUBLIC_IFRAME_DESIGN_URL || "https://example.com/design",
  gitlab: "https://gitlab.com",
  missions: "https://example.com/missions"
}

// 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();
  }

  // Create the proxy URL instead of direct iframe URL
  const proxyUrl = `/api/proxy/${section}`;

  return (
    <div className="w-full h-[calc(100vh-8rem)]">
      <ResponsiveIframe 
        src={proxyUrl}
        className="w-full h-full border-none"
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
      />
    </div>
  )
}

