/* eslint-disable @typescript-eslint/no-explicit-any */
import { createFileRoute, Link } from "@tanstack/react-router";
import { useState, useRef, useEffect, useCallback } from "react";
import {
  Mic,
  MicOff,
  Volume2,
  VolumeX,
  Loader2,
  Send,
  Sparkles,
  Radio,
  MessageSquare,
  Copy,
  Check,
  Bot,
  User as UserIcon,
  Zap,
  ArrowLeft,
  Cpu,
  Terminal,
  Activity,
  ShieldAlert,
} from "lucide-react";
import { chatWithVoiceCompanion } from "@/lib/ai";
import { useUserProfile } from "@/lib/user-profile";
import { useTheme } from "@/lib/theme";

export const Route = createFileRoute("/companion")({
  head: () => ({
    meta: [
      { title: "NeuroSaathi Cyber Voice AI · Real-Time Companion" },
      {
        name: "description",
        content:
          "Talk to NeuroSaathi AI in real-time voice and text with instant Gemini audio responses in Hinglish and Hindi.",
      },
      { property: "og:title", content: "NeuroSaathi Cyber Voice AI · Real-Time Companion" },
      {
        property: "og:description",
        content:
          "Instant voice conversation powered by Gemini 2.5 Flash with fast Hinglish response.",
      },
    ],
  }),
  component: CompanionScreen,
});

type Message = {
  id: string;
  sender: "user" | "ai";
  text: string;
  timestamp: string;
  latencyMs?: number;
};

type Personality = "warm" | "cyber" | "coach" | "spiritual" | "playful";

const QUICK_PROMPTS = [
  { label: "⚡ Fast Health Tip", text: "Aaj ka sabse aasan aur accha health tip batao." },
  { label: "🧘 Quick Yoga", text: "Back pain aur posture ke liye fast yoga exercise batao." },
  { label: "✨ Shubh Vichar", text: "Mujhe ek sundar suvichar sunao." },
  { label: "🧩 Quick Riddle", text: "Mere dimag ke liye ek fast paheli pucho." },
  { label: "🍵 Memory Booster", text: "Focus aur memory fast karne ka aasan tareeqa batao." },
];

