import type { Metadata } from "next";
import { PageHero } from "@/components/PageHero";
import { PlainText, Unavailable } from "@/components/RichText";
import { ApiDown, api } from "@/lib/api";
import type { ProjectDetail } from "@/lib/types";

type Props = { params: Promise<{ slug: string }> };

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  try {
    const { slug } = await params;
    const project = await api<ProjectDetail>(`/projects/${slug}`);
    return { title: { absolute: project.seo.title }, description: project.seo.description ?? undefined };
  } catch {
    return { title: "تجربه تخصصی" };
  }
}

export default async function ProjectPage({ params }: Props) {
  try {
    const { slug } = await params;
    const project = await api<ProjectDetail>(`/projects/${slug}`);
    return (
      <>
        <PageHero title={project.title} lead={project.category_label} />
        <article className="shell section-pad max-w-3xl space-y-10">
          {project.client_name ? (
            <p className="border-b border-line pb-6 text-sm text-muted">کارفرما: {project.client_name}</p>
          ) : null}
          <section className="border-t border-line pt-8">
            <h2 className="display text-xl text-navy">مسئله</h2>
            <div className="mt-3"><PlainText text={project.problem} /></div>
          </section>
          <section className="border-t border-line pt-8">
            <h2 className="display text-xl text-navy">راهکار</h2>
            <div className="mt-3"><PlainText text={project.solution} /></div>
          </section>
          <section className="border-t border-line pt-8">
            <h2 className="display text-xl text-navy">نقش گروه</h2>
            <div className="mt-3"><PlainText text={project.role} /></div>
          </section>
          {project.technologies.length > 0 && (
            <p className="border-t border-line pt-6 text-sm text-muted">فناوری‌ها: {project.technologies.join("، ")}</p>
          )}
          {project.results ? (
            <section className="border-t border-line pt-8">
              <h2 className="display text-xl text-navy">نتایج</h2>
              <div className="mt-3"><PlainText text={project.results} /></div>
            </section>
          ) : null}
          {project.images.length > 0 && (
            <div className="grid gap-4 border-t border-line pt-8">
              {project.images.map((image) => (
                <img key={image} src={image} alt="" className="w-full border border-line object-cover" />
              ))}
            </div>
          )}
        </article>
      </>
    );
  } catch (error) {
    if (error instanceof ApiDown) return <Unavailable />;
    throw error;
  }
}
