import * as React from 'react';
import { Metadata } from 'next';

// ─── Core homepage components (never change) ─────────────────────────────────
import { HeroSection } from '@/components/home/HeroSection';
import { TargetAudience } from '@/components/home/TargetAudience';
import { Features } from '@/components/home/Features';
import { CommonTroubles } from '@/components/home/CommonTroubles';
import { KeyTerms } from '@/components/home/KeyTerms';
import { NewsletterSection } from '@/components/home/NewsletterSection';
import { LatestArticles } from '@/components/home/LatestArticles';
import { CategorySection } from '@/components/home/CategorySection';
import { TrendWidget } from '@/components/home/TrendWidget';
import { MostReadWidget } from '@/components/home/MostReadWidget';

// ─── Extra components (rendered only when user adds them via editor) ──────────
import { FeaturedArticleHero } from '@/components/sections/FeaturedArticleHero';
import { FeaturedArticleSpotlight } from '@/components/sections/FeaturedArticleSpotlight';
import { AuthorProfile } from '@/components/sections/AuthorProfile';
import { BannerCTA } from '@/components/sections/BannerCTA';
import { IntroSection } from '@/components/sections/IntroSection';
import { SectionHeading } from '@/components/sections/SectionHeading';
import { RankedTopList } from '@/components/sections/RankedTopList';
import { ReviewSection } from '@/components/sections/ReviewSection';
import { DetailedServiceCard } from '@/components/sections/DetailedServiceCard';
import { LibHeroSection } from '@/components/sections/LibHeroSection';
import { BlogGrid } from '@/components/sections/BlogGrid';
import { TwoColumnLayout } from '@/components/sections/TwoColumnLayout';
import { HeroBlogCarousel } from '@/components/sections/HeroBlogCarousel';
import { BlogShowcaseGrid } from '@/components/sections/BlogShowcaseGrid';
import { ArticleGridCategorySections } from '@/components/sections/ArticleGridCategorySections';

import {
  getLatestArticles,
  getTrendingArticles,
  getMostReadArticles,
  getAllCategories,
  getCategoryArticles,
} from '@/lib/utils/db';
import { getHomepageContent } from '@/lib/homepage-content';

// Revalidate every 60 seconds so editor changes appear quickly
export const revalidate = 60;

export const metadata: Metadata = {
  title: 'zen-cart.jp | オンラインカジノ情報メディア',
  description:
    'zen-cart.jp は、オンラインカジノに関する最新情報・攻略ガイド・ボーナス情報・業界ニュースを発信する情報メディアです。',
  keywords: ['オンラインカジノ', 'カジノボーナス', 'フリースピン', 'カジノガイド', 'カジノニュース', 'オンラインカジノ おすすめ'],
  alternates: { canonical: 'https://zen-cart.jp' },
  openGraph: {
    title: 'zen-cart.jp | オンラインカジノ情報メディア',
    description: 'zen-cart.jp は、オンラインカジノに関する最新情報・攻略ガイド・ボーナス情報・業界ニュースを発信する情報メディアです。',
    url: 'https://zen-cart.jp', siteName: 'zen-cart.jp', locale: 'ja_JP', type: 'website',
    images: [{ url: '/og-image.jpg', width: 1200, height: 630, alt: 'zen-cart.jp' }],
  },
  twitter: {
    card: 'summary_large_image',
    title: 'zen-cart.jp | オンラインカジノ情報メディア',
    description: 'zen-cart.jp は、オンラインカジノに関する最新情報・攻略ガイド・ボーナス情報・業界ニュースを発信する情報メディアです。',
    creator: '@zencartjp', images: ['/og-image.jpg'],
  },
};

// ─── CORE site-component keys (handled by the fixed layout below) ─────────────
// These are NEVER rendered from the DB to avoid double-rendering core sections.
const CORE_TYPES = new Set([
  'SiteHeroSection', 'SiteTargetAudience', 'SiteFeatures',
  'SiteLatestArticles', 'SiteAllCategorySections', 'SiteTwoColumnLayout',
  'SiteCommonTroubles', 'SiteKeyTerms', 'SiteNewsletterSection',
  'TwoColumnLayout', // the library version of the sidebar — also handled by core layout
]);