export function CompanionScreen() {
  const profile = useUserProfile();
  const { theme, toggle: toggleTheme } = useTheme();
  const [viewMode, setViewMode] = useState<"call" | "chat">("call");
  const [personality, setPersonality] = useState<Personality>("warm");
  const [listening, setListening] = useState(false);
  const [loading, setLoading] = useState(false);
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [soundEnabled, setSoundEnabled] = useState(true);
  const [inputText, setInputText] = useState("");
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [liveTranscript, setLiveTranscript] = useState("");
  const [lastLatency, setLastLatency] = useState<number | null>(180);

  const [messages, setMessages] = useState<Message[]>([
    {
      id: "init",
      sender: "ai",
      text: "Namaste! Main aapka Cyber NeuroSaathi Voice AI Assistant hoon. Aap kaisa mehsoos kar rahe hain? Boliye, main turant jawab doonga!",
      timestamp: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
    },
  ]);

  const recognitionRef = useRef<any>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, liveTranscript]);

  const stopAudio = useCallback(() => {
    if (typeof window !== "undefined" && "speechSynthesis" in window) {
      window.speechSynthesis.cancel();
    }
    setIsSpeaking(false);
  }, []);

  // Web Speech API Voice Response (Zero Delay Instant Playback)
  const speakVoiceInstant = useCallback(
    (text: string) => {
      if (!soundEnabled) return;
      stopAudio();
      setIsSpeaking(true);

      if (typeof window !== "undefined" && "speechSynthesis" in window) {
        try {
          const utterance = new SpeechSynthesisUtterance(text);
          utterance.lang = profile.language === "English" ? "en-IN" : "hi-IN";
          utterance.rate = 1.05;
          utterance.pitch = 1.05;
          utterance.onend = () => setIsSpeaking(false);
          utterance.onerror = () => setIsSpeaking(false);
          window.speechSynthesis.speak(utterance);
        } catch (e) {
          console.error("SpeechSynthesis error:", e);
          setIsSpeaking(false);
        }
      } else {
        setIsSpeaking(false);
      }
    },
    [profile.language, soundEnabled, stopAudio],
  );

  // Handle message processing
  const handleSendMessage = async (textToSend: string) => {
    const trimmed = textToSend.trim();
    if (!trimmed || loading) return;

    stopAudio();
    setInputText("");
    setLiveTranscript("");

    const userMsg: Message = {
      id: "usr-" + Date.now(),
      sender: "user",
      text: trimmed,
      timestamp: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
    };

    setMessages((prev) => [...prev, userMsg]);
    setLoading(true);

    const startTime = Date.now();

    try {
      const response = await chatWithVoiceCompanion({
        data: {
          message: trimmed,
          userName: profile.name || "Dost",
          personality,
          language: profile.language || "Hinglish",
          fastMode: true,
        },
      });

      const elapsed = response.latencyMs || Date.now() - startTime;
      setLastLatency(elapsed);

      const aiMsg: Message = {
        id: "ai-" + Date.now(),
        sender: "ai",
        text: response.text,
        timestamp: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
        latencyMs: elapsed,
      };

      setMessages((prev) => [...prev, aiMsg]);
      speakVoiceInstant(response.text);
    } catch (error) {
      console.error("Chat error:", error);
      const errorMsg: Message = {
        id: "err-" + Date.now(),
        sender: "ai",
        text: `Maaf kijiye ${profile.name || "Dost"} ji, main samajh gaya. Phir se boliye!`,
        timestamp: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
      };
      setMessages((prev) => [...prev, errorMsg]);
      speakVoiceInstant(errorMsg.text);
    } finally {
      setLoading(false);
    }
  };

  // Speech Recognition Initializer
  const initRecognition = () => {
    if (typeof window === "undefined") return null;
    const SpeechRecognition =
      (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;

    if (!SpeechRecognition) return null;

    const recognition = new SpeechRecognition();
    recognition.lang = profile.language === "English" ? "en-IN" : "hi-IN";
    recognition.continuous = false;
    recognition.interimResults = true;

    recognition.onstart = () => {
      stopAudio();
      setListening(true);
      setLiveTranscript("Sun raha hoon...");
    };

    recognition.onresult = (event: any) => {
      let interim = "";
      let final = "";
      for (let i = event.resultIndex; i < event.results.length; ++i) {
        if (event.results[i].isFinal) {
          final += event.results[i][0].transcript;
        } else {
          interim += event.results[i][0].transcript;
        }
      }
      if (interim) setLiveTranscript(interim);
      if (final) {
        setLiveTranscript(final);
        setListening(false);
        handleSendMessage(final);
      }
    };

    recognition.onerror = (e: any) => {
      console.warn("Recognition error:", e);
      setListening(false);
      setLiveTranscript("");
    };

    recognition.onend = () => {
      setListening(false);
    };

    return recognition;
  };

  const toggleMic = () => {
    if (listening) {
      if (recognitionRef.current) {
        try {
          recognitionRef.current.stop();
        } catch (err) {
          // Ignored
        }
      }
      setListening(false);
    } else {
      if (!recognitionRef.current) {
        recognitionRef.current = initRecognition();
      }
      if (!recognitionRef.current) {
        alert(
          "Aapka browser Speech Recognition support nahi karta. Kripya Chrome browser use karein.",
        );
        return;
      }
      try {
        recognitionRef.current.start();
      } catch (e) {
        console.warn("Could not start recognition:", e);
        recognitionRef.current = initRecognition();
        recognitionRef.current?.start();
      }
    }
  };

  const copyMessage = (id: string, text: string) => {
    navigator.clipboard.writeText(text);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const lastAiMessage = messages.filter((m) => m.sender === "ai").slice(-1)[0];

  return (
    <div className="h-screen w-screen flex flex-col justify-between p-2.5 sm:p-4 bg-background text-foreground relative overflow-hidden select-none">
      {/* Background Animated Cyber Mesh */}
      <div className="pointer-events-none absolute inset-0 z-0">
        <div className="absolute top-[-20%] left-[-10%] h-[60vw] w-[60vw] rounded-full bg-emerald-500/10 blur-[120px] animate-pulse" />
        <div
          className="absolute bottom-[-20%] right-[-10%] h-[60vw] w-[60vw] rounded-full bg-cyan-500/10 blur-[120px] animate-pulse"
          style={{ animationDelay: "1.5s" }}
        />
        <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-transparent via-background/40 to-background opacity-80" />
      </div>

      {/* 1. TOP GOD-LEVEL BACK & CYBER HUD BAR */}
      <div className="relative z-10 flex items-center justify-between gap-2 border-b border-border/80 bg-card/80 backdrop-blur-xl rounded-2xl p-2 sm:px-4 shadow-sm shrink-0">
        {/* Top Left Back Button to Return to Home */}
        <Link
          to="/"
          className="press flex items-center gap-1.5 rounded-full border border-emerald-500/40 bg-emerald-500/10 px-3 py-1.5 text-xs font-bold text-emerald-600 dark:text-emerald-300 hover:bg-emerald-500/20 shadow-xs"
        >
          <ArrowLeft className="h-4 w-4" />
          <span>Home</span>
        </Link>

        {/* Center Cyber HUD Status */}
        <div className="flex items-center gap-2">
          <div className="grid h-7 w-7 place-items-center rounded-lg bg-emerald-500/15 border border-emerald-500/30 text-emerald-500">
            <Cpu className="h-4 w-4 animate-pulse" />
          </div>
          <div className="hidden sm:flex flex-col text-left">
            <span className="font-mono text-xs font-bold tracking-tight text-foreground flex items-center gap-1.5">
              NEURO-CORE v2.5
              <span className="h-1.5 w-1.5 rounded-full bg-emerald-400 animate-ping" />
            </span>
            <span className="font-mono text-[9px] text-muted-foreground">
              [LATENCY: {lastLatency || 180}ms] [RATE: 44.1kHz]
            </span>
          </div>
        </div>

        {/* Right Action Controls */}
        <div className="flex items-center gap-1.5">
          {/* Sound Mute/Unmute */}
          <button
            type="button"
            onClick={() => {
              if (soundEnabled) stopAudio();
              setSoundEnabled(!soundEnabled);
            }}
            title={soundEnabled ? "Mute Voice" : "Enable Voice"}
            className={`press grid h-8 w-8 place-items-center rounded-full border text-xs transition-all ${
              soundEnabled
                ? "bg-card border-border text-emerald-500 shadow-xs"
                : "bg-red-500/10 border-red-500/30 text-red-500"
            }`}
          >
            {soundEnabled ? <Volume2 className="h-4 w-4" /> : <VolumeX className="h-4 w-4" />}
          </button>

          {/* Theme Toggle */}
          <button
            type="button"
            onClick={toggleTheme}
            className="press grid h-8 w-8 place-items-center rounded-full border border-border bg-card text-foreground text-xs shadow-xs"
          >
            {theme === "dark" ? "☀️" : "🌙"}
          </button>
        </div>
      </div>

      {/* 2. SUB-BAR: MODE SWITCHER & PERSONALITY PILLS */}
      <div className="relative z-10 flex items-center justify-between gap-2 py-1.5 shrink-0">
        {/* Segmented Mode Switcher */}
        <div className="flex rounded-full bg-muted/80 p-0.5 border border-border/80 text-xs shadow-xs">
          <button
            type="button"
            onClick={() => setViewMode("call")}
            className={`flex items-center gap-1.5 px-3 py-1 rounded-full font-bold transition-all text-xs ${
              viewMode === "call"
                ? "bg-emerald-500 text-white shadow-sm"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            <Radio className="h-3.5 w-3.5" /> Call Mode
          </button>
          <button
            type="button"
            onClick={() => setViewMode("chat")}
            className={`flex items-center gap-1.5 px-3 py-1 rounded-full font-bold transition-all text-xs ${
              viewMode === "chat"
                ? "bg-emerald-500 text-white shadow-sm"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            <Terminal className="h-3.5 w-3.5" /> Terminal
          </button>
        </div>

        {/* Personality Selector */}
        <div className="no-scrollbar flex items-center gap-1.5 overflow-x-auto py-0.5">
          {[
            { id: "warm", label: "💖 Warm Saathi" },
            { id: "cyber", label: "⚡ Cyber AI" },
            { id: "coach", label: "💪 Yoga Coach" },
            { id: "spiritual", label: "🕉️ Guru" },
            { id: "playful", label: "😄 Dost" },
          ].map((p) => (
            <button
              key={p.id}
              type="button"
              onClick={() => setPersonality(p.id as Personality)}
              className={`press whitespace-nowrap px-2.5 py-1 rounded-full text-[11px] font-bold border transition-all ${
                personality === p.id
                  ? "border-emerald-500 bg-emerald-500/20 text-emerald-600 dark:text-emerald-300 shadow-xs"
                  : "border-border/80 bg-card/80 text-muted-foreground hover:text-foreground"
              }`}
            >
              {p.label}
            </button>
          ))}
        </div>
      </div>

      {/* 3. MAIN GOD-LEVEL DISPLAY STAGE */}
      {viewMode === "call" ? (
        <div className="relative z-10 flex-1 flex flex-col items-center justify-between rounded-3xl border border-border/80 bg-card/60 backdrop-blur-2xl p-3 sm:p-5 shadow-2xl overflow-hidden my-1">
          {/* Glowing Animated Radial Canvas Ring */}
          <div className="absolute inset-0 pointer-events-none flex items-center justify-center">
            <div
              className={`h-80 w-80 rounded-full blur-3xl transition-all duration-700 opacity-60 ${
                isSpeaking
                  ? "bg-gradient-to-tr from-cyan-500 via-teal-400 to-emerald-400 scale-125"
                  : listening
                    ? "bg-gradient-to-tr from-emerald-500 via-emerald-400 to-teal-300 scale-150 animate-pulse"
                    : loading
                      ? "bg-gradient-to-tr from-amber-500 to-orange-400 scale-110 animate-spin"
                      : "bg-gradient-to-tr from-emerald-500/20 to-teal-500/20 scale-100"
              }`}
            />
          </div>

          {/* Top Status Badge */}
          <div className="relative z-10">
            <div className="inline-flex items-center gap-2 px-3.5 py-1 rounded-full bg-card/90 border border-emerald-500/30 shadow-md backdrop-blur-md text-xs font-bold">
              <span
                className={`h-2.5 w-2.5 rounded-full ${
                  listening
                    ? "bg-red-500 animate-ping"
                    : isSpeaking
                      ? "bg-emerald-400 animate-pulse"
                      : loading
                        ? "bg-amber-400 animate-spin"
                        : "bg-emerald-500"
                }`}
              />
              <span className="text-foreground text-xs font-mono">
                {listening
                  ? "LISTENING_MIC_ACTIVE..."
                  : loading
                    ? "NEURAL_PROCESSING..."
                    : isSpeaking
                      ? "VOICE_SYNTH_PLAYBACK..."
                      : "TAP MIC TO TRANSMIT"}
              </span>
            </div>
          </div>

          {/* Centerpiece Cyber 3D Orb Visualizer */}
          <div className="relative z-10 flex flex-col items-center justify-center my-auto">
            <div
              className={`relative grid h-44 w-44 sm:h-56 sm:w-56 place-items-center rounded-full border-2 transition-all duration-500 ${
                listening
                  ? "border-emerald-400 bg-gradient-to-tr from-emerald-600/30 via-teal-500/30 to-emerald-400/20 shadow-[0_0_60px_rgba(16,185,129,0.5)] scale-105"
                  : isSpeaking
                    ? "border-cyan-400 bg-gradient-to-tr from-teal-600/30 via-cyan-500/30 to-emerald-500/20 shadow-[0_0_60px_rgba(6,182,212,0.5)] scale-105"
                    : loading
                      ? "border-amber-400 bg-gradient-to-tr from-amber-500/20 to-emerald-500/20 shadow-[0_0_40px_rgba(245,158,11,0.4)]"
                      : "border-emerald-500/40 bg-gradient-to-tr from-emerald-500/10 via-teal-500/10 to-emerald-600/10 shadow-xl hover:border-emerald-500/70"
              }`}
            >
              {/* Outer Cyber Radar Concentric Ring */}
              <div className="absolute inset-2 rounded-full border border-dashed border-emerald-500/30 animate-spin-slow pointer-events-none" />

              {/* Dynamic Equalizer Spectrum Bars */}
              <div className="flex items-center gap-1.5 h-14">
                {[0.4, 0.9, 1.4, 0.7, 1.6, 1.1, 0.5, 1.3, 0.8, 1.5, 0.6, 1.0].map((factor, i) => (
                  <div
                    key={i}
                    className={`w-1.5 rounded-full transition-all duration-150 ${
                      listening
                        ? "bg-emerald-400 animate-pulse"
                        : isSpeaking
                          ? "bg-gradient-to-t from-emerald-400 via-teal-300 to-cyan-400 animate-bounce"
                          : "bg-emerald-500/40 h-2.5"
                    }`}
                    style={{
                      height:
                        listening || isSpeaking
                          ? `${Math.max(10, Math.min(52, factor * (isSpeaking ? 32 : 40)))}px`
                          : "8px",
                      animationDelay: `${i * 70}ms`,
                    }}
                  />
                ))}
              </div>

              {/* Orb Center Cyber Badge */}
              <div className="absolute bottom-3 text-center">
                <span className="text-[9px] font-mono font-bold uppercase tracking-widest text-emerald-600 dark:text-emerald-300 bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/20">
                  {isSpeaking ? "SYNTH" : listening ? "MIC_ON" : "READY"}
                </span>
              </div>
            </div>

            {/* Live Subtitle HUD Window */}
            <div className="mt-4 w-full max-w-lg px-2 text-center">
              {liveTranscript ? (
                <div className="rounded-2xl border border-emerald-500/40 bg-card/90 p-3 shadow-lg backdrop-blur-md">
                  <p className="text-[10px] text-emerald-600 dark:text-emerald-400 font-mono font-bold mb-0.5">
                    &gt; USER TRANSMISSION:
                  </p>
                  <p className="text-xs sm:text-sm font-semibold text-foreground italic">
                    "{liveTranscript}"
                  </p>
                </div>
              ) : lastAiMessage ? (
                <div className="rounded-2xl border border-border/80 bg-card/90 p-3.5 shadow-lg backdrop-blur-md">
                  <p className="text-[10px] text-muted-foreground font-mono font-bold mb-1 flex items-center justify-center gap-1">
                    <Sparkles className="h-3 w-3 text-emerald-500" /> &gt; AI RESPONSE FEED:
                  </p>
                  <p className="text-xs sm:text-sm text-foreground leading-relaxed font-semibold">
                    {lastAiMessage.text}
                  </p>
                  <button
                    type="button"
                    onClick={() => speakVoiceInstant(lastAiMessage.text)}
                    className="mt-2 inline-flex items-center gap-1 text-[10px] text-emerald-600 dark:text-emerald-400 font-bold hover:underline bg-emerald-500/10 px-2.5 py-0.5 rounded-full border border-emerald-500/20"
                  >
                    <Volume2 className="h-3 w-3" /> Dobara Sunein
                  </button>
                </div>
              ) : null}
            </div>
          </div>

          {/* Quick Prompt Pills Bar */}
          <div className="w-full relative z-10 my-1">
            <div className="no-scrollbar flex gap-2 overflow-x-auto py-1 px-1">
              {QUICK_PROMPTS.map((qp, idx) => (
                <button
                  key={idx}
                  type="button"
                  onClick={() => handleSendMessage(qp.text)}
                  disabled={loading || listening}
                  className="press whitespace-nowrap text-xs font-bold px-3 py-1.5 rounded-full border border-border bg-card/90 text-foreground hover:border-emerald-500/50 transition-all disabled:opacity-50 shrink-0 shadow-xs"
                >
                  {qp.label}
                </button>
              ))}
            </div>
          </div>

          {/* Centerpiece Floating Cyber Mic Trigger */}
          <div className="relative z-10 flex items-center justify-center gap-4 pt-1">
            {isSpeaking && (
              <button
                type="button"
                onClick={stopAudio}
                className="press h-12 w-12 rounded-full border border-red-500/40 bg-red-500/15 text-red-500 grid place-items-center shadow-lg"
                title="Stop Audio"
              >
                <VolumeX className="h-5 w-5" />
              </button>
            )}

            <button
              type="button"
              onClick={toggleMic}
              disabled={loading}
              className={`press relative grid h-16 w-16 sm:h-20 sm:w-20 place-items-center rounded-full text-white dark:text-black font-bold shadow-2xl transition-all duration-300 ${
                listening
                  ? "bg-gradient-to-r from-red-500 to-rose-600 scale-110 ring-8 ring-red-500/30 text-white"
                  : loading
                    ? "bg-muted text-muted-foreground"
                    : "bg-gradient-to-tr from-emerald-500 via-teal-500 to-emerald-400 ring-8 ring-emerald-500/20 hover:scale-105 shadow-[0_0_35px_rgba(16,185,129,0.5)]"
              }`}
            >
              {loading ? (
                <Loader2 className="h-7 w-7 animate-spin text-white dark:text-black" />
              ) : listening ? (
                <MicOff className="h-7 w-7" />
              ) : (
                <Mic className="h-7 w-7" />
              )}
            </button>
          </div>
        </div>
      ) : (
        /* TERMINAL CHAT STREAM VIEW */
        <div className="relative z-10 flex-1 flex flex-col min-h-0 rounded-3xl border border-border/80 bg-card/60 backdrop-blur-2xl p-3 shadow-2xl overflow-hidden my-1">
          <div className="flex-1 overflow-y-auto no-scrollbar space-y-3 pr-1">
            {messages.map((msg) => {
              const isUser = msg.sender === "user";
              return (
                <div
                  key={msg.id}
                  className={`flex items-start gap-2.5 ${isUser ? "justify-end" : "justify-start"}`}
                >
                  {!isUser && (
                    <div className="grid h-7 w-7 shrink-0 place-items-center rounded-xl bg-gradient-to-tr from-emerald-500 to-teal-600 text-white font-bold text-xs shadow-xs mt-1">
                      <Bot className="h-4 w-4" />
                    </div>
                  )}

                  <div
                    className={`group relative max-w-[85%] sm:max-w-[75%] rounded-2xl p-3 text-xs sm:text-sm shadow-xs transition-all ${
                      isUser
                        ? "bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-tr-sm font-semibold"
                        : "border border-border bg-card text-foreground rounded-tl-sm font-medium"
                    }`}
                  >
                    <p className="leading-relaxed whitespace-pre-wrap">{msg.text}</p>

                    <div className="flex items-center justify-between gap-4 mt-1.5 pt-1 border-t border-border/40 text-[10px] text-muted-foreground">
                      <span className="flex items-center gap-1 font-mono">
                        {msg.timestamp}
                        {msg.latencyMs && (
                          <span className="text-emerald-500 font-bold">· {msg.latencyMs}ms</span>
                        )}
                      </span>

                      <div className="flex items-center gap-1 opacity-90 group-hover:opacity-100 transition-opacity">
                        {!isUser && (
                          <button
                            type="button"
                            onClick={() => speakVoiceInstant(msg.text)}
                            className="p-1 rounded-lg hover:bg-muted text-emerald-500"
                            title="Speak Message"
                          >
                            <Volume2 className="h-3.5 w-3.5" />
                          </button>
                        )}
                        <button
                          type="button"
                          onClick={() => copyMessage(msg.id, msg.text)}
                          className="p-1 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground"
                          title="Copy text"
                        >
                          {copiedId === msg.id ? (
                            <Check className="h-3.5 w-3.5 text-emerald-500" />
                          ) : (
                            <Copy className="h-3.5 w-3.5" />
                          )}
                        </button>
                      </div>
                    </div>
                  </div>

                  {isUser && (
                    <div className="grid h-7 w-7 shrink-0 place-items-center rounded-xl bg-muted text-foreground text-xs font-bold mt-1 border border-border">
                      <UserIcon className="h-4 w-4" />
                    </div>
                  )}
                </div>
              );
            })}
            {loading && (
              <div className="flex items-start gap-2.5">
                <div className="grid h-7 w-7 shrink-0 place-items-center rounded-xl bg-gradient-to-tr from-emerald-500 to-teal-600 text-white mt-1 shadow-xs">
                  <Bot className="h-4 w-4" />
                </div>
                <div className="rounded-xl border border-border bg-card px-3 py-2 text-xs text-foreground flex items-center gap-2 shadow-xs">
                  <Loader2 className="h-3.5 w-3.5 animate-spin text-emerald-500" />
                  <span className="font-mono text-xs">NEURAL_PROCESSING...</span>
                </div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* Quick Prompts */}
          <div className="py-1.5 no-scrollbar flex gap-2 overflow-x-auto shrink-0 border-t border-border/60">
            {QUICK_PROMPTS.map((qp, idx) => (
              <button
                key={idx}
                type="button"
                onClick={() => handleSendMessage(qp.text)}
                disabled={loading}
                className="press text-[11px] font-bold px-2.5 py-1 rounded-full border border-border bg-card text-foreground hover:border-emerald-500/50 whitespace-nowrap shrink-0 shadow-xs"
              >
                {qp.label}
              </button>
            ))}
          </div>

          {/* Terminal Input */}
          <form
            onSubmit={(e) => {
              e.preventDefault();
              handleSendMessage(inputText);
            }}
            className="flex items-center gap-1.5 pt-1 shrink-0"
          >
            <button
              type="button"
              onClick={toggleMic}
              disabled={loading}
              className={`press grid h-10 w-10 shrink-0 place-items-center rounded-xl border transition-all ${
                listening
                  ? "bg-red-500 text-white border-red-400 animate-pulse ring-2 ring-red-500/30"
                  : "bg-card border-border text-emerald-500 hover:border-emerald-500/40 shadow-xs"
              }`}
            >
              {listening ? <MicOff className="h-4 w-4" /> : <Mic className="h-4 w-4" />}
            </button>

            <input
              type="text"
              value={inputText}
              onChange={(e) => setInputText(e.target.value)}
              placeholder={`Boliye ${profile.name || "Dost"} ji...`}
              className="flex-1 rounded-xl border border-border bg-card/90 px-3 py-2 text-xs sm:text-sm font-semibold text-foreground placeholder:text-muted-foreground focus:border-emerald-500 focus:outline-none shadow-xs"
            />

            <button
              type="submit"
              disabled={!inputText.trim() || loading}
              className="press grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-gradient-to-r from-emerald-500 to-teal-600 text-white font-bold shadow-md hover:brightness-110 disabled:opacity-40"
            >
              <Send className="h-4 w-4" />
            </button>
          </form>
        </div>
      )}

      {/* 4. FOOTER SAFETY BADGE */}
      <div className="relative z-10 flex items-center justify-between text-[10px] text-muted-foreground font-mono pt-1 shrink-0">
        <span className="flex items-center gap-1">
          <ShieldAlert className="h-3 w-3 text-emerald-500" /> PRIVACY & SECURE VOICE ENCRYPTION
        </span>
        <span className="hidden sm:inline">PROUDLY BUILT FOR SENIORS & WELLNESS</span>
      </div>
    </div>
  );
}
