// Handle text copying with citation
// Feature Registration Pattern implementation

import type { ReaderContext } from "../core/reader-context";
import { showToast } from "../../toast";

export function init(context: ReaderContext): void {
  let mediaItem: MediaItemSummary | null = null;

  context.events.on("reader:loaded", (detail: { mediaItem: MediaItemSummary }) => {
    mediaItem = detail.mediaItem;
    enableContextMenuCopy(mediaItem);
  });

  context.events.on("copy:selection", async () => {
    if (mediaItem) {
      await copySelection(mediaItem);
    }
  });

  context.events.on("reader:unload", () => {
    mediaItem = null;
  });
}

async function copySelection(mediaItem: MediaItemSummary): Promise<boolean> {
  const selection = window.getSelection();
  if (!selection || selection.rangeCount === 0) return false;

  const selectedText = selection.toString();
  if (!selectedText.trim()) return false;

  const citation = createCitation(selectedText, mediaItem);

  try {
    await navigator.clipboard.writeText(citation);
    showToast("Copied to clipboard", "success");
    return true;
  } catch (error) {
    console.error("Failed to copy:", error);
    showToast("Failed to copy to clipboard", "error");
    return false;
  }
}

function createCitation(text: string, mediaItem: MediaItemSummary): string {
  let citation = `"${text}"\n`;
  citation += `— ${mediaItem.title}`;
  if (mediaItem.author) {
    citation += ` by ${mediaItem.author}`;
  }
  citation += `\n(Source: Bookhoard)`;

  return citation;
}

function enableContextMenuCopy(mediaItem: MediaItemSummary): void {
  document.addEventListener("contextmenu", async (e) => {
    const selection = window.getSelection();
    const selectedText = selection?.toString().trim();

    if (selectedText) {
      e.preventDefault();
      await copySelection(mediaItem);
    }
  });
}