"use client";

import { useState, useEffect } from "react";
import Script from "next/script";

interface ElevenLabsWidgetProps {
  agentId: string;
  placeholder?: string;
}

export default function ElevenLabsWidget({
  agentId,
  placeholder,
}: ElevenLabsWidgetProps) {
  const [isActive, setIsActive] = useState(false);
  const [scriptLoaded, setScriptLoaded] = useState(false);

  // Listen for custom event to activate the widget
  useEffect(() => {
    const handleActivate = () => {
      setIsActive(true);
    };

    window.addEventListener("elevenlabs-activate", handleActivate);
    return () =>
      window.removeEventListener("elevenlabs-activate", handleActivate);
  }, []);

  if (!isActive) {
    return (
      <div className="flex min-h-[200px] flex-col items-center justify-center rounded-xl border-2 border-dashed border-[#10B981]/30 bg-[#10B981]/5 p-8 text-center">
        <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-[#10B981]/10">
          <span className="text-3xl">🎙️</span>
        </div>
        <p className="text-sm font-medium text-[#1E293B] dark:text-white">
          {placeholder || 'Click "Start Conversation Now" to begin'}
        </p>
        <p className="mt-2 text-xs text-[#64748B] dark:text-[#94A3B8]">
          Voice AI powered by ElevenLabs
        </p>
      </div>
    );
  }

  return (
    <div className="min-h-[200px]">
      {/* Load the ElevenLabs script only when activated */}
      <Script
        src="https://unpkg.com/@elevenlabs/convai-widget-embed"
        strategy="lazyOnload"
        onLoad={() => setScriptLoaded(true)}
      />

      {/* Render the widget */}
      {/* @ts-ignore - Custom element from ElevenLabs */}
      <elevenlabs-convai agent-id={agentId}></elevenlabs-convai>

      {!scriptLoaded && (
        <div className="flex min-h-[200px] items-center justify-center">
          <div className="flex items-center gap-3">
            <div className="h-5 w-5 animate-spin rounded-full border-2 border-[#10B981] border-t-transparent" />
            <span className="text-sm text-[#64748B]">
              Loading voice agent...
            </span>
          </div>
        </div>
      )}
    </div>
  );
}
