// Copy selected text to clipboard (plain text, preserve line breaks)
// Critical for technical textbooks with code examples
// Procedural implementation (no OOP)

function setupPDFClipboard(container: HTMLElement): void {
  container.addEventListener("copy", (e) => {
    handlePDFCopy(e);
  });
}

function handlePDFCopy(event: ClipboardEvent): void {
  const selection = window.getSelection();
  if (!selection || selection.rangeCount === 0) return;

  const selectedText = selection.toString();

  if (!selectedText) return;

  const plainText = formatPDFPlainText(selectedText);

  event.clipboardData?.setData("text/plain", plainText);

  event.preventDefault();

  showPDFCopyFeedback();
}

function formatPDFPlainText(text: string): string {
  let formatted = text;

  formatted = formatted.replace(/[ \t]+/g, " ");

  formatted = formatted
    .split("\n")
    .map((line) => line.trim())
    .join("\n");

  formatted = formatted.replace(/\n{3,}/g, "\n\n");

  return formatted;
}

async function copyPDFText(text: string): Promise<boolean> {
  const formatted = formatPDFPlainText(text);

  try {
    await navigator.clipboard.writeText(formatted);
    showPDFCopyFeedback();
    return true;
  } catch (error) {
    console.error("Failed to copy text:", error);

    const textarea = document.createElement("textarea");
    textarea.value = formatted;
    textarea.style.position = "fixed";
    textarea.style.opacity = "0";
    document.body.appendChild(textarea);
    textarea.select();

    try {
      const success = document.execCommand("copy");
      if (success) {
        showPDFCopyFeedback();
      }
      return success;
    } catch (fallbackError) {
      console.error("Fallback copy failed:", fallbackError);
      return false;
    } finally {
      document.body.removeChild(textarea);
    }
  }
}

function showPDFCopyFeedback(): void {
  const toast = document.createElement("div");
  toast.className = "pdf-copy-toast";
  toast.textContent = "Copied to clipboard";
  toast.style.cssText = `
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: var(--accent);
    color: white;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    z-index: 10000;
    animation: fadeIn 0.2s ease-out;
  `;

  document.body.appendChild(toast);

  setTimeout(() => {
    toast.style.animation = "fadeOut 0.2s ease-out";
    setTimeout(() => toast.remove(), 200);
  }, 1500);
}
