// app/scholarships/[id]/page.js
import React from 'react';
import ScholarshipDetail from '../../../components/organisms/ScholarshipDetail';

// Single API call to get scholarship detail and related scholarships
async function getScholarshipData(slug) { 
  try {
    const res = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/frontend/scholarships/${slug}?include_related=true&include_faqs=true`, {
      method: 'GET',
      cache: 'no-store'
    });

    if (!res.ok) {
      throw new Error('Failed to fetch scholarship data');
    }

    const data = await res.json();
    return data.data || null;
  } catch (error) {
    console.error('Error fetching scholarship data:', error);
    return null;
  }
}

// Generate FAQ Schema Markup
function generateFAQSchema(faqs) {
  if (!faqs || faqs.length === 0) return null;

  const faqSchema = {
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    'mainEntity': faqs.map(faq => ({
      '@type': 'Question',
      'name': faq.question,
      'acceptedAnswer': {
        '@type': 'Answer',
        'text': faq.answer
      }
    }))
  };

  return faqSchema;
}

// Generate Article Schema Markup (Alternative approach)
function generateArticleSchema(scholarship) {
  if (!scholarship) return null;

  const articleSchema = {
    '@context': 'https://schema.org',
    '@type': 'Article',
    'headline': scholarship.title,
    'description': scholarship.description?.replace(/<[^>]*>/g, '').substring(0, 300),
    'image': `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${scholarship.image}`,
    'author': {
      '@type': 'Organization',
      'name': 'Universities Page'
    },
    'publisher': {
      '@type': 'Organization',
      'name': 'Universities Page',
      'logo': {
        '@type': 'ImageObject',
        'url': `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/logo.png`
      }
    },
    'datePublished': scholarship.created_at,
    'dateModified': new Date().toISOString(),
    'mainEntityOfPage': {
      '@type': 'WebPage',
      '@id': `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/scholarships/${scholarship.slug}`
    },
    'keywords': [
      scholarship.title,
      `${scholarship.country_name} scholarships`,
      ...(scholarship.qualifications?.map(q => `${q.qualification_name} scholarships`) || [])
    ].join(', ')
  };

  return articleSchema;
}


export async function generateMetadata({ params }) {
  const { slug } = await params;
  const scholarshipData = await getScholarshipData(slug);
  
  if (!scholarshipData || !scholarshipData.scholarship) {
    return {
      title: 'Scholarship Not Found - Study Abroad Scholarships',
      description: 'The requested scholarship could not be found. Browse our available study abroad scholarships.',
    };
  }

  const { scholarship } = scholarshipData;
  const cleanDescription = scholarship.description?.replace(/<[^>]*>/g, '').substring(0, 160) || 'Study abroad scholarship opportunity for international students.';
  
  const scholarshipImage = scholarship.image ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${scholarship.image}` : `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/default-scholarship-og.jpg`;

  // Generate keywords based on scholarship data
  const keywords = [
    scholarship.title,
    `${scholarship.country_name} scholarships`,
    ...(scholarship.qualifications?.map(q => `${q.qualification_name} scholarships`) || []),
    'study abroad funding',
    'international scholarships',
    'education funding',
    'student grants',
    'academic scholarships'
  ].filter(Boolean);

  return {
    title: `${scholarship.title}`,
    description: cleanDescription,
    keywords: keywords,
    authors: [{ name: 'Universities Page' }],
    publisher: 'Universities Page',
    robots: 'index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1',
    openGraph: {
      title: scholarship.title,
      description: cleanDescription,
      url: `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/scholarships/${scholarship.slug}`,
      siteName: 'Universities Page',
      images: [
        {
          url: scholarshipImage,
          width: 1200,
          height: 630,
          alt: scholarship.title,
        },
      ],
      locale: 'en_US',
      type: 'article',
      publishedTime: scholarship.created_at,
      modifiedTime: new Date().toISOString(),
    },
    twitter: {
      card: 'summary_large_image',
      site: '@studyabroad',
      creator: '@studyabroad',
      title: scholarship.title,
      description: cleanDescription,
      images: [scholarshipImage],
    },
    alternates: {
      canonical: `${process.env.NEXT_PUBLIC_APP_URL_DOMAIN}/scholarships/${scholarship.slug}`,
    }
  };
}

const Page = async ({ params }) => {
  const { slug } = await params;
  const scholarshipData = await getScholarshipData(slug);
  
  if (!scholarshipData || !scholarshipData.scholarship) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-900 mb-4">Scholarship Not Found</h1>
          <p className="text-gray-600">The requested scholarship could not be found.</p>
        </div>
      </div>
    );
  }

  const { scholarship, faqs } = scholarshipData;

  // Generate all schema markups
  const faqSchema = generateFAQSchema(faqs);
  const articleSchema = generateArticleSchema(scholarship); // Using Article schema as primary

  return (
    <div>
      {/* Structured Data Schema Markup */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(articleSchema)
        }}
      />
      {faqSchema && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify(faqSchema)
          }}
        />
      )}

      <ScholarshipDetail 
        scholarshipData={scholarshipData}
        params={params}
      />
    </div>
  );
}

export default Page;