import Link from "next/link";
import { notFound } from "next/navigation";
import { isLocale, type Locale, publicPath } from "@/i18n/routes";
import { getDict } from "@/i18n/dictionaries";
import { getDb } from "@/lib/db";
import { getProject } from "@/lib/models";
import { buildMetadata } from "@/lib/metadata";
import { StackIcon } from "@/components/stack-icon";

const THUMBED = ["hermes", "casino-bot", "polymarket-trader"];

export async function generateMetadata({
  params,
}: {
  params: Promise<{ lang: string; slug: string }>;
}) {
  const { lang, slug } = await params;
  const locale: Locale = isLocale(lang) ? lang : "de";
  const project = getProject(getDb(), locale, slug);
  const slugPath = publicPath(locale, "projectItem", slug);
  const ogImage = `${publicPath(locale, "projectItem", slug)}/opengraph-image`;
  if (!project) return buildMetadata(locale, slug, "Projekt auf eldov.win", { path: slugPath });
  return buildMetadata(locale, `${project.slug} · ${project.category}`, project.summary, {
    path: slugPath,
    image: ogImage,
  });
}

export default async function ProjectDetailPage({
  params,
}: {
  params: Promise<{ lang: string; slug: string }>;
}) {
  const { lang, slug } = await params;
  const locale: Locale = isLocale(lang) ? lang : "de";
  const project = getProject(getDb(), locale, slug);
  if (!project) notFound();
  const dict = getDict(locale);

  const paragraphs = project.body.split(/\n\n+/).filter((p) => p.trim().length > 0);
  const hasThumb = THUMBED.includes(project.slug);
  const stackItems = project.stack.split("·").map((s) => s.trim()).filter(Boolean);

  return (
    <article className="mx-auto max-w-[var(--max-w-narrow)] px-4 py-10 md:px-6">
      <Link
        href={publicPath(locale, "projects")}
        className="mb-6 inline-flex items-center gap-1 font-mono text-xs uppercase text-muted hover:text-accent"
        data-cursor="hover"
      >
        ← {dict.actions.backToProjects}
      </Link>

      {hasThumb ? (
        <div className="relative mb-8 aspect-[2/1] overflow-hidden border border-hairline">
          <img
            src={`/img/projects/${project.slug}.jpg`}
            alt=""
            className="h-full w-full object-cover opacity-65"
            style={{ filter: "saturate(0.85) contrast(1.05)" }}
          />
          <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-[var(--bg)] via-transparent to-transparent" />
        </div>
      ) : null}

      <header className="ascii-box mb-8">
        <div className="mb-3 flex flex-wrap items-center gap-2">
          <span className="font-mono text-xs text-muted">{project.number}</span>
          <span className={`badge ${project.featured ? "badge--live" : "badge--muted"}`}>{project.status}</span>
          <span className="font-mono text-xs text-muted">{project.category}</span>
          {project.featured ? <span className="badge badge--accent">★ featured</span> : null}
        </div>
        <h1 className="mb-3 text-4xl font-semibold tracking-tight">{project.slug}</h1>
        <p className="text-lg text-[var(--fg-dim)]">{project.summary}</p>
      </header>

      <section className="mb-8">
        <div className="section-heading">
          <span className="section-heading__label">~/stack</span>
          <h2 className="section-heading__title">Stack</h2>
        </div>
        <div className="flex flex-wrap gap-2">
          {stackItems.map((s) => (
            <span key={s} className="stack-pill">
              <StackIcon name={s} />
              {s}
            </span>
          ))}
        </div>
      </section>

      {project.stance ? (
        <blockquote className="ascii-box mb-8 border-l-2 border-l-accent">
          <span className="font-mono text-[10px] uppercase tracking-wider text-accent">{dict.projectDetail.stanceLabel}:</span>
          <p className="mt-2 text-[var(--fg-dim)] italic">{project.stance}</p>
        </blockquote>
      ) : null}

      <section className="mb-8">
        <div className="section-heading">
          <span className="section-heading__label">~/notes</span>
          <h2 className="section-heading__title">{locale === "de" ? "Notizen" : "Notes"}</h2>
        </div>
        <div className="space-y-4 text-[var(--fg)]">
          {paragraphs.map((p, i) => (
            <p key={i} className="leading-relaxed">{p}</p>
          ))}
        </div>
      </section>

      {project.href ? (
        <a
          href={project.href}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-2 border border-accent px-5 py-2.5 font-mono text-sm uppercase tracking-wider text-accent hover:bg-accent hover:text-[var(--bg-deep)]"
          data-cursor="hover"
        >
          {dict.projectDetail.liveLabel} ↗
        </a>
      ) : null}
    </article>
  );
}
