"use client";

import { useRef, useState } from "react";
import { eventPath, withDateMarker } from "@/lib/event-url";

export default function CopyEventLinkButton({
  eventId,
  eventTitle,
  eventSlug,
  startsAt,
}: {
  eventId: string;
  eventTitle: string;
  eventSlug: string | null;
  startsAt: string;
}) {
  const [copied, setCopied] = useState(false);
  const [fallbackUrl, setFallbackUrl] = useState<string | null>(null);
  const fallbackRef = useRef<HTMLInputElement>(null);

  async function copy() {
    const url = withDateMarker(`${window.location.origin}${eventPath({ id: eventId, title: eventTitle, slug: eventSlug })}`, startsAt);
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // Clipboard access can be blocked (permissions, insecure context); fall
      // back to a selectable field instead of a blocking prompt() dialog,
      // which isn't supported in every embedding context.
      setFallbackUrl(url);
      setTimeout(() => fallbackRef.current?.select(), 0);
    }
  }

  return (
    <div className="relative inline-block">
      <button
        type="button"
        onClick={copy}
        className="rounded-md border border-be-border px-3 py-1.5 text-sm font-medium hover:bg-be-surface-2"
      >
        {copied ? "Link copied!" : "Copy event link"}
      </button>
      {fallbackUrl && (
        <input
          ref={fallbackRef}
          readOnly
          value={fallbackUrl}
          onClick={(e) => e.currentTarget.select()}
          onBlur={() => setFallbackUrl(null)}
          className="input absolute right-0 top-full z-10 mt-1 w-72 text-xs"
        />
      )}
    </div>
  );
}
