"use client";

import React, { useState, useRef, useCallback, useEffect } from "react";
import Image from "next/image";
import { motion } from "motion/react";
import {
  Mic,
  ShieldCheck,
  Zap,
  MessageSquare,
  Globe,
} from "lucide-react";
import { cn } from "@/lib/utils";

type Channel = "voice" | "whatsapp" | "web";

const CHANNEL_ORDER: Channel[] = ["voice", "whatsapp", "web"];

const CHANNEL_DATA: Record<
  Channel,
  {
    image: string;
    alt: string;
    badgeText: string;
    subText: string;
  }
> = {
  voice: {
    image: "/images/home-voice-agent-image.webp",
    alt: "Quto AI Voice Agent desktop console showing live voice interaction and caller waveform",
    badgeText: "Live Inbound Call",
    subText: "Streaming voice",
  },
  whatsapp: {
    image: "/images/home-whatsapp-image.webp",
    alt: "Quto AI WhatsApp Business Agent interface displaying instant customer conversation and demo confirmation",
    badgeText: "WhatsApp Business Active",
    subText: "Meta Cloud API Verified",
  },
  web: {
    image: "/images/home-web-widget-image.webp",
    alt: "Quto AI Web Concierge Widget interface showing on-site instant qualification and booking assistance",
    badgeText: "Site Agent Connected",
    subText: "Active on your website",
  },
};

