import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { SiteShell, SiteLink } from "@/components/site/site-shell";
import { resolveRequestTenant } from "@/core/tenant/request-tenant";
import { getArchitectProfile } from "@/services/profile-service";
import { getPublishedJournalBySlug } from "@/services/journal-service";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const resolved = await resolveRequestTenant();
  if (!resolved.ok) return { title: "Not found", robots: { index: false } };

  const post = await getPublishedJournalBySlug(resolved.context, slug);
  if (!post) return { title: "Not found", robots: { index: false } };

  return {
    title: post.seoTitle || post.title,
    description: post.seoDescription || post.excerpt || undefined,
  };
}

export default async function TenantJournalPostPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const resolved = await resolveRequestTenant();
  if (!resolved.ok) notFound();

  const [{ profile }, post] = await Promise.all([
    getArchitectProfile(resolved.context),
    getPublishedJournalBySlug(resolved.context, slug),
  ]);
  if (!post) notFound();

  return (
    <SiteShell
      studioName={resolved.context.studioName}
      location={profile?.location}
      active="journal"
    >
      <main className="studio-container max-w-3xl pb-20 pt-[calc(5rem+env(safe-area-inset-top))] sm:pb-24">
        <SiteLink
          href="/journal"
          className="text-sm text-[var(--archi-ink-muted)] transition hover:text-[var(--archi-ink)]"
        >
          ← Journal
        </SiteLink>
        <div className="studio-line-accent mt-10 mb-6 h-px w-16" />
        <h1 className="font-[family-name:var(--font-display)] text-4xl tracking-tight sm:text-5xl lg:text-6xl">
          {post.title}
        </h1>
        {post.publishedAt ? (
          <p className="mt-5 text-sm tracking-[0.14em] text-[var(--archi-ink-muted)] uppercase">
            {post.publishedAt.toLocaleDateString(undefined, {
              year: "numeric",
              month: "long",
              day: "numeric",
            })}
          </p>
        ) : null}
        {post.excerpt ? (
          <p className="mt-8 text-xl leading-9 text-[var(--archi-ink-muted)]">
            {post.excerpt}
          </p>
        ) : null}
        {post.content ? (
          <div className="mt-12 whitespace-pre-wrap text-lg leading-9 text-[var(--archi-ink)]/90">
            {post.content}
          </div>
        ) : null}
      </main>
    </SiteShell>
  );
}
