import { notFound } from 'next/navigation';
import type { SectionRecord } from '$entities/Section';
import { getCollection } from '$shared/api';
import { SectionAccordion } from '$widgets/SectionAccordion';
import { SectionFactory } from '$widgets/SectionFactory';

/**
 * Optional catchall: `/` → first section, `/:slug` → that section.
 */
export async function generateStaticParams() {
  try {
    const { items: sections } = await getCollection<SectionRecord>('sections', {
      sort: 'order',
    });
    return [{}, ...sections.map((s) => ({ slug: [s.slug] }))];
  } catch (err) {
    console.warn('[generateStaticParams] PocketBase unreachable at build — deferring to runtime ISR', err);
    return [];
  }
}

export interface Props {
  params: Promise<{ slug?: string[] }>;
}

/**
 * Portfolio page — one route per section, sections list always visible.
 */
export default async function SectionPage({ params }: Props) {
  const { slug } = await params;

  const { items: sections } = await getCollection<SectionRecord>('sections', {
    sort: 'order',
    tags: ['sections'],
  });

  if (sections.length === 0) {
    notFound();
  }

  const activeSlug = slug?.[0] ?? sections[0].slug;

  if (!sections.some((s) => s.slug === activeSlug)) {
    notFound();
  }

  return (
    <main className="px-4 py-6 sm:px-8 sm:py-12 lg:py-16 lg:px-16">
      <SectionAccordion sections={sections} activeSlug={activeSlug}>
        {sections.map((s) => (
          <SectionFactory key={s.slug} slug={s.slug} />
        ))}
      </SectionAccordion>
    </main>
  );
}
