import { notFound } from 'next/navigation';
import Link from 'next/link';
import { AdminShell } from '@/components/admin/AdminShell';
import { PostEditor } from '@/components/admin/PostEditor';
import type { JsonValue } from '@/components/admin/JsonForm';
import { loadContent } from '@/lib/content/load';
import { loadPost, loadPostOverrides, isKnownSlug } from '@/lib/content/posts-store';

// Always render on demand so the editor mirrors current DB state.
export const dynamic = 'force-dynamic';

export default function AdminPostEditorPage({ params }: { params: { slug: string } }) {
  const { slug } = params;
  if (!isKnownSlug(slug)) notFound();

  const post = loadPost(slug);
  if (!post) notFound();

  const overridden = slug in loadPostOverrides();
  const { en } = loadContent();
  const title = en.blog.items.find((p) => p.slug === slug)?.title ?? slug;

  return (
    <AdminShell>
      <div className="mx-auto max-w-3xl">
        <Link
          href="/admin/posts"
          className="font-mono text-[0.7rem] uppercase tracking-wider text-slate-500 transition-colors hover:text-electric"
        >
          ← Journal articles
        </Link>
        <h1 className="mb-1 mt-3 text-2xl font-bold text-white">{title}</h1>
        <p className="mb-6 text-sm text-slate-400">
          Edit the lead and body blocks for both languages, then save. Changes go live immediately.
        </p>

        <PostEditor
          slug={slug}
          title={title}
          initial={{
            date: post.date as JsonValue,
            accent: post.accent as JsonValue,
            fa: post.fa as unknown as JsonValue,
            en: post.en as unknown as JsonValue,
          }}
          isOverridden={overridden}
        />
      </div>
    </AdminShell>
  );
}
