import { redirect, notFound } from "next/navigation";
import { loadCurrentDid } from "@/data/queries";
import { loadDraftDetail } from "@/data/drafts/queries";
import { loadEmbed } from "@/app/loadEmbed";
import { DraftEditor } from "./DraftEditor";

export default async function DraftPage({ params }: { params: Promise<{ rkey: string }> }) {
  const { rkey } = await params;

  const did = await loadCurrentDid();
  if (!did) {
    redirect("/login");
  }

  const draft = await loadDraftDetail(rkey);
  if (!draft) {
    notFound();
  }

  // Preload embeds for all stops that have external links
  const initialEmbeds: Array<[string, Promise<React.ReactElement>]> = draft.stops
    .filter((stop) => stop.external?.uri)
    .map((stop) => [stop.external!.uri, loadEmbed(stop.external!.uri)]);

  return <DraftEditor rkey={rkey} initialDraft={draft} initialEmbeds={initialEmbeds} />;
}