// ─── Render an extra (non-core) editor component safely ───────────────────────
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function renderExtraComponent(type: string, props: Record<string, any>) {
  // Strip Puck internal keys
  const PUCK_KEYS = new Set(['puck', 'editMode', 'id', 'renderDropZone', 'metadata', 'dragRef', 'isEditing']);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const p: Record<string, any> = {};
  for (const k of Object.keys(props ?? {})) {
    if (!PUCK_KEYS.has(k)) p[k] = props[k];
  }

  try {
    switch (type) {
      case 'FeaturedArticleHero':
        return <FeaturedArticleHero {...p} />;
      case 'FeaturedArticleSpotlight':
        return <FeaturedArticleSpotlight {...p} />;
      case 'AuthorProfile':
        return <AuthorProfile {...p} />;
      case 'BannerCTA':
        if (!p.headline || !p.ctaText || !p.ctaUrl) return null;
        return <BannerCTA headline={p.headline} description={p.description ?? ''} ctaText={p.ctaText} ctaUrl={p.ctaUrl} theme={p.theme} bgImage={p.bgImage} />;
      case 'IntroSection':
        return <IntroSection {...p} />;
      case 'SectionHeading':
        return <SectionHeading title={p.title ?? ''} {...p} />;
      case 'RankedTopList':
        return <RankedTopList sectionTitle={p.sectionTitle ?? ''} items={p.items ?? []} {...p} />;
      case 'ReviewSection':
        return <ReviewSection sectionTitle={p.sectionTitle ?? ''} items={p.items ?? []} {...p} />;
      case 'DetailedServiceCard':
        return <DetailedServiceCard {...p} />;
      case 'LibHeroSection':
        return <LibHeroSection {...p} />;
      case 'BlogGrid':
        return <BlogGrid {...p} />;
      case 'HeroBlogCarousel':
        return <HeroBlogCarousel {...p} />;
      case 'BlogShowcaseGrid':
        return <BlogShowcaseGrid {...p} />;
      case 'ArticleCategorySections':
      case 'ArticleGridCategorySections':
        return <ArticleGridCategorySections {...p} />;
      default:
        return null;
    }
  } catch (err) {
    console.error(`[HomePage] Error rendering extra component "${type}":`, err);
    return null;
  }
}

export default async function HomePage() {
  // Fetch core data and editor content in parallel
  const [latestArticles, trendingArticles, mostReadArticles, categories, { puckData }] =
    await Promise.all([
      getLatestArticles(1),
      getTrendingArticles(5),
      getMostReadArticles(5),
      getAllCategories(),
      getHomepageContent(),
    ]);

  const categoryArticles = await Promise.all(
    categories.map(async (cat) => ({
      category: cat,
      articles: await getCategoryArticles(cat.name, 4, 0),
    })),
  );

  // Determine final layout order based on editor config (fall back to default order)
  const sections = puckData?.content && Array.isArray(puckData.content) && puckData.content.length > 0
    ? puckData.content
    : [
        { type: "SiteHeroSection",        props: {} },
        { type: "SiteTargetAudience",     props: {} },
        { type: "SiteFeatures",           props: {} },
        { type: "SiteTwoColumnLayout",    props: {} },
        { type: "SiteCommonTroubles",     props: {} },
        { type: "SiteKeyTerms",           props: {} },
        { type: "SiteNewsletterSection",  props: {} },
      ];

  // Resolve all JSX elements in order
  const elements = await Promise.all(
    sections.map(async (s: { type: string; props: Record<string, any> }, i: number) => {
      const type = s.type;
      const p = s.props ?? {};

      switch (type) {
        case 'SiteHeroSection':
          return <HeroSection key={`core-${type}-${i}`} />;
        case 'SiteTargetAudience':
          return <TargetAudience key={`core-${type}-${i}`} />;
        case 'SiteFeatures':
          return <Features key={`core-${type}-${i}`} />;
        case 'SiteCommonTroubles':
          return <CommonTroubles key={`core-${type}-${i}`} />;
        case 'SiteKeyTerms':
          return <KeyTerms key={`core-${type}-${i}`} />;
        case 'SiteNewsletterSection':
          return <NewsletterSection key={`core-${type}-${i}`} />;
        case 'SiteTwoColumnLayout':
        case 'TwoColumnLayout':
          return (
            <div key={`core-${type}-${i}`} className="container py-12">
              <div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-8">
                <div className="space-y-12">
                  {latestArticles.length > 0 && <LatestArticles articles={latestArticles} />}
                  {categoryArticles.map(
                    ({ category, articles }) =>
                      articles.length > 0 && (
                        <CategorySection
                          key={category.slug}
                          categoryName={category.name}
                          categorySlug={category.slug}
                          articles={articles}
                        />
                      ),
                  )}
                </div>
                <aside className="lg:sticky lg:top-24 space-y-6 self-start">
                  {trendingArticles.length > 0 && <TrendWidget articles={trendingArticles} />}
                  {mostReadArticles.length > 0 && <MostReadWidget articles={mostReadArticles} />}
                </aside>
              </div>
            </div>
          );
        default:
          const el = await renderExtraComponent(type, p);
          return el ? <React.Fragment key={`extra-${type}-${i}`}>{el}</React.Fragment> : null;
      }
    })
  );

  return (
    <main>
      {elements}
    </main>
  );
}
