"use client";

import { useEffect, useRef, useState } from "react";

/**
 * Copy-to-clipboard icon button. Ported verbatim from leisure-ui.com's
 * components/ui/CopyButton.tsx for BookingDetailsView — same component, same
 * markup, same fallback behaviour.
 *
 * `label` is required so every instance says what it copies: these buttons
 * sit next to the thing they copy, and two adjacent controls both
 * announcing "Copy booking reference" is a screen-reader dead end.
 *
 * `navigator.clipboard` is undefined outside a secure context — plain-http
 * dev hosts and LAN IPs included — so the execCommand path below is a real
 * fallback, not legacy cruft. If both fail the button reports failure rather
 * than showing a checkmark it hasn't earned.
 */
export default function CopyButton({
  value,
  label,
  className = "",
}: {
  value: string;
  /** What is being copied, e.g. "booking reference" — becomes "Copy booking reference". */
  label: string;
  className?: string;
}) {
  const [state, setState] = useState<"idle" | "copied" | "failed">("idle");
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, []);

  const flash = (next: "copied" | "failed") => {
    setState(next);
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => setState("idle"), 1600);
  };

  const handleCopy = async () => {
    try {
      if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(value);
        flash("copied");
        return;
      }
    } catch {
      // Permission denied or non-secure context — fall through to execCommand.
    }

    try {
      const textarea = document.createElement("textarea");
      textarea.value = value;
      textarea.setAttribute("readonly", "");
      textarea.style.position = "fixed";
      textarea.style.top = "-9999px";
      document.body.appendChild(textarea);
      textarea.select();
      const ok = document.execCommand("copy");
      document.body.removeChild(textarea);
      flash(ok ? "copied" : "failed");
    } catch {
      flash("failed");
    }
  };

  return (
    <button
      type="button"
      onClick={handleCopy}
      className={`fbs-copy-btn d-inline-flex align-items-center justify-content-center border-0 bg-transparent p-1 rounded-2 color-text-first flex-shrink-0 ${className}`}
      aria-label={`Copy ${label}`}
      title={state === "copied" ? "Copied" : state === "failed" ? "Press Ctrl+C to copy" : `Copy ${label}`}
    >
      {state === "copied" ? (
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" width={16} height={16} aria-hidden="true" className="color-text-green-700">
          <path d="M20 6 9 17l-5-5" />
        </svg>
      ) : state === "failed" ? (
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width={16} height={16} aria-hidden="true">
          <circle cx="12" cy="12" r="10" />
          <path d="M12 8v4M12 16h.01" />
        </svg>
      ) : (
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width={16} height={16} aria-hidden="true">
          <rect x="9" y="9" width="13" height="13" rx="2" />
          <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
        </svg>
      )}
      <span className="visually-hidden" role="status" aria-live="polite">
        {state === "copied" ? `${label} copied` : state === "failed" ? `Could not copy ${label}` : ""}
      </span>
    </button>
  );
}
