import { Metadata } from "next";
import { loadTrailDetail, loadCurrentUser } from "@/data/queries";
import { TrailView } from "./TrailView";
import { loadEmbed } from "@/app/loadEmbed";

type Props = {
  params: Promise<{
    handle: string;
    rkey: string;
  }>;
};

export const instant = false;

function decodeHandle(rawHandle: string): string {
  return decodeURIComponent(rawHandle);
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { handle: rawHandle, rkey } = await params;
  const handle = decodeHandle(rawHandle);

  const trail = await loadTrailDetail(handle, rkey);

  return {
    title: trail.header.title,
    description: trail.header.description || `A trail by @${trail.header.creator.handle}`,
    openGraph: {
      title: trail.header.title,
      description: trail.header.description || `A trail by @${trail.header.creator.handle}`,
    },
  };
}

export default async function TrailPage({ params }: Props) {
  const { handle: rawHandle, rkey } = await params;
  const handle = decodeHandle(rawHandle);

  const [trail, currentUser] = await Promise.all([
    loadTrailDetail(handle, rkey),
    loadCurrentUser(),
  ]);

  // await new Promise(resolve => setTimeout(resolve, 4000))

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

  return (
    <TrailView
      trail={trail}
      cleanHandle={handle}
      rkey={rkey}
      currentUserDid={currentUser?.did || null}
      initialEmbeds={initialEmbeds}
    />
  );
}
