"use client";

/**
 * Client-only "Copy citation" button for /studies/[pmid].
 *
 * Builds a Vancouver-style citation string from the already-loaded `Study`
 * record and writes it to the clipboard. We accept the citation as a prop
 * from the server component so the formatting logic can be unit-tested in
 * isolation (and so we don't have to import the `Study` type twice).
 *
 * The button gives short transient feedback after a click: "Copied!" for a
 * couple of seconds, then snaps back to its idle label. We deliberately do
 * NOT render the citation string inline — the detail page already shows all
 * the fields a reader needs, so inlining would just be noise.
 */

import { useState } from "react";

type Props = {
  citation: string;
};

export function CopyCitationButton({ citation }: Props) {
  const [state, setState] = useState<"idle" | "copied" | "error">("idle");

  async function handleCopy() {
    try {
      if (navigator?.clipboard?.writeText) {
        await navigator.clipboard.writeText(citation);
      } else {
        // Fallback for older browsers / non-secure contexts.
        const ta = document.createElement("textarea");
        ta.value = citation;
        ta.setAttribute("readonly", "");
        ta.style.position = "absolute";
        ta.style.left = "-9999px";
        document.body.appendChild(ta);
        ta.select();
        document.execCommand("copy");
        document.body.removeChild(ta);
      }
      setState("copied");
    } catch {
      setState("error");
    }
    window.setTimeout(() => setState("idle"), 2000);
  }

  const label =
    state === "copied"
      ? "Copied!"
      : state === "error"
        ? "Copy failed"
        : "Copy citation";

  return (
    <button
      type="button"
      onClick={handleCopy}
      aria-live="polite"
      className="inline-flex items-center justify-center gap-2 rounded-lg border border-[var(--color-line)] bg-transparent px-6 py-3 text-[15px] font-semibold text-[var(--color-ink)] transition-all duration-200 hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
    >
      <svg
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
        className="h-4 w-4"
        aria-hidden
      >
        {state === "copied" ? (
          <path d="M20 6 9 17l-5-5" />
        ) : (
          <>
            <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
          </>
        )}
      </svg>
      {label}
    </button>
  );
}
