"use client";

import { useEffect, useRef, useState } from "react";
import Script from "next/script";
import classNames from "classnames";
import type { Lang } from "@/lib/config";

interface AIVoiceAgentCTAProps {
  lang: Lang;
}

export default function AIVoiceAgentCTA({ lang }: AIVoiceAgentCTAProps) {
  const widgetRef = useRef<HTMLDivElement>(null);
  const [isWidgetReady, setIsWidgetReady] = useState(false);
  const isAr = lang === "ar";

  useEffect(() => {
    // Inject the widget element after component mounts to avoid hydration issues
    if (
      widgetRef.current &&
      !widgetRef.current.querySelector("elevenlabs-convai")
    ) {
      const widget = document.createElement("elevenlabs-convai");
      widget.setAttribute("agent-id", "agent_1901kankm2vreyba3t77q3he8210");
      widgetRef.current.appendChild(widget);
      setIsWidgetReady(true);

      // Listen for collapse button clicks to completely hide the widget
      const observer = new MutationObserver(() => {
        const shadowRoot = widget.shadowRoot;
        if (shadowRoot) {
          // Find collapse button when expanded
          const collapseButton = Array.from(
            shadowRoot.querySelectorAll("button"),
          ).find(
            (btn: any) =>
              btn.textContent?.toLowerCase().includes("collapse") ||
              btn.getAttribute("aria-label")?.toLowerCase().includes("close") ||
              btn
                .getAttribute("aria-label")
                ?.toLowerCase()
                .includes("minimize"),
          );

          if (
            collapseButton &&
            !collapseButton.hasAttribute("data-listener-added")
          ) {
            collapseButton.setAttribute("data-listener-added", "true");
            collapseButton.addEventListener("click", () => {
              // Let the widget collapse naturally, then hide the container
              setTimeout(() => {
                if (widgetRef.current) {
                  widgetRef.current.style.display = "none";
                }
              }, 400); // Wait for collapse animation to complete
            });
          }

          // Also hide when clicking the minimized bubble's close if it exists
          const minimizedButtons = shadowRoot.querySelectorAll("button");
          minimizedButtons.forEach((btn: any) => {
            if (
              !btn.hasAttribute("data-hide-listener") &&
              btn.textContent?.toLowerCase().includes("need help")
            ) {
              // This is the minimized state - add a way to close it completely
              // We'll hide on a long press or add a close icon
            }
          });
        }
      });

      // Observe changes to the shadow DOM
      if (widget.shadowRoot) {
        observer.observe(widget.shadowRoot, {
          childList: true,
          subtree: true,
        });
      }

      return () => observer.disconnect();
    }
  }, []);

  const handleTryAgent = () => {
    if (!isWidgetReady) return;

    // Show the widget container
    if (widgetRef.current) {
      widgetRef.current.style.display = "block";
    }

    // Wait for the widget to be visible, then find and click "Start a call" button
    setTimeout(() => {
      const widget = widgetRef.current?.querySelector(
        "elevenlabs-convai",
      ) as any;
      if (widget?.shadowRoot) {
        const shadowRoot = widget.shadowRoot;

        // Find the "Start a call" button
        const buttons = Array.from(shadowRoot.querySelectorAll("button"));
        const startCallButton = buttons.find((btn: any) => {
          const text = btn.textContent?.toLowerCase() || "";
          return text.includes("call") || text.includes("start");
        });

        if (startCallButton) {
          (startCallButton as HTMLButtonElement).click();
        }
      }
    }, 200);
  };

  return (
    <>
      {/* Load ElevenLabs widget script */}
      <Script
        src="https://unpkg.com/@elevenlabs/convai-widget-embed"
        strategy="lazyOnload"
        async
      />

      <section className="relative overflow-hidden bg-gradient-to-br from-brand-green to-emerald-600 text-white">
        <div className="absolute inset-0 bg-[url('/grid.svg')] opacity-10" />

        <div className="relative mx-auto max-w-6xl px-4 py-20">
          <div className="text-center">
            {/* Badge */}
            <div className="mb-6 inline-flex items-center gap-2 rounded-full bg-white/20 px-4 py-2 backdrop-blur">
              <span className="text-2xl">🎙️</span>
              <span className="text-sm font-semibold">
                {isAr ? "تقنية الذكاء الاصطناعي الصوتي" : "AI Voice Technology"}
              </span>
            </div>

            {/* Heading */}
            <h2 className="text-3xl font-bold md:text-5xl">
              {isAr
                ? "جرّب مساعدنا الصوتي الذكي الآن"
                : "Try Our AI Voice Agent Now"}
            </h2>

            {/* Description */}
            <p className="mx-auto mt-6 max-w-2xl text-lg text-white/90">
              {isAr
                ? "تحدث مباشرةً مع مساعدنا الصوتي الذكي واكتشف كيف يمكن لموعدي أن يحول استفسارات عملائك إلى حجوزات مؤكدة بالعربية والإنجليزية"
                : "Speak directly with our AI voice agent and discover how Mawidi can transform your customer inquiries into confirmed bookings in Arabic and English"}
            </p>

            {/* CTA Button */}
            <div className="mt-10">
              <button
                onClick={handleTryAgent}
                className={classNames(
                  "group relative inline-flex items-center gap-3 rounded-xl bg-white px-8 py-4 text-lg font-semibold text-brand-green shadow-2xl transition-all hover:scale-105 hover:shadow-xl",
                  "focus:outline-none focus:ring-4 focus:ring-white/50",
                )}
              >
                <span className="text-2xl transition-transform group-hover:scale-110">
                  🎤
                </span>
                <span>
                  {isAr ? "ابدأ المحادثة الصوتية" : "Start Voice Conversation"}
                </span>
                <svg
                  className={classNames(
                    "h-5 w-5 transition-transform group-hover:translate-x-1",
                    isAr && "rotate-180 group-hover:-translate-x-1",
                  )}
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M13 7l5 5m0 0l-5 5m5-5H6"
                  />
                </svg>
              </button>
            </div>

            {/* Features */}
            <div className="mt-12 grid gap-6 text-left md:grid-cols-3">
              {[
                {
                  icon: "🌐",
                  titleEn: "Bilingual Support",
                  titleAr: "دعم ثنائي اللغة",
                  descEn: "Seamlessly switches between Arabic and English",
                  descAr: "يتنقل بسلاسة بين العربية والإنجليزية",
                },
                {
                  icon: "⚡",
                  titleEn: "Instant Responses",
                  titleAr: "ردود فورية",
                  descEn: "Natural conversation with sub-second response time",
                  descAr: "محادثة طبيعية مع استجابة فورية",
                },
                {
                  icon: "🎯",
                  titleEn: "Smart Booking",
                  titleAr: "حجز ذكي",
                  descEn: "Understands context and guides to appointments",
                  descAr: "يفهم السياق ويوجه للمواعيد",
                },
              ].map((feature) => (
                <div
                  key={feature.titleEn}
                  className="rounded-xl bg-white/10 p-5 backdrop-blur transition-colors hover:bg-white/20"
                >
                  <div className="text-3xl">{feature.icon}</div>
                  <h3 className="mt-3 font-semibold">
                    {isAr ? feature.titleAr : feature.titleEn}
                  </h3>
                  <p className="mt-2 text-sm text-white/80">
                    {isAr ? feature.descAr : feature.descEn}
                  </p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* ElevenLabs Widget Container - Hidden until user clicks button */}
      <div ref={widgetRef} style={{ display: "none" }} />
    </>
  );
}
