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

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

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(),
  ]);

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