"use client";

import { useState, useCallback } from "react";

interface VoiceAgentTriggerButtonProps {
  label: string;
  ariaLabel?: string;
}

export default function VoiceAgentTriggerButton({
  label,
  ariaLabel,
}: VoiceAgentTriggerButtonProps) {
  const [isClicked, setIsClicked] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const startElevenLabsConversation = useCallback(() => {
    // First, dispatch event to activate the widget if it's not already loaded
    window.dispatchEvent(new CustomEvent("elevenlabs-activate"));

    // Give the widget time to load, then try to interact with it
    setTimeout(() => {
      const widget = document.querySelector(
        "elevenlabs-convai",
      ) as HTMLElement & {
        startConversation?: () => void;
        click?: () => void;
      };

      if (widget) {
        // Try to start conversation programmatically
        if (typeof widget.startConversation === "function") {
          widget.startConversation();
          return;
        }

        // Alternative: Find and click the widget's start button
        const shadowRoot = widget.shadowRoot;
        if (shadowRoot) {
          const startButton = shadowRoot.querySelector(
            "button",
          ) as HTMLButtonElement;
          if (startButton) {
            startButton.click();
            return;
          }
        }

        // Fallback: Click the widget itself
        widget.click();
      }
    }, 500);
  }, []);

  const handleClick = () => {
    setIsClicked(true);
    setIsLoading(true);

    // Scroll to demo section first
    const demoSection = document.getElementById("demo");
    if (demoSection) {
      demoSection.scrollIntoView({ behavior: "smooth", block: "center" });
    }

    // Start the conversation
    startElevenLabsConversation();

    // Reset states
    setTimeout(() => {
      setIsClicked(false);
      setIsLoading(false);
    }, 800);
  };

  return (
    <button
      onClick={handleClick}
      aria-label={ariaLabel || label}
      disabled={isLoading}
      className={`group relative inline-flex items-center justify-center gap-3 overflow-hidden rounded-xl bg-gradient-to-r from-[#10B981] to-[#059669] px-8 py-4 text-base font-bold text-white shadow-lg shadow-[#10B981]/25 transition-all duration-300 hover:-translate-y-0.5 hover:shadow-xl hover:shadow-[#10B981]/30 active:scale-95 disabled:opacity-70 ${
        isClicked ? "scale-95" : ""
      }`}
    >
      {/* Animated Pulse Ring */}
      <span className="absolute inset-0 rounded-xl bg-white/20 opacity-0 transition-opacity group-hover:opacity-100" />

      {/* Icon with pulse animation when loading */}
      <span className={`relative text-xl ${isLoading ? "animate-pulse" : ""}`}>
        🎙️
      </span>

      {/* Label */}
      <span className="relative">{isLoading ? "Starting..." : label}</span>

      {/* Arrow Animation */}
      <span className="relative transition-transform duration-300 group-hover:translate-x-1">
        →
      </span>

      {/* Gradient overlay on hover */}
      <span className="absolute inset-0 -z-10 bg-gradient-to-r from-[#059669] to-[#10B981] opacity-0 transition-opacity duration-300 group-hover:opacity-100" />
    </button>
  );
}