export function HeroConsole({ className }: { className?: string }) {
  const [activeChannel, setActiveChannel] = useState<Channel>("voice");

  // Preload inactive tab images in the background after initial render for instant tab switching
  useEffect(() => {
    const inactiveChannels = ["whatsapp", "web"] as const;
    inactiveChannels.forEach((ch) => {
      const img = new window.Image();
      img.src = CHANNEL_DATA[ch].image;
    });
  }, []);

  // Spotlight mouse glow tracking
  const containerRef = useRef<HTMLDivElement>(null);
  const [mousePos, setMousePos] = useState({ x: -400, y: -400 });
  const [isHovered, setIsHovered] = useState(false);

  const handleMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    if (!containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();
    setMousePos({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    });
  }, []);

  return (
    <div
      ref={containerRef}
      onMouseMove={handleMouseMove}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      className={cn(
        "relative mx-auto w-full max-w-6xl rounded-3xl border border-[#4FDAF1]/30 bg-card/95 p-4 shadow-2xl shadow-[0_0_50px_-15px_rgba(79,218,241,0.25)] backdrop-blur-xl transition-all md:p-6 lg:p-8",
        className,
      )}
    >
      {/* Mouse hover radial glow bubble tracking */}
      <div
        className="pointer-events-none absolute -inset-px rounded-3xl transition-opacity duration-300 z-0"
        style={{
          opacity: isHovered ? 1 : 0,
          background: `radial-gradient(550px circle at ${mousePos.x}px ${mousePos.y}px, rgba(79, 218, 241, 0.16), transparent 70%)`,
        }}
        aria-hidden="true"
      />

      {/* Console Top Toolbar */}
      <div className="relative z-10 flex flex-col gap-3 border-b border-border/60 pb-4 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between">
        {/* Channel Switcher Tabs — full-width segmented control on mobile */}
        <div
          role="group"
          aria-label="Preview a channel"
          className="flex w-full items-center gap-1 rounded-full border border-border/80 bg-background/90 p-1 shadow-xs sm:w-auto sm:gap-1.5"
        >
          <button
            type="button"
            onClick={() => setActiveChannel("voice")}
            aria-pressed={activeChannel === "voice"}
            className={cn(
              "flex min-w-0 flex-1 items-center justify-center gap-1 whitespace-nowrap rounded-full px-2 py-1.5 text-[11px] font-semibold transition-all sm:flex-initial sm:gap-2 sm:px-4 sm:text-xs",
              activeChannel === "voice"
                ? "bg-gradient-brand text-white font-bold shadow-sm glow-brand [&_svg]:text-white"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            <Mic className="hidden size-3.5 shrink-0 sm:block" />
            <span>Voice Agent</span>
          </button>
          <button
            type="button"
            onClick={() => setActiveChannel("whatsapp")}
            aria-pressed={activeChannel === "whatsapp"}
            className={cn(
              "flex min-w-0 flex-1 items-center justify-center gap-1 whitespace-nowrap rounded-full px-2 py-1.5 text-[11px] font-semibold transition-all sm:flex-initial sm:gap-2 sm:px-4 sm:text-xs",
              activeChannel === "whatsapp"
                ? "bg-gradient-brand text-white font-bold shadow-sm glow-brand [&_svg]:text-white"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            <MessageSquare className="hidden size-3.5 shrink-0 sm:block" />
            <span>WhatsApp Agent</span>
          </button>
          <button
            type="button"
            onClick={() => setActiveChannel("web")}
            aria-pressed={activeChannel === "web"}
            className={cn(
              "flex min-w-0 flex-1 items-center justify-center gap-1 whitespace-nowrap rounded-full px-2 py-1.5 text-[11px] font-semibold transition-all sm:flex-initial sm:gap-2 sm:px-4 sm:text-xs",
              activeChannel === "web"
                ? "bg-gradient-brand text-white font-bold shadow-sm glow-brand [&_svg]:text-white"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            <Globe className="hidden size-3.5 shrink-0 sm:block" />
            <span>Web Widget</span>
          </button>
        </div>

        {/* Live status badge */}
        <div className="flex items-center gap-2 self-start rounded-full border border-[#4FDAF1]/40 bg-[#4FDAF1]/10 px-3 py-1 text-xs font-semibold text-foreground sm:self-auto">
          <span className="relative flex size-2">
            <span className="absolute inline-flex size-full animate-ping rounded-full bg-[#4FDAF1] opacity-75 motion-reduce:animate-none" />
            <span className="relative inline-flex size-2 rounded-full bg-[#4FDAF1]" />
          </span>
          <span>Live Demo Ready</span>
        </div>
      </div>

      {/* Main Preview Grid: Active UI mockups left, stats right */}
      <div className="relative z-10 mt-6 grid grid-cols-1 gap-6 lg:grid-cols-12 lg:gap-8">
        {/* Left Column: Interactive Product Previews */}
        <div className="lg:col-span-8 flex flex-col justify-center overflow-hidden rounded-2xl border border-border/80 bg-background/60 p-3 sm:p-6 shadow-xs">
          <div className="relative min-h-[380px] w-full flex items-center justify-center">
            {CHANNEL_ORDER.map((ch) => {
              const active = activeChannel === ch;
              return (
                <motion.div
                  key={ch}
                  aria-hidden={!active}
                  initial={false}
                  animate={{
                    opacity: active ? 1 : 0,
                    scale: active ? 1 : 0.98,
                    pointerEvents: active ? "auto" : "none",
                  }}
                  transition={{ duration: 0.25, ease: "easeOut" }}
                  className="absolute inset-0 flex items-center justify-center"
                >
                  <Image
                    src={CHANNEL_DATA[ch].image}
                    alt={CHANNEL_DATA[ch].alt}
                    width={920}
                    height={620}
                    priority={ch === "voice"}
                    loading={ch === "voice" ? "eager" : "lazy"}
                    sizes="(max-width: 640px) 92vw, (max-width: 1024px) 90vw, 680px"
                    className="h-auto w-full max-h-[460px] rounded-xl object-contain shadow-xs"
                  />
                </motion.div>
              );
            })}
          </div>
        </div>

        {/* Right Column: Live Telemetry & Capability Badges */}
        <div className="flex flex-col justify-between gap-3 lg:col-span-4">
          <div className="flex-1 rounded-2xl border border-[#E26B0B]/30 bg-background/95 p-4 md:p-5 shadow-[0_0_20px_-8px_rgba(226,107,11,0.25)] transition-all hover:border-[#E26B0B]/60 flex flex-col justify-center">
            <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
              <span className="flex size-6 items-center justify-center rounded-lg bg-[#E26B0B]/15 text-[#E26B0B]">
                <Zap className="size-3.5" />
              </span>
              Turn-Taking Speed
            </div>
            <div className="mt-2 font-display text-3xl font-extrabold tracking-tight text-gradient-warm">
              &lt;350ms
            </div>
            <p className="mt-1 text-xs text-pretty text-muted-foreground leading-relaxed">
              Zero awkward pauses. The agent detects interruptions and responds with natural human cadence.
            </p>
          </div>

          <div className="flex-1 rounded-2xl border border-[#67B7E7]/30 bg-background/95 p-4 md:p-5 shadow-[0_0_20px_-8px_rgba(103,183,231,0.25)] transition-all hover:border-[#67B7E7]/60 flex flex-col justify-center">
            <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
              <span className="flex size-6 items-center justify-center rounded-lg bg-[#67B7E7]/15 text-[#67B7E7]">
                <Globe className="size-3.5" />
              </span>
              Global Accents
            </div>
            <div className="mt-2 font-display text-3xl font-extrabold tracking-tight text-gradient-cool">
              20+ Languages
            </div>
            <p className="mt-1 text-xs text-pretty text-muted-foreground leading-relaxed">
              Native dialect recognition across US, UK, Indian English, Hindi, Hinglish, Spanish, Arabic &amp; more.
            </p>
          </div>

          <div className="flex-1 rounded-2xl border border-[#4FDAF1]/30 bg-background/95 p-4 md:p-5 shadow-[0_0_20px_-8px_rgba(79,218,241,0.25)] transition-all hover:border-[#4FDAF1]/60 flex flex-col justify-center">
            <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
              <span className="flex size-6 items-center justify-center rounded-lg bg-[#4FDAF1]/15 text-[#4FDAF1]">
                <ShieldCheck className="size-3.5" />
              </span>
              Data Security
            </div>
            <div className="mt-2 font-display text-2xl font-extrabold tracking-tight text-gradient-brand">
              Private by Default
            </div>
            <p className="mt-1 text-xs text-pretty text-muted-foreground leading-relaxed">
              Runs in your VPC. Customer audio and PII are never retained or used to train third-party models.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
