"use client";

import { useState } from "react";
import { cn } from "@/lib/utils";
import { trackEvent } from "@/lib/analytics";
import { openCalModal } from "@/lib/cal";

interface CalButtonProps {
  children: React.ReactNode;
  className?: string;
  variant?: "primary" | "secondary";
  location?: string;
}

export function CalButton({
  children,
  className,
  variant = "primary",
  location = "unknown",
}: CalButtonProps) {
  const [isOpening, setIsOpening] = useState(false);

  // L'embed Cal.com n'est plus chargé au montage (voir lib/cal.ts) : le script
  // et ses cookies tiers n'arrivent qu'ici, au clic. D'où l'état d'attente —
  // sans lui le bouton paraîtrait mort le temps du téléchargement.
  const handleClick = async () => {
    if (isOpening) return;
    trackEvent("cta_click", {
      cta_type: "cal_booking",
      cta_location: location,
    });
    setIsOpening(true);
    try {
      await openCalModal();
    } finally {
      setIsOpening(false);
    }
  };

  const baseStyles =
    variant === "primary"
      ? "bg-gradient-to-r from-orange-500 to-orange-600 text-white hover:from-orange-600 hover:to-orange-800 shadow-md hover:shadow-lg"
      : "border border-slate-300 text-slate-900 hover:bg-slate-50";

  return (
    <button
      type="button"
      onClick={handleClick}
      aria-busy={isOpening}
      className={cn(
        "font-semibold rounded-full transition-all cursor-pointer",
        "inline-flex items-center justify-center gap-2",
        baseStyles,
        className
      )}
    >
      {isOpening && (
        <span
          aria-hidden="true"
          className="h-4 w-4 shrink-0 animate-spin rounded-full border-2 border-current border-t-transparent"
        />
      )}
      {children}
    </button>
  );
}
