import { getPublishedArticles, getTagList } from '@/lib/queries';
import ArticleCard from '@/components/ArticleCard';
import { InFeedAd, SidebarAd } from '@/components/ads/placements';
import Link from 'next/link';
import { env } from '@/lib/env';

export const dynamic = 'force-dynamic';

export default async function HomePage({
  searchParams,
}: {
  searchParams: { page?: string };
}) {
  const page = Math.max(1, parseInt(searchParams.page ?? '1', 10) || 1);
  const PER = 21;
  const [articles, tags] = await Promise.all([
    getPublishedArticles('top-stories', PER, (page - 1) * PER),
    getTagList(12),
  ]);

  const hero = articles[0];
  const rest = articles.slice(1);

  return (
    <>
      <div className="mx-auto max-w-6xl px-4 py-6 sm:px-6">
        <div className="grid gap-8 lg:grid-cols-3">
          {/* Main column */}
          <div className="lg:col-span-2">
            {hero ? (
              <Link
                href={`/article/${hero.slug}`}
                className="group mb-8 block overflow-hidden rounded-2xl border border-ink-200 bg-white shadow-sm"
              >
                <div className="relative aspect-[16/8] overflow-hidden bg-ink-100">
                  {hero.image ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={hero.image}
                      alt=""
                      className="h-full w-full object-cover transition duration-500 group-hover:scale-[1.02]"
                    />
                  ) : (
                    <div className="flex h-full items-center justify-center bg-masthead-gradient">
                      <span className="font-display text-2xl font-bold text-white/90">
                        {env.siteName}
                      </span>
                    </div>
                  )}
                  <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-ink-950/95 via-ink-950/70 to-transparent p-5 pt-16">
                    <span className="mb-2 inline-block rounded bg-maple-600 px-2 py-0.5 text-[11px] font-bold uppercase tracking-wider text-white">
                      Lead briefing
                    </span>
                    <h1 className="font-display text-2xl font-bold leading-tight text-white sm:text-3xl">
                      {hero.headline ?? hero.title}
                    </h1>
                    <p className="mt-2 line-clamp-2 text-sm text-ink-200">{hero.excerpt}</p>
                  </div>
                </div>
              </Link>
            ) : (
              <EmptyState />
            )}

            {rest.length > 0 && (
              <div className="grid gap-5 sm:grid-cols-2">
                {interleaveInFeedAds(rest, 3).map((node) => node)}
              </div>
            )}
          </div>

          {/* Sidebar */}
          <aside className="space-y-8" aria-label="Sidebar">
            <SidebarAd tall />
            {tags.length > 0 && (
              <section className="rounded-xl border border-ink-200 bg-white p-5">
                <h2 className="text-xs font-semibold uppercase tracking-wider text-ink-500">
                  Trending topics
                </h2>
                <div className="mt-3 flex flex-wrap gap-2">
                  {tags.map((t) => (
                    <Link
                      key={t}
                      href={`/tag/${t}`}
                      className="rounded-full bg-ink-100 px-3 py-1 text-sm text-ink-700 hover:bg-maple-100 hover:text-maple-800"
                    >
                      #{t}
                    </Link>
                  ))}
                </div>
              </section>
            )}
          </aside>
        </div>
      </div>
    </>
  );
}

import type { ReactNode } from 'react';

/** Interleave an InFeedAd after every `every`th card. */
function interleaveInFeedAds(
  cards: Awaited<ReturnType<typeof getPublishedArticles>>,
  every: number,
): ReactNode[] {
  const out: ReactNode[] = [];
  cards.forEach((card, i) => {
    out.push(<ArticleCard key={card.id} card={card} />);
    if ((i + 1) % every === 0) out.push(<InFeedAd key={`ad-${i + 1}`} index={i + 1} />);
  });
  return out;
}

function EmptyState() {
  return (
    <div className="rounded-2xl border border-dashed border-ink-300 bg-white p-12 text-center">
      <p className="font-display text-xl font-bold text-ink-800">
        No briefings yet
      </p>
      <p className="mx-auto mt-2 max-w-md text-sm text-ink-500">
        The ingestion worker has not published anything yet. Trigger your first
        run (see the README “First run” section) and this page will fill with
        synthesized briefings.
      </p>
    </div>
  );
}
