import Link from 'next/link';
import { notFound } from 'next/navigation';
import { isLocale, localePath } from '@ai-radar/shared';
import { getHome, getTelegramBot } from '@/lib/api';
import { getDictionary } from '@/lib/dictionary';
import { DailyOverview } from '@/components/digest/DailyOverview';
import { HeroCard, StandardCard, CompactCard } from '@/components/cards/StoryCards';
import { Section, RowList, EmptyState } from '@/components/sections/Section';
import { Rail } from '@/components/rail/Rail';
import { AdSlot } from '@/components/ads/AdSlot';
import { SubscribeForm } from '@/components/subscribe/SubscribeForm';

/**
 * The homepage.
 *
 * Five tiers of decreasing visual weight, per docs/DESIGN.md section 4.
 * The reader scrolls from most to least important without having to work
 * out where to look:
 *
 *   1 daily overview   full width, serif, no card
 *   2 hero story       surface + accent rule
 *   3 important        two up, surface
 *   4 tools            compact, border only
 *   5 updates/pricing  editorial rows, no card
 */
export default async function HomePage({ params }: { params: Promise<{ lang: string }> }) {
  // Next.js 16 removed synchronous params access.
  const { lang } = await params;
  if (!isLocale(lang)) notFound();

  const dict = getDictionary(lang);
  const [home, telegramBot] = await Promise.all([getHome(lang), getTelegramBot()]);
  const date = new Date(home.date);

  // Nothing published yet — say so plainly rather than showing a shell.
  if (home.totalPublished === 0 && home.top.length === 0) {
    return (
      <main id="main" className="page">
        <DailyOverview date={date} stories={[]} counts={{}} locale={lang} dict={dict} />
        <div className="section">
          <EmptyState title={dict.home.emptyTitle} body={dict.home.emptyBody} />
          <Link href={localePath('/status', lang)} className="section-link">
            {lang === 'ar' ? 'حالة النظام' : 'See pipeline status'}{' '}
            <span className="arrow">→</span>
          </Link>
        </div>
      </main>
    );
  }

  return (
    <main id="main" className="page">
      {/* Tier 1 — full width, above the rail, so it reads as the page's
          answer to "what happened today?" */}
      <DailyOverview
        date={date}
        stories={home.top}
        counts={home.counts}
        locale={lang}
        dict={dict}
      />

      <div className="split" style={{ marginTop: 'var(--section-gap)' }}>
        <div>
          {/* Tier 2 + 3 */}
          {home.hero && (
            <Section title={dict.home.importantToday}>
              <div className="stack">
                <HeroCard post={home.hero} locale={lang} dict={dict} />
                {home.important.length > 0 && (
                  <div className="grid-2">
                    {home.important.slice(0, 2).map((post) => (
                      <StandardCard key={post.id} post={post} locale={lang} dict={dict} />
                    ))}
                  </div>
                )}
              </div>
            </Section>
          )}

          {/* First ad sits after the hero and important stories — the
              reader has already had the value. */}
          <AdSlot slotKey="home_top_feed" label={dict.meta.advertisement} />

          {/* Signup sits after the hero and important stories, for the
              same reason the first ad does: the reader has already had
              what they came for, so the offer reads as useful rather
              than as a toll gate. Once on the page, never a popup. */}
          <div style={{ marginTop: 'var(--section-gap)' }}>
            <SubscribeForm locale={lang} dict={dict} telegramBot={telegramBot.username} />
          </div>

          {/* Tier 4 */}
          {home.tools.length > 0 && (
            <Section
              title={dict.home.newTools}
              viewAll={{ href: localePath('/tools', lang), label: dict.home.viewAll }}
            >
              <div className="grid-4">
                {home.tools.map((post) => (
                  <CompactCard key={post.id} post={post} locale={lang} dict={dict} />
                ))}
              </div>
            </Section>
          )}

          {/* Tier 5 — rows, not cards */}
          {home.updates.length > 0 && (
            <Section
              title={dict.home.productUpdates}
              viewAll={{ href: localePath('/updates', lang), label: dict.home.viewAll }}
            >
              <RowList posts={home.updates} locale={lang} />
            </Section>
          )}

          <AdSlot slotKey="home_between_sections" label={dict.meta.advertisement} />

          {home.models.length > 0 && (
            <Section
              title={dict.home.newModels}
              viewAll={{ href: localePath('/models', lang), label: dict.home.viewAll }}
            >
              <RowList posts={home.models} locale={lang} />
            </Section>
          )}

          {home.pricing.length > 0 && (
            <Section
              title={dict.home.pricingChanges}
              viewAll={{ href: localePath('/pricing', lang), label: dict.home.viewAll }}
            >
              <RowList posts={home.pricing} locale={lang} />
            </Section>
          )}
        </div>

        <Rail
          trending={home.trending}
          worthTrying={home.worthTrying}
          locale={lang}
          dict={dict}
        />
      </div>
    </main>
  );
}
