import { getPublishedArticles, getTagList } from '@/lib/queries';
import ArticleCard from '@/components/ArticleCard';
import { InFeedAd, SidebarAd } from '@/components/ads/placements';
import { SECTIONS } from '@/data/feeds';
import type { ReactNode } from 'react';
import { notFound } from 'next/navigation';

export const dynamic = 'force-dynamic';

type Params = { section: string; page?: string };

export default async function SectionPage({
  params,
  searchParams,
}: {
  params: Params;
  searchParams: { page?: string };
}) {
  const section = params.section;
  const known = SECTIONS.find((s) => s.slug === section);
  if (!known) notFound();

  const page = Math.max(1, parseInt(searchParams.page ?? '1', 10) || 1);
  const PER = 24;
  const [articles, tags] = await Promise.all([
    getPublishedArticles(section, PER, (page - 1) * PER),
    getTagList(10),
  ]);

  return (
    <>
      <div className="mx-auto max-w-6xl px-4 py-6 sm:px-6">
        <h1 className="mb-6 font-display text-3xl font-bold text-ink-900">
          {known.label}
        </h1>
        <div className="grid gap-8 lg:grid-cols-3">
          <div className="lg:col-span-2">
            {articles.length === 0 ? (
              <p className="rounded-xl border border-dashed border-ink-300 bg-white p-10 text-center text-sm text-ink-500">
                Nothing in {known.label} yet — the worker will fill this in.
              </p>
            ) : (
              <div className="grid gap-5 sm:grid-cols-2">
                {interleave(articles, 3)}
              </div>
            )}
          </div>
          <aside aria-label="Sidebar" className="space-y-8">
            <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) => (
                    <a
                      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}
                    </a>
                  ))}
                </div>
              </section>
            )}
          </aside>
        </div>
      </div>
    </>
  );
}

function interleave(
  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;
}
