"use client";

import { use, createContext } from "react";
import type { ExternalEmbed } from "@/data/queries";
import "./embeds/TrailEmbed.css";
import "@/app/TrailCard.css";

type EmbedPromise = Promise<React.ReactElement>;
export type EmbedCache = Map<string, EmbedPromise>;
export const EmbedCacheContext = createContext<[EmbedCache | null, (c: EmbedCache) => void]>([
  null,
  () => {},
]);

type Props = {
  external: ExternalEmbed;
  onDelete?: () => void;
};

function isTrailUri(uri: string): boolean {
  return uri.includes("/app.sidetrail.trail/");
}

function getPromise(uri: string, cache: EmbedCache): EmbedPromise {
  const existing = cache.get(uri);
  if (!existing) {
    throw new Error(`Embed not in cache: ${uri}. Must be pre-populated before render.`);
  }
  return existing;
}

export function StopEmbed({ external, onDelete }: Props) {
  const [cache] = use(EmbedCacheContext);
  if (!cache) throw new Error("StopEmbed must be used within EmbedCacheContext.Provider");

  const uri = external.uri;
  const isTrail = isTrailUri(uri);
  const promise = getPromise(uri, cache);
  const embed = use(promise);

  if (onDelete) {
    const containerClass = isTrail ? "TrailEmbed-container" : "BlueskyPostEmbed-container";
    const buttonClass = isTrail ? "TrailEmbed-deleteButton" : "BlueskyPostEmbed-deleteButton";
    return (
      <div className={containerClass}>
        {embed}
        <button onClick={onDelete} className={buttonClass} title="remove link">
          ×
        </button>
      </div>
    );
  }

  return embed;
}
