"use client";

import { useRef, useState } from "react";
import { eventSlug, withDateMarker } from "@/lib/event-url";

export interface AffiliateLinkEvent {
  id: string;
  title: string;
  slug: string | null;
  startsAt: string;
}

// Copies a promoter's referral link. With an event picked it's the short,
// readable /go/<event-name>/<code> form that lands on that event (see
// src/app/go/[event]/[code]/route.ts); "Whole site" keeps the old homepage
// ?ref= link. Either way the click is credited for 30 days.
export default function CopyAffiliateLinkButton({ code, events }: { code: string; events: AffiliateLinkEvent[] }) {
  const [eventId, setEventId] = useState<string>(events[0]?.id ?? "");
  const [copied, setCopied] = useState(false);
  const [fallbackUrl, setFallbackUrl] = useState<string | null>(null);
  const fallbackRef = useRef<HTMLInputElement>(null);

  function linkFor(origin: string) {
    const event = events.find((e) => e.id === eventId);
    // The event's stored slug is its link name (/events/<slug>); /go uses it too.
    const slug = event ? event.slug || eventSlug(event.title) : "";
    // Lowercase reads better in a link; codes match case-insensitively
    // (affiliates.code uses a case-insensitive collation).
    const ref = encodeURIComponent(code.toLowerCase());
    // The date marker makes WhatsApp build a fresh preview after a date change.
    return event && slug ? withDateMarker(`${origin}/go/${slug}/${ref}`, event.startsAt) : `${origin}/?ref=${ref}`;
  }

  async function copy() {
    const url = linkFor(window.location.origin);
    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 flex items-center gap-1.5">
      <select
        value={eventId}
        onChange={(e) => {
          setEventId(e.target.value);
          setCopied(false);
        }}
        aria-label="Link to"
        className="be-input max-w-[12rem] py-1 text-xs"
      >
        {events.map((e) => (
          <option key={e.id} value={e.id}>
            {e.title}
          </option>
        ))}
        <option value="">Whole site (homepage)</option>
      </select>
      <button
        type="button"
        onClick={copy}
        className="whitespace-nowrap rounded-md border border-be-border px-2.5 py-1 text-xs font-medium hover:bg-be-surface-2"
      >
        {copied ? "Copied!" : "Copy 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>
  );
}
