import * as React from 'react';
import { HeroSection } from '@/components/home/HeroSection';
import { LatestArticles } from '@/components/home/LatestArticles';
import { CategorySection } from '@/components/home/CategorySection';
import { NewsletterSection } from '@/components/home/NewsletterSection';
import { PuckLibraryRenderer } from '@/components/home/PuckLibraryRenderer';
import { FeaturedArticleHero } from '@/components/sections/FeaturedArticleHero';
import { ArticleGridCategorySections } from '@/components/sections/ArticleGridCategorySections';
import { FeaturedArticleSpotlight } from '@/components/sections/FeaturedArticleSpotlight';
import { BlogShowcaseGrid } from '@/components/sections/BlogShowcaseGrid';
import { BlogGrid } from '@/components/sections/BlogGrid';
import { ArticleGridTrendingRanking } from '@/components/sections/ArticleGridTrendingRanking';
import { AuthorBox } from '@/components/sections/AuthorBox';
import { AuthorProfile } from '@/components/sections/AuthorProfile';
import { HeroBlogCarousel } from '@/components/sections/HeroBlogCarousel';
import { TwoColumnLayout } from '@/components/sections/TwoColumnLayout';
import { BlogPost } from '@/components/sections/BlogPost';
import { TabsClientWrapper } from '@/components/editor/TabsClientWrapper';
import { getCategoryArticles, getLatestArticles } from '@/lib/utils/db';

const categories = [
  { name: '攻略情報', slug: '攻略情報' },
  { name: 'キャラクター評価', slug: 'キャラクター評価' },
  { name: 'リセマラ・ガチャ情報', slug: 'リセマラ・ガチャ情報' },
  { name: 'イベント・アップデート', slug: 'イベント・アップデート' },
  { name: '初心者・育成ガイド', slug: '初心者・育成ガイド' },
];

export async function PageRenderer({ dataToRender, fullPuckData }: { dataToRender: any[], fullPuckData?: any }) {
  if (!dataToRender || !Array.isArray(dataToRender)) return null;

  const sections = await Promise.all(
    dataToRender.map(async (item: any) => {
      const { type, props } = item;
      let content: React.ReactNode = null;
      let isHandledDirectly = true;

      switch (type) {
        case 'SiteHeroSection': {
          const count = props.count || 5;
          const recentArticles = await getLatestArticles(count);
          content = <HeroSection key={props.id} recentArticles={recentArticles} {...props} />;
          break;
        }
        case 'SiteLatestArticles': {
          const count = props.count || 12;
          const latestArticles = await getLatestArticles(count);
          if (latestArticles.length === 0) return null;
          content = <LatestArticles key={props.id} articles={latestArticles} {...props} />;
          break;
        }
        case 'SiteAllCategorySections': {
          const articlesPerCategory = props.articlesPerCategory || 4;
          const categoryArticles = await Promise.all(
            categories.map(async (category) => {
              const articles = await getCategoryArticles(category.name, articlesPerCategory, 0);
              return { category, articles };
            })
          );
          content = (
            <React.Fragment key={props.id}>
              {categoryArticles.map(({ category, articles }, index) =>
                articles.length > 0 ? (
                  <CategorySection
                    key={category.slug}
                    categoryName={category.name}
                    articles={articles}
                    index={index}
                    {...props}
                  />
                ) : null
              )}
            </React.Fragment>
          );
          break;
        }
        case 'SiteNewsletterSection': {
          content = <NewsletterSection key={props.id} {...props} />;
          break;
        }
        case 'FeaturedArticleHero': {
          content = <FeaturedArticleHero key={props.id} {...props} />;
          break;
        }
        case 'ArticleCategorySections': {
          content = <ArticleGridCategorySections key={props.id} {...props} />;
          break;
        }
        case 'FeaturedArticleSpotlight': {
          content = <FeaturedArticleSpotlight key={props.id} {...props} />;
          break;
        }
        case 'BlogShowcaseGrid': {
          content = <BlogShowcaseGrid key={props.id} {...props} />;
          break;
        }
        case 'BlogGrid': {
          content = <BlogGrid key={props.id} {...props} />;
          break;
        }
        case 'ArticleTrendingRanking': {
          content = <ArticleGridTrendingRanking key={props.id} {...props} />;
          break;
        }
        case 'AuthorBox': {
          content = <AuthorBox key={props.id} {...props} />;
          break;
        }
        case 'AuthorProfile': {
          content = <AuthorProfile key={props.id} {...props} />;
          break;
        }
        case 'HeroBlogCarousel': {
          content = <HeroBlogCarousel key={props.id} {...props} />;
          break;
        }
        case 'TwoColumnLayout': {
          content = <TwoColumnLayout key={props.id} {...props} />;
          break;
        }
        case 'BlogPost': {
          content = <BlogPost key={props.id} {...props} />;
          break;
        }
        case 'SiteTabsContainer': {
          const tabs = props.tabs || [];
          if (tabs.length === 0) return null;
          content = (
            <section key={props.id} className="py-12 bg-transparent">
              <div className="w-full max-w-[1280px] mx-auto px-4 sm:px-6">
                {props.title && (
                  <h2 className="text-2xl md:text-3xl font-bold text-brand-primary mb-8 text-center">
                    {props.title}
                  </h2>
                )}
                <TabsClientWrapper tabs={tabs}>
                  {tabs.map((tab: any, i: number) => {
                    const zoneKey = `${props.id}:tab-${i}`;
                    const zoneItems = fullPuckData?.zones?.[zoneKey] || [];
                    return (
                      <div key={tab.id || `zone-${i}`} className="w-full">
                        <PageRenderer dataToRender={zoneItems} fullPuckData={fullPuckData} />
                      </div>
                    );
                  })}
                </TabsClientWrapper>
              </div>
            </section>
          );
          break;
        }
        case 'SiteHeader':
        case 'SiteFooter':
          return null; // Do not render inside the main canvas content
        default:
          isHandledDirectly = false;
          content = <PuckLibraryRenderer key={props.id} type={type} props={props} />;
          break;
      }

      const anchorId = props.anchorId ? props.anchorId.replace(/^#/, '') : null;

      if (isHandledDirectly && anchorId) {
        return (
          <div id={anchorId} key={`anchor-wrap-${props.id}`} className="scroll-mt-24 group/anchor relative">
            {content}
          </div>
        );
      }

      return content;
    })
  );

  return <>{sections}</>;
}
