import Header from "@/components/Header";
import Hero from "@/components/Hero";
import About from "@/components/About";
import Services from "@/components/Services";
import Gallery from "@/components/Gallery";
import InstagramFeed from "@/components/InstagramFeed";
import Contact from "@/components/Contact";
import Footer from "@/components/Footer";
import { getDictionary } from "../dictionaries";
import { prisma } from "@/lib/db";

async function getInstagramData() {
  try {
    const res = await fetch('https://instagram120.p.rapidapi.com/api/instagram/posts', {
      method: 'POST',
      headers: {
        'x-rapidapi-key': process.env.RAPIDAPI_KEY || '',
        'x-rapidapi-host': 'instagram120.p.rapidapi.com',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: 'moy_akyaka',
        maxId: ''
      }),
      next: { revalidate: 3600 } // 1 hour to prevent CDN link expiration
    });

    if (!res.ok) {
      console.error('Instagram verisi çekilemedi:', await res.text());
      return [];
    }

    const data = await res.json();
    const edges = data?.result?.edges || [];
    
    // Get the first 4 posts and map them
    return edges.slice(0, 4).map((edge: any) => ({
      id: edge.node.id || edge.node.code,
      url: `https://www.instagram.com/p/${edge.node.code}/`,
      imageUrl: edge.node.image_versions2?.candidates?.[0]?.url || edge.node.display_uri || '',
      caption: edge.node.caption?.text || '',
      isVideo: edge.node.media_type === 2
    }));
  } catch (error) {
    console.error('Instagram API hatası:', error);
    return [];
  }
}

export default async function Home({ params }: { params: Promise<{ lang: string }> }) {
  const { lang } = await params;
  const dict = await getDictionary(lang);
  
  const [dbPhotos, dbServices, heroMediaList, dbSettings, instagramPosts] = await Promise.all([
    prisma.gallery.findMany({ orderBy: { createdAt: 'desc' } }),
    prisma.service.findMany({ orderBy: { createdAt: 'asc' } }),
    prisma.heroMedia.findMany(),
    prisma.siteSettings.findFirst(),
    getInstagramData()
  ]);

  const dbHeroMedia = heroMediaList.length > 0 ? heroMediaList[0] : null;

  return (
    <main className="min-h-screen bg-brand-white">
      <Header dict={dict} lang={lang} dbSettings={dbSettings} />
      <Hero dict={dict} dbHeroMedia={dbHeroMedia} />
      <About dict={dict} />
      <Services dict={dict} dbServices={dbServices} />
      <Gallery dict={dict} dbPhotos={dbPhotos} />
      <InstagramFeed dict={dict} posts={instagramPosts} />
      <Contact dict={dict} dbSettings={dbSettings} />
      <Footer dict={dict} dbSettings={dbSettings} />
    </main>
  );
}
