'use client';

import React, { useEffect, useState, useRef } from 'react';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/auth-context';
import {
  Send,
  MessageSquare,
  RefreshCw,
  Terminal,
  ShoppingBag,
  Trash2,
  ExternalLink,
  Search,
  ShoppingCart,
  Star,
  ArrowLeft,
  X,
  ChevronRight,
} from 'lucide-react';

interface ChatMessage {
  id: string;
  direction: 'inbound' | 'outbound';
  messageBody: string;
  createdAt: string;
  rawPayloadJson?: string | null;
}

interface CartItem {
  id: string;
  quantity: number;
  unitPrice: number;
  lineTotal: number;
  product: {
    name: string;
  };
}

interface CartState {
  id: string;
  totalAmount: number;
  items: CartItem[];
}

export default function SimulatorPage() {
  const { user } = useAuth();
  const [phone, setPhone] = useState('+263779998887');
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [sessionState, setSessionState] = useState<Record<string, any>>({});
  const [sending, setSending] = useState(false);
  const [activeSimTab, setActiveSimTab] = useState<'chat' | 'inspector'>('chat');
  const chatEndRef = useRef<HTMLDivElement>(null);
  const [qtySelectProduct, setQtySelectProduct] = useState<{ name: string; price: number; imageUrl?: string } | null>(null);
  const [qtyValue, setQtyValue] = useState(1);

  useEffect(() => {
    if (user?.phone) {
      setPhone(user.phone);
    }
  }, [user]);

  useEffect(() => {
    if (user) {
      loadChatHistory();
      loadSessionState();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user, phone]);

  useEffect(() => {
    // Scroll to bottom of chat
    chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const loadChatHistory = async () => {
    try {
      const data = await apiRequest(`api/whatsapp/logs?phone=${encodeURIComponent(phone)}`);
      setMessages(data);
    } catch (err) {
      console.error('Failed to load chat logs:', err);
    }
  };

  const loadSessionState = async () => {
    try {
      const sessions = await apiRequest('api/whatsapp/sessions');
      const activeSession = sessions.find((s: any) => s.whatsappNumber === phone);
      if (activeSession) {
        setSessionState({
          currentStep: activeSession.currentStep,
          data: JSON.parse(activeSession.sessionDataJson),
          expiresAt: activeSession.expiresAt,
        });
      } else {
        setSessionState({ currentStep: 'WELCOME', data: {} });
      }
    } catch (err) {
      console.error('Failed to load session state:', err);
    }
  };

  const sendSimulatedInput = async (input: string) => {
    if (!user || sending) return;
    setSending(true);

    // Append user message locally immediately for instant feedback
    const tempId = `temp-${Date.now()}`;
    setMessages((prev) => [
      ...prev,
      {
        id: tempId,
        direction: 'inbound',
        messageBody: input,
        createdAt: new Date().toISOString(),
      },
    ]);

    try {
      const res = await apiRequest('webhooks/whatsapp/simulate', 'POST', {
        businessId: user.id,
        whatsappNumber: phone,
        message: input,
      });

      // Reload chat history to get persistent DB logs and correct order
      await loadChatHistory();
      
      if (res.sessionState) {
        setSessionState(res.sessionState);
      }
    } catch (err: any) {
      alert(`Simulation error: ${err.message}`);
    } finally {
      setSending(false);
    }
  };

  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!message.trim() || !user || sending) return;

    const userMsg = message;
    setMessage('');
    await sendSimulatedInput(userMsg);
  };

  const handleResetSession = async () => {
    if (!user) return;
    try {
      await apiRequest('api/whatsapp/sessions/reset', 'POST', {
        whatsappNumber: phone,
      });
      setSessionState({ currentStep: 'WELCOME', data: {} });
      // Send a dummy welcome trigger to re-initialize
      const res = await apiRequest('webhooks/whatsapp/simulate', 'POST', {
        businessId: user.id,
        whatsappNumber: phone,
        message: 'reset',
      });
      await loadChatHistory();
      if (res.sessionState) {
        setSessionState(res.sessionState);
      }
      alert('Session reset back to Welcome menu!');
    } catch (err: any) {
      alert(`Reset error: ${err.message}`);
    }
  };

  return (
    <div className="space-y-6 font-sans h-[calc(100vh-140px)] flex flex-col overflow-hidden">
      <div className="shrink-0">
        <h1 className="text-3xl font-extrabold tracking-tight text-white Outfit">
          WhatsApp Bot Simulator
        </h1>
        <p className="text-sm text-gray-400 mt-1">
          Chat with your shopping assistant and inspect session variables in real-time
        </p>
      </div>

      {/* Mobile Tab Toggle */}
      <div className="flex border-b border-white/5 gap-6 lg:hidden shrink-0">
        <button
          onClick={() => setActiveSimTab('chat')}
          className={`pb-2.5 font-semibold text-xs transition-all relative cursor-pointer ${
            activeSimTab === 'chat' ? 'text-emerald-400 font-bold' : 'text-gray-400 hover:text-gray-200'
          }`}
        >
          <span>Chat Simulator</span>
          {activeSimTab === 'chat' && (
            <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-emerald-400 rounded-full" />
          )}
        </button>
        <button
          onClick={() => setActiveSimTab('inspector')}
          className={`pb-2.5 font-semibold text-xs transition-all relative cursor-pointer ${
            activeSimTab === 'inspector' ? 'text-emerald-400 font-bold' : 'text-gray-400 hover:text-gray-200'
          }`}
        >
          <span>Session Inspector</span>
          {activeSimTab === 'inspector' && (
            <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-emerald-400 rounded-full" />
          )}
        </button>
      </div>

      <div className="flex-1 grid grid-cols-1 lg:grid-cols-12 gap-8 overflow-hidden items-stretch">
        {/* Phone Config & Simulator Column */}
        {/* Phone Config & Simulator Column */}
        <div className={`lg:col-span-7 flex flex-col glass-panel rounded-2xl p-6 border border-slate-200 dark:border-white/5 bg-white dark:bg-[#0e0f14]/80 relative overflow-hidden ${
          activeSimTab === 'chat' ? 'flex' : 'hidden lg:flex'
        }`}>
          {/* Simulator Config Toolbar */}
          <div className="flex items-center justify-between border-b border-white/5 pb-4 mb-4 shrink-0">
            <div className="flex items-center gap-2">
              <div className="w-2 h-2 rounded-full bg-emerald-500" />
              <span className="text-xs font-semibold text-gray-300">Device Simulator Workspace</span>
            </div>
            {/* Phone select input */}
            <div className="flex items-center gap-2">
              <span className="text-[10px] font-bold text-gray-500 uppercase tracking-wider">Test Number:</span>
              <input
                type="text"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                className="bg-black/40 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white font-mono outline-none focus:border-emerald-500/50 w-36 text-center shadow-inner"
              />
            </div>
          </div>

          {/* Centered Phone Chassis */}
          <div className="flex-1 flex items-center justify-center p-2 min-h-0">
            <div className="w-full max-w-[340px] h-[550px] border-[10px] border-[#1d1f27] rounded-[36px] bg-[var(--outer-bg)] flex flex-col overflow-hidden relative shadow-[0_20px_40px_-15px_rgba(0,0,0,0.8)] outline outline-1 outline-white/5 select-none shrink-0">
              {/* Notch */}
              <div className="absolute top-1.5 left-1/2 -translate-x-1/2 w-24 h-3.5 bg-[#1d1f27] rounded-full z-30 flex items-center justify-center">
                <div className="w-1.5 h-1.5 rounded-full bg-[#111318]" />
              </div>

              {/* Internal Display */}
              <div className="flex-1 flex flex-col h-full overflow-hidden pt-3 bg-[var(--outer-bg)] relative">
                {/* Phone Status Bar */}
                <div className="flex justify-between items-center text-[8px] text-gray-500 font-mono tracking-tight px-6 py-0.5 select-none shrink-0">
                  <span>9:41 AM</span>
                  <div className="flex items-center gap-1">
                    <span>LTE</span>
                    <span>88%</span>
                  </div>
                </div>

                {/* Chat App Header inside display */}
                <div className="bg-[var(--surface-bright)]/95 px-4 py-2 flex items-center justify-between border-b border-white/5 relative z-20 backdrop-blur-md shrink-0 font-sans">
                  <div className="flex items-center gap-2.5">
                    <div className="h-7 w-7 rounded-full bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center font-bold text-white text-xs">
                      <ShoppingBag className="h-4 w-4 text-emerald-400" />
                    </div>
                    <div>
                      <h3 className="font-extrabold text-white text-[11px] leading-none">Shopping Bot</h3>
                      <span className="text-[8px] text-emerald-400 flex items-center gap-1 mt-0.5 font-medium">
                        <span className="h-1 w-1 rounded-full bg-emerald-400"></span>
                        Online
                      </span>
                    </div>
                  </div>
                </div>

                {/* Chat Messages Log */}
                <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-[var(--bg-color)] relative scrollbar-thin">
                  {/* WhatsApp chat background pattern simulation */}
                  <div className="absolute inset-0 bg-cover opacity-[0.08] pointer-events-none" style={{ backgroundImage: `url('/whats%20backgroud.jpg')` }}></div>
                  
                  {messages.length === 0 ? (
                    <div className="h-full flex flex-col items-center justify-center text-center text-gray-500 space-y-3 relative z-10 p-4">
                      <p className="text-[11px] max-w-xs leading-relaxed">
                        No chat history for this number yet. Type *&quot;hello&quot;* or *&quot;menu&quot;* in the input below to trigger the greeting menu!
                      </p>
                    </div>
                  ) : (
                    <div className="space-y-3 relative z-10">
                      {messages.map((msg) => {
                        const isBot = msg.direction === 'outbound';
                        
                        // Parse payload if it exists
                        let payload: any = null;
                        if (msg.rawPayloadJson) {
                          try {
                            payload = JSON.parse(msg.rawPayloadJson);
                          } catch (err) {
                            console.error("Payload parse error:", err);
                          }
                        }

                        // Function to render payload components
                        const renderPayload = () => {
                          if (!payload || !payload.type) return null;

                          switch (payload.type) {
                            case 'button_grid':
                              return (
                                <div className="grid grid-cols-2 gap-2 mt-2.5">
                                  {payload.buttons?.map((btn: any) => {
                                    const getIcon = () => {
                                      const iconName = (btn.icon || '').toLowerCase();
                                      const titleLower = (btn.title || '').toLowerCase();

                                      if (iconName.includes('box') || titleLower.includes('shop')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" className="h-4.5 w-4.5">
                                            <rect x="8" y="16" width="34" height="26" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <line x1="8" y1="22" x2="42" y2="22" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="21" y="10" width="8" height="20" fill="#dedcd1" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="13" y="28" width="6" height="5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="miter" strokeLinecap="square" />
                                          </svg>
                                        );
                                      }
                                      if (iconName.includes('list') || titleLower.includes('search')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" className="h-4.5 w-4.5">
                                            <rect x="8" y="12" width="8" height="8" fill="#dedcd1" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <line x1="22" y1="16" x2="42" y2="16" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="8" y="24" width="8" height="8" fill="none" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <line x1="22" y1="28" x2="42" y2="28" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="8" y="36" width="8" height="8" fill="none" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <line x1="22" y1="40" x2="42" y2="40" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                          </svg>
                                        );
                                      }
                                      if (iconName.includes('cart') || titleLower.includes('cart') || titleLower.includes('checkout')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className="h-4.5 w-4.5" fill="currentColor">
                                            <path d="M89,35.477H76.193V22.723C76.193,15.707,70.486,10,63.471,10H36.529c-7.015,0-12.723,5.707-12.723,12.723v12.754H11 c-0.552,0-1,0.447-1,1c0,0.553,0.448,1,1,1h2.334l6.041,51.64C19.434,89.62,19.861,90,20.368,90h60.18 c0.514,0,0.944-0.39,0.995-0.901l5.134-51.622H89c0.552,0,1-0.447,1-1C90,35.924,89.552,35.477,89,35.477z M25.807,22.723 C25.807,16.81,30.617,12,36.529,12h26.941c5.913,0,10.723,4.81,10.723,10.723v12.754H25.807V22.723z M40.058,61.887v-24.41H61.01 v24.41H40.058z M61.01,63.887V88H40.058V63.887H61.01z M38.058,37.477v24.41H18.203l-2.855-24.41H38.058z M18.437,63.887h19.62V88 h-16.8L18.437,63.887z M79.643,88H63.01V63.887h19.031L79.643,88z M82.24,61.887H63.01v-24.41h21.658L82.24,61.887z" />
                                          </svg>
                                        );
                                      }
                                      if (iconName.includes('user') || iconName.includes('customer') || titleLower.includes('support')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" className="h-4.5 w-4.5">
                                            <circle cx="25" cy="18" r="8" fill="#dedcd1" stroke="currentColor" strokeWidth="2.5" />
                                            <path d="M9 40c0-6 6-10 16-10s16 4 16 10" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                          </svg>
                                        );
                                      }
                                      if (iconName.includes('settings') || titleLower.includes('store') || titleLower.includes('change')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" className="h-4.5 w-4.5">
                                            <path d="M 27.5 2 C 27.039063 2 26.644531 2.304688 26.53125 2.75 L 26.125 4.4375 C 24.648438 4.882813 23.285156 5.65625 22.15625 6.71875 L 20.5 6.25 C 20.058594 6.125 19.574219 6.289063 19.34375 6.6875 L 17.84375 9.3125 C 17.613281 9.710938 17.703125 10.210938 18.03125 10.53125 L 19.25 11.71875 C 19.074219 12.464844 19 13.226563 19 14 C 19 14.773438 19.074219 15.535156 19.25 16.28125 L 18.03125 17.46875 C 17.703125 17.789063 17.613281 18.289063 17.84375 18.6875 L 19.34375 21.3125 C 19.574219 21.710938 20.058594 21.871094 20.5 21.75 L 22.15625 21.28125 C 23.285156 22.34375 24.648438 23.117188 26.125 23.5625 L 26.53125 25.25 C 26.640625 25.695313 27.039063 26 27.5 26 L 30.5 26 C 30.960938 26 31.355469 25.695313 31.46875 25.25 L 31.875 23.5625 C 33.351563 23.117188 34.714844 22.34375 35.84375 21.28125 L 37.5 21.75 C 37.9375 21.878906 38.425781 21.710938 38.65625 21.3125 L 40.15625 18.6875 C 40.386719 18.289063 40.296875 17.789063 39.96875 17.46875 L 38.75 16.28125 C 38.925781 15.53125 39 14.773438 39 14 C 39 13.226563 38.925781 12.46875 38.75 11.71875 L 39.96875 10.53125 C 40.296875 10.210938 40.386719 9.710938 40.15625 9.3125 L 38.65625 6.6875 C 38.425781 6.289063 37.9375 6.125 37.5 6.25 L 35.84375 6.71875 C 34.714844 5.65625 33.351563 4.882813 31.875 4.4375 L 31.46875 2.75 C 31.355469 2.304688 30.960938 2 30.5 2 Z M 29 11 C 30.667969 11 32 12.332031 32 14 C 32 15.667969 30.667969 17 29 17 C 27.332031 17 26 15.667969 26 14 C 26 12.332031 27.332031 11 29 11 Z M 11.5 20 C 11.039063 20 10.644531 20.304688 10.53125 20.75 L 10.125 22.4375 C 8.648438 22.882813 7.285156 23.65625 6.15625 24.71875 L 4.5 24.25 C 4.058594 24.125 3.574219 24.289063 3.34375 24.6875 L 1.84375 27.3125 C 1.613281 27.710938 1.703125 28.210938 2.03125 28.53125 L 3.25 29.71875 C 3.074219 30.464844 3 31.226563 3 32 C 3 32.773438 3.074219 33.535156 3.25 34.28125 L 2.03125 35.46875 C 1.703125 35.789063 1.613281 36.289063 1.84375 36.6875 L 3.34375 39.3125 C 3.574219 39.710938 4.058594 39.871094 4.5 39.75 L 6.15625 39.28125 C 7.285156 40.34375 8.648438 41.117188 10.125 41.5625 L 10.53125 43.25 C 10.640625 43.695313 11.039063 44 11.5 44 L 14.5 44 C 14.960938 44 15.355469 43.695313 15.46875 43.25 L 15.875 41.5625 C 17.351563 41.117188 18.714844 40.34375 19.84375 39.28125 L 21.5 39.75 C 21.9375 39.878906 22.425781 39.710938 22.65625 39.3125 L 24.15625 36.6875 C 24.386719 36.289063 24.296875 35.789063 23.96875 35.46875 L 22.75 34.28125 C 22.925781 33.53125 23 32.773438 23 32 C 23 31.226563 22.925781 30.46875 22.75 29.71875 L 23.96875 28.53125 C 24.296875 28.210938 24.386719 27.710938 24.15625 27.3125 L 22.65625 24.6875 C 22.425781 24.289063 21.9375 24.125 21.5 24.25 L 19.84375 24.71875 C 18.714844 23.65625 17.351563 22.882813 15.875 22.4375 L 15.46875 20.75 C 15.359375 20.304688 14.960938 20 14.5 20 Z M 34.5 25 C 34.039063 25 33.644531 25.304688 33.53125 25.75 L 33.125 27.4375 C 31.648438 27.882813 30.285156 28.65625 29.15625 29.71875 L 27.5 29.25 C 27.058594 29.125 26.574219 29.289063 26.34375 29.6875 L 24.84375 32.3125 C 24.613281 32.710938 24.703125 33.210938 25.03125 33.53125 L 26.25 34.71875 C 26.074219 35.464844 26 36.226563 26 37 C 26 37.773438 26.074219 38.535156 26.25 39.28125 L 25.03125 40.46875 C 24.703125 40.789063 24.613281 41.289063 24.84375 41.6875 L 26.34375 44.3125 C 26.574219 44.710938 27.058594 44.871094 27.5 44.75 L 29.15625 44.28125 C 30.285156 45.34375 31.648438 46.117188 33.125 46.5625 L 33.53125 48.25 C 33.640625 48.695313 34.039063 49 34.5 49 L 37.5 49 C 37.960938 49 38.355469 48.695313 38.46875 48.25 L 38.875 46.5625 C 40.351563 46.117188 41.714844 45.34375 42.84375 44.28125 L 44.5 44.75 C 44.9375 44.878906 45.425781 44.710938 45.65625 44.3125 L 47.15625 41.6875 C 47.386719 41.289063 47.296875 40.789063 46.96875 40.46875 L 45.75 39.28125 C 45.925781 38.53125 46 37.773438 46 37 C 46 36.226563 45.925781 35.46875 45.75 34.71875 L 46.96875 33.53125 C 47.296875 33.210938 47.386719 32.710938 47.15625 32.3125 L 45.65625 29.6875 C 45.425781 29.289063 44.9375 29.125 44.5 29.25 L 42.84375 29.71875 C 41.714844 28.65625 40.351563 27.882813 38.875 27.4375 L 38.46875 25.75 C 38.359375 25.304688 37.960938 25 37.5 25 Z M 13 29 C 14.667969 29 16 30.332031 16 32 C 16 33.667969 14.667969 35 13 35 C 11.332031 35 10 33.667969 10 32 C 10 30.332031 11.332031 29 13 29 Z M 36 33 C 38.210938 33 40 34.789063 40 37 C 40 39.210938 38.210938 41 36 41 C 33.789063 41 32 39.210938 32 37 C 32 34.789063 33.789063 33 36 33 Z" />
                                          </svg>
                                        );
                                      }

                                      // Default Lucide mapping fallback
                                      switch (btn.icon) {
                                        case 'shopping-bag': return <ShoppingBag className="h-4 w-4" />;
                                        case 'search': return <Search className="h-4 w-4" />;
                                        case 'shopping-cart': return <ShoppingCart className="h-4 w-4" />;
                                        case 'message-square': return <MessageSquare className="h-4 w-4" />;
                                        default: return <span className="text-sm leading-none">{btn.icon}</span>;
                                      }
                                    };
                                    const getColorClasses = () => {
                                      switch (btn.color) {
                                        case 'emerald': return 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20 hover:bg-emerald-500/15';
                                        case 'cyan': return 'bg-cyan-500/10 text-cyan-400 border-cyan-500/20 hover:bg-cyan-500/15';
                                        case 'amber': return 'bg-amber-500/10 text-amber-400 border-amber-500/20 hover:bg-amber-500/15';
                                        case 'purple': return 'bg-purple-500/10 text-purple-400 border-purple-500/20 hover:bg-purple-500/15';
                                        default: return 'bg-white/5 text-white border-white/10 hover:bg-white/10';
                                      }
                                    };
                                    return (
                                      <button
                                        key={btn.id}
                                        onClick={() => sendSimulatedInput(btn.id)}
                                        className={`flex flex-col items-center justify-center p-3 rounded-xl border text-center transition-all duration-200 cursor-pointer ${getColorClasses()}`}
                                      >
                                        <div className="p-2 rounded-full bg-black/20 mb-1.5">
                                          {getIcon()}
                                        </div>
                                        <span className="font-extrabold text-[9px] uppercase tracking-wider">{btn.title}</span>
                                      </button>
                                    );
                                  })}
                                </div>
                              );

                            case 'pills':
                              return (
                                <div className="flex flex-wrap gap-1.5 mt-2.5">
                                  {payload.options?.map((opt: any) => {
                                    const getPillIcon = () => {
                                      const iconName = (opt.icon || '').toLowerCase();
                                      const titleLower = (opt.title || '').toLowerCase();

                                      // 1. Explicit icon property matching
                                      if (iconName.includes('cart') || iconName.includes('checkout')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className="h-3.5 w-3.5 text-emerald-400" fill="currentColor">
                                            <path d="M89,35.477H76.193V22.723C76.193,15.707,70.486,10,63.471,10H36.529c-7.015,0-12.723,5.707-12.723,12.723v12.754H11 c-0.552,0-1,0.447-1,1c0,0.553,0.448,1,1,1h2.334l6.041,51.64C19.434,89.62,19.861,90,20.368,90h60.18 c0.514,0,0.944-0.39,0.995-0.901l5.134-51.622H89c0.552,0,1-0.447,1-1C90,35.924,89.552,35.477,89,35.477z M25.807,22.723 C25.807,16.81,30.617,12,36.529,12h26.941c5.913,0,10.723,4.81,10.723,10.723v12.754H25.807V22.723z M40.058,61.887v-24.41H61.01 v24.41H40.058z M61.01,63.887V88H40.058V63.887H61.01z M38.058,37.477v24.41H18.203l-2.855-24.41H38.058z M18.437,63.887h19.62V88 h-16.8L18.437,63.887z M79.643,88H63.01V63.887h19.031L79.643,88z M82.24,61.887H63.01v-24.41h21.658L82.24,61.887z" />
                                          </svg>
                                        );
                                      }
                                      if (iconName.includes('box') || iconName.includes('delivery')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" className="h-3.5 w-3.5 text-emerald-400">
                                            <rect x="8" y="16" width="34" height="26" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <line x1="8" y1="22" x2="42" y2="22" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="21" y="10" width="8" height="20" fill="#dedcd1" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="13" y="28" width="6" height="5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="miter" strokeLinecap="square" />
                                          </svg>
                                        );
                                      }
                                      if (iconName.includes('list') || iconName.includes('menu')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" className="h-3.5 w-3.5 text-emerald-400">
                                            <rect x="8" y="12" width="8" height="8" fill="#dedcd1" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <line x1="22" y1="16" x2="42" y2="16" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="8" y="24" width="8" height="8" fill="none" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <line x1="22" y1="28" x2="42" y2="28" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="8" y="36" width="8" height="8" fill="none" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <line x1="22" y1="40" x2="42" y2="40" stroke="currentColor" stroke-width="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                          </svg>
                                        );
                                      }
                                      if (iconName.includes('settings') || iconName.includes('pickup')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" className="h-3.5 w-3.5 text-emerald-400">
                                            <path d="M 27.5 2 C 27.039063 2 26.644531 2.304688 26.53125 2.75 L 26.125 4.4375 C 24.648438 4.882813 23.285156 5.65625 22.15625 6.71875 L 20.5 6.25 C 20.058594 6.125 19.574219 6.289063 19.34375 6.6875 L 17.84375 9.3125 C 17.613281 9.710938 17.703125 10.210938 18.03125 10.53125 L 19.25 11.71875 C 19.074219 12.464844 19 13.226563 19 14 C 19 14.773438 19.074219 15.535156 19.25 16.28125 L 18.03125 17.46875 C 17.703125 17.789063 17.613281 18.289063 17.84375 18.6875 L 19.34375 21.3125 C 19.574219 21.710938 20.058594 21.871094 20.5 21.75 L 22.15625 21.28125 C 23.285156 22.34375 24.648438 23.117188 26.125 23.5625 L 26.53125 25.25 C 26.640625 25.695313 27.039063 26 27.5 26 L 30.5 26 C 30.960938 26 31.355469 25.695313 31.46875 25.25 L 31.875 23.5625 C 33.351563 23.117188 34.714844 22.34375 35.84375 21.28125 L 37.5 21.75 C 37.9375 21.878906 38.425781 21.710938 38.65625 21.3125 L 40.15625 18.6875 C 40.386719 18.289063 40.296875 17.789063 39.96875 17.46875 L 38.75 16.28125 C 38.925781 15.53125 39 14.773438 39 14 C 39 13.226563 38.925781 12.46875 38.75 11.71875 L 39.96875 10.53125 C 40.296875 10.210938 40.386719 9.710938 40.15625 9.3125 L 38.65625 6.6875 C 38.425781 6.289063 37.9375 6.125 37.5 6.25 L 35.84375 6.71875 C 34.714844 5.65625 33.351563 4.882813 31.875 4.4375 L 31.46875 2.75 C 31.355469 2.304688 30.960938 2 30.5 2 Z M 29 11 C 30.667969 11 32 12.332031 32 14 C 32 15.667969 30.667969 17 29 17 C 27.332031 17 26 15.667969 26 14 C 26 12.332031 27.332031 11 29 11 Z M 11.5 20 C 11.039063 20 10.644531 20.304688 10.53125 20.75 L 10.125 22.4375 C 8.648438 22.882813 7.285156 23.65625 6.15625 24.71875 L 4.5 24.25 C 4.058594 24.125 3.574219 24.289063 3.34375 24.6875 L 1.84375 27.3125 C 1.613281 27.710938 1.703125 28.210938 2.03125 28.53125 L 3.25 29.71875 C 3.074219 30.464844 3 31.226563 3 32 C 3 32.773438 3.074219 33.535156 3.25 34.28125 L 2.03125 35.46875 C 1.703125 35.789063 1.613281 36.289063 1.84375 36.6875 L 3.34375 39.3125 C 3.574219 39.710938 4.058594 39.871094 4.5 39.75 L 6.15625 39.28125 C 7.285156 40.34375 8.648438 41.117188 10.125 41.5625 L 10.53125 43.25 C 10.640625 43.695313 11.039063 44 11.5 44 L 14.5 44 C 14.960938 44 15.355469 43.695313 15.46875 43.25 L 15.875 41.5625 C 17.351563 41.117188 18.714844 40.34375 19.84375 39.28125 L 21.5 39.75 C 21.9375 39.878906 22.425781 39.710938 22.65625 39.3125 L 24.15625 36.6875 C 24.386719 36.289063 24.296875 35.789063 23.96875 35.46875 L 22.75 34.28125 C 22.925781 33.53125 23 32.773438 23 32 C 23 31.226563 22.925781 30.46875 22.75 29.71875 L 23.96875 28.53125 C 24.296875 28.210938 24.386719 27.710938 24.15625 27.3125 L 22.65625 24.6875 C 22.425781 24.289063 21.9375 24.125 21.5 24.25 L 19.84375 24.71875 C 18.714844 23.65625 17.351563 22.882813 15.875 22.4375 L 15.46875 20.75 C 15.359375 20.304688 14.960938 20 14.5 20 Z M 34.5 25 C 34.039063 25 33.644531 25.304688 33.53125 25.75 L 33.125 27.4375 C 31.648438 27.882813 30.285156 28.65625 29.15625 29.71875 L 27.5 29.25 C 27.058594 29.125 26.574219 29.289063 26.34375 29.6875 L 24.84375 32.3125 C 24.613281 32.710938 24.703125 33.210938 25.03125 33.53125 L 26.25 34.71875 C 26.074219 35.464844 26 36.226563 26 37 C 26 37.773438 26.074219 38.535156 26.25 39.28125 L 25.03125 40.46875 C 24.703125 40.789063 24.613281 41.289063 24.84375 41.6875 L 26.34375 44.3125 C 26.574219 44.710938 27.058594 44.871094 27.5 44.75 L 29.15625 44.28125 C 30.285156 45.34375 31.648438 46.117188 33.125 46.5625 L 33.53125 48.25 C 33.640625 48.695313 34.039063 49 34.5 49 L 37.5 49 C 37.960938 49 38.355469 48.695313 38.46875 48.25 L 38.875 46.5625 C 40.351563 46.117188 41.714844 45.34375 42.84375 44.28125 L 44.5 44.75 C 44.9375 44.878906 45.425781 44.710938 45.65625 44.3125 L 47.15625 41.6875 C 47.386719 41.289063 47.296875 40.789063 46.96875 40.46875 L 45.75 39.28125 C 45.925781 38.53125 46 37.773438 46 37 C 46 36.226563 45.925781 35.46875 45.75 34.71875 L 46.96875 33.53125 C 47.296875 33.210938 47.386719 32.710938 47.15625 32.3125 L 45.65625 29.6875 C 45.425781 29.289063 44.9375 29.125 44.5 29.25 L 42.84375 29.71875 C 41.714844 28.65625 40.351563 27.882813 38.875 27.4375 L 38.46875 25.75 C 38.359375 25.304688 37.960938 25 37.5 25 Z M 13 29 C 14.667969 29 16 30.332031 16 32 C 16 33.667969 14.667969 35 13 35 C 11.332031 35 10 33.667969 10 32 C 10 30.332031 11.332031 29 13 29 Z M 36 33 C 38.210938 33 40 34.789063 40 37 C 40 39.210938 38.210938 41 36 41 C 33.789063 41 32 39.210938 32 37 C 32 34.789063 33.789063 33 36 33 Z" />
                                          </svg>
                                        );
                                      }
                                      if (iconName.includes('user') || iconName.includes('customer')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" className="h-3.5 w-3.5 text-emerald-400">
                                            <circle cx="25" cy="18" r="8" fill="#dedcd1" stroke="currentColor" strokeWidth="2.5" />
                                            <path d="M9 40c0-6 6-10 16-10s16 4 16 10" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                          </svg>
                                        );
                                      }
                                      if (iconName.includes('cancel') || iconName.includes('x')) {
                                        return <X className="h-3.5 w-3.5 text-rose-400" />;
                                      }

                                      // 2. Keyword fallback matching
                                      if (titleLower.includes('checkout')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className="h-3.5 w-3.5 text-emerald-400 animate-in fade-in duration-100" fill="currentColor">
                                            <path d="M89,35.477H76.193V22.723C76.193,15.707,70.486,10,63.471,10H36.529c-7.015,0-12.723,5.707-12.723,12.723v12.754H11 c-0.552,0-1,0.447-1,1c0,0.553,0.448,1,1,1h2.334l6.041,51.64C19.434,89.62,19.861,90,20.368,90h60.18 c0.514,0,0.944-0.39,0.995-0.901l5.134-51.622H89c0.552,0,1-0.447,1-1C90,35.924,89.552,35.477,89,35.477z M25.807,22.723 C25.807,16.81,30.617,12,36.529,12h26.941c5.913,0,10.723,4.81,10.723,10.723v12.754H25.807V22.723z M40.058,61.887v-24.41H61.01 v24.41H40.058z M61.01,63.887V88H40.058V63.887H61.01z M38.058,37.477v24.41H18.203l-2.855-24.41H38.058z M18.437,63.887h19.62V88 h-16.8L18.437,63.887z M79.643,88H63.01V63.887h19.031L79.643,88z M82.24,61.887H63.01v-24.41h21.658L82.24,61.887z" />
                                          </svg>
                                        );
                                      }
                                      if (titleLower.includes('cart')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className="h-3.5 w-3.5 text-emerald-400 animate-in fade-in duration-100" fill="currentColor">
                                            <path d="M89,35.477H76.193V22.723C76.193,15.707,70.486,10,63.471,10H36.529c-7.015,0-12.723,5.707-12.723,12.723v12.754H11 c-0.552,0-1,0.447-1,1c0,0.553,0.448,1,1,1h2.334l6.041,51.64C19.434,89.62,19.861,90,20.368,90h60.18 c0.514,0,0.944-0.39,0.995-0.901l5.134-51.622H89c0.552,0,1-0.447,1-1C90,35.924,89.552,35.477,89,35.477z M25.807,22.723 C25.807,16.81,30.617,12,36.529,12h26.941c5.913,0,10.723,4.81,10.723,10.723v12.754H25.807V22.723z M40.058,61.887v-24.41H61.01 v24.41H40.058z M61.01,63.887V88H40.058V63.887H61.01z M38.058,37.477v24.41H18.203l-2.855-24.41H38.058z M18.437,63.887h19.62V88 h-16.8L18.437,63.887z M79.643,88H63.01V63.887h19.031L79.643,88z M82.24,61.887H63.01v-24.41h21.658L82.24,61.887z" />
                                          </svg>
                                        );
                                      }
                                      if (titleLower.includes('shop') || titleLower.includes('continue')) {
                                        return (
                                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" className="h-3.5 w-3.5 text-emerald-400">
                                            <rect x="8" y="16" width="34" height="26" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <line x1="8" y1="22" x2="42" y2="22" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="21" y="10" width="8" height="20" fill="#dedcd1" stroke="currentColor" strokeWidth="2.5" strokeLinejoin="miter" strokeLinecap="square" />
                                            <rect x="13" y="28" width="6" height="5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="miter" strokeLinecap="square" />
                                          </svg>
                                        );
                                      }
                                      if (titleLower.includes('back')) {
                                        return <ChevronRight className="h-3.5 w-3.5 rotate-180 text-gray-400" />;
                                      }
                                      if (titleLower.includes('menu')) {
                                        return <ShoppingBag className="h-3.5 w-3.5 text-emerald-400" />;
                                      }
                                      if (titleLower.includes('cancel')) {
                                        return <X className="h-3.5 w-3.5 text-rose-400" />;
                                      }

                                      return null;
                                    };
                                    const icon = getPillIcon();
                                    return (
                                      <button
                                        key={opt.id}
                                        onClick={() => sendSimulatedInput(opt.id)}
                                        className="flex items-center gap-1.5 bg-[#1f222e] hover:bg-[#2b2f40] border border-white/10 hover:border-emerald-500 text-gray-200 hover:text-white px-3 py-1 rounded-full text-[10px] font-semibold cursor-pointer transition-all duration-150 shadow-sm"
                                      >
                                        {icon}
                                        <span>{opt.title}</span>
                                      </button>
                                    );
                                  })}
                                </div>
                              );

                            case 'product_carousel':
                              return (
                                <div className="flex gap-3 mt-2.5 overflow-x-auto pb-2 -mx-2 px-2 scrollbar-thin">
                                  {payload.products?.map((prod: any) => (
                                    <div
                                      key={prod.id}
                                      className="flex-shrink-0 w-40 bg-[#0e0f14] border border-white/5 rounded-lg overflow-hidden shadow hover:border-emerald-500/30 transition-all duration-200 flex flex-col"
                                    >
                                      {prod.imageUrl ? (
                                        // eslint-disable-next-line @next/next/no-img-element
                                        <img src={prod.imageUrl} alt={prod.name} className="w-full h-20 object-cover" />
                                      ) : (
                                        <div className="w-full h-20 bg-white/5 flex items-center justify-center text-gray-500">
                                          <ShoppingBag className="h-4 w-4" />
                                        </div>
                                      )}
                                      <div className="p-2 flex-1 flex flex-col justify-between">
                                        <div>
                                          <h4 className="font-bold text-white text-[10px] line-clamp-1">{prod.name}</h4>
                                          {prod.description && (
                                            <p className="text-[8px] text-gray-400 mt-0.5 line-clamp-2 leading-tight">{prod.description}</p>
                                          )}
                                        </div>
                                        <div className="mt-2">
                                          <div className="flex justify-between items-center text-[9px]">
                                            <span className="font-mono font-extrabold text-emerald-400">${prod.price.toFixed(2)}</span>
                                            {prod.rating && (
                                              <span className="text-amber-400 flex items-center gap-0.5 font-semibold">
                                                <Star className="h-2.5 w-2.5 fill-amber-400 text-amber-400" />
                                                {prod.rating.toFixed(1)}
                                              </span>
                                            )}
                                          </div>
                                          <button
                                            onClick={() => sendSimulatedInput(prod.id)}
                                            className="mt-2 w-full bg-emerald-500 hover:bg-emerald-600 text-white font-bold py-1 rounded-md text-[8px] transition-colors cursor-pointer"
                                          >
                                            View Details
                                          </button>
                                        </div>
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              );

                            case 'product_detail':
                              const product = payload.product;
                              if (!product) return null;
                              return (
                                <div className="w-full bg-[#0e0f14] border border-white/5 rounded-lg overflow-hidden shadow mt-2.5 flex flex-col">
                                  {product.imageUrl ? (
                                    // eslint-disable-next-line @next/next/no-img-element
                                    <img src={product.imageUrl} alt={product.name} className="w-full h-28 object-cover" />
                                  ) : (
                                    <div className="w-full h-28 bg-white/5 flex items-center justify-center text-gray-500">
                                      <ShoppingBag className="h-6 w-6" />
                                    </div>
                                  )}
                                  <div className="p-3">
                                    <h4 className="font-extrabold text-white text-[11px] leading-tight">{product.name}</h4>
                                    {product.description && (
                                      <p className="text-[9px] text-gray-300 mt-1 leading-normal">{product.description}</p>
                                    )}
                                    <p className="font-mono text-[10px] font-extrabold text-emerald-400 mt-2">Price: ${product.price.toFixed(2)}</p>
                                    
                                    <div className="mt-3 border-t border-white/5 pt-2 flex gap-1.5">
                                      <button
                                        onClick={() => {
                                          setQtySelectProduct({
                                            name: product.name,
                                            price: product.price,
                                            imageUrl: product.imageUrl || undefined
                                          });
                                          setQtyValue(1);
                                        }}
                                        className="flex-1 bg-emerald-500 hover:bg-emerald-600 text-white font-bold py-1.5 rounded-md text-[9px] transition-all cursor-pointer flex items-center justify-center gap-1 shadow border-0"
                                      >
                                        <ShoppingCart className="h-3 w-3" />
                                        Quantity
                                      </button>
                                      <button
                                        onClick={() => sendSimulatedInput('B')}
                                        className="bg-white/5 hover:bg-white/10 border border-white/10 text-white px-2 py-1.5 rounded-md text-[9px] font-bold cursor-pointer transition-all flex items-center gap-1"
                                      >
                                        <ArrowLeft className="h-2.5 w-2.5" />
                                        Back
                                      </button>
                                    </div>
                                  </div>
                                </div>
                              );

                            case 'cta_url':
                              return (
                                <div className="mt-2.5">
                                  <button
                                    onClick={async () => {
                                      if (payload.url?.includes('whatsapp/quantity')) {
                                        try {
                                          const urlObj = new URL(payload.url, window.location.origin);
                                          const prodId = urlObj.searchParams.get('productId');
                                          const products = await apiRequest('api/products');
                                          const matched = products.find((p: any) => p.id === prodId);
                                          if (matched) {
                                            setQtySelectProduct({
                                              name: matched.name,
                                              price: matched.price,
                                              imageUrl: matched.imageUrl || undefined
                                            });
                                            setQtyValue(1);
                                          }
                                        } catch (err) {
                                          console.error('Failed to parse webview url:', err);
                                        }
                                      } else {
                                        window.open(payload.url, '_blank');
                                      }
                                    }}
                                    className="w-full bg-emerald-500 hover:bg-emerald-600 text-white font-bold py-1.5 rounded-md text-[9px] transition-all cursor-pointer flex items-center justify-center gap-1 shadow border-0"
                                  >
                                    <ExternalLink className="h-3 w-3" />
                                    {payload.urlButtonText || 'Open Link'}
                                  </button>
                                </div>
                              );

                            default:
                              return null;
                          }
                        };

                        return (
                          <div
                            key={msg.id}
                            className={`flex ${isBot ? 'justify-end' : 'justify-start'}`}
                          >
                            <div
                              className={`max-w-[85%] rounded-xl px-3 py-2 text-[11px] shadow ${
                                isBot
                                  ? 'chat-bubble-out font-sans'
                                  : 'chat-bubble-in font-sans'
                              }`}
                            >
                              {/* Preserve bot whitespaces and line breaks */}
                              <p className="whitespace-pre-wrap leading-relaxed select-text font-sans">
                                {msg.messageBody}
                              </p>

                              {/* Visual Interactive Templates */}
                              {isBot && renderPayload()}
                              
                              {/* Payment Link Cards inside Bot Bubble */}
                              {isBot && !payload && msg.messageBody.includes('http://localhost:3000/payments/checkout') && (
                                <div className="mt-2.5 p-2 bg-black/30 border border-white/5 rounded-lg flex items-center justify-between gap-3">
                                  <div>
                                    <p className="font-bold text-[9px] text-white">Interactive Invoice</p>
                                    <span className="text-[7px] text-gray-500 font-mono">Sandbox Sandbox</span>
                                  </div>
                                  {/* Extract and render the payment url */}
                                  {(() => {
                                    const match = msg.messageBody.match(/https?:\/\/[^\s]+/);
                                    const payUrl = match ? match[0] : '#';
                                    return (
                                      <a
                                        href={payUrl}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="bg-emerald-500 hover:bg-emerald-600 text-white font-bold px-2 py-1 rounded text-[8px] flex items-center gap-1 transition-colors leading-none shadow cursor-pointer border-0"
                                      >
                                        Pay Invoice
                                        <ExternalLink className="h-2 w-2" />
                                      </a>
                                    );
                                  })()}
                                </div>
                              )}

                              <span className="text-[7px] text-gray-400 block text-right mt-1 font-mono">
                                {new Date(msg.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                              </span>
                            </div>
                          </div>
                        );
                      })}
                      <div ref={chatEndRef} />
                    </div>
                  )}
                </div>

                {/* Chat Input */}
                <form onSubmit={handleSendMessage} className="bg-[var(--surface-bright)] p-3 flex gap-2 border-t border-white/5 shrink-0 z-20">
                  <input
                    type="text"
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    placeholder="Type a message..."
                    disabled={sending}
                    className="flex-1 glass-input bg-[var(--input-bg)] px-3 py-2 text-[11px] outline-none focus:border-emerald-500 min-w-0"
                  />
                  <button
                    type="submit"
                    disabled={sending || !message.trim()}
                    className="bg-emerald-500 hover:bg-emerald-600 text-white h-8 w-8 rounded-full flex items-center justify-center transition-all disabled:opacity-50 disabled:pointer-events-none cursor-pointer shrink-0 border-0"
                  >
                    <Send className="h-3.5 w-3.5" />
                  </button>
                </form>

                {/* Bottom Sheet Modal Overlay for Select Quantity */}
                {qtySelectProduct && (
                  <div className="absolute inset-0 bg-black/70 z-30 transition-opacity duration-300 flex flex-col justify-end">
                    {/* Tap to close background */}
                    <div className="flex-1" onClick={() => setQtySelectProduct(null)} />
                    
                    {/* Bottom Sheet Panel */}
                    <div className="bg-[#12141c] border-t border-white/10 rounded-t-3xl p-5 text-white animate-slide-up relative z-40 select-none shadow-[0_-8px_30px_rgba(0,0,0,0.5)] flex flex-col">
                      {/* Drag Handle */}
                      <div className="w-10 h-1 bg-white/10 rounded-full mx-auto mb-4" />

                      {/* Header */}
                      <div className="flex justify-between items-center mb-4">
                        <h3 className="text-sm font-bold text-white font-sans tracking-tight">Select Quantity</h3>
                        <button 
                          onClick={() => setQtySelectProduct(null)} 
                          className="p-1 rounded-full hover:bg-white/5 text-gray-400 hover:text-white transition-colors border-0 cursor-pointer bg-transparent"
                        >
                          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                          </svg>
                        </button>
                      </div>

                      {/* Product Info Card */}
                      <div className="flex gap-3 p-3 rounded-xl bg-white/5 border border-white/5 mb-4 items-center">
                        {qtySelectProduct.imageUrl ? (
                          <img 
                            src={qtySelectProduct.imageUrl} 
                            alt={qtySelectProduct.name} 
                            className="w-12 h-12 object-cover rounded-lg border border-white/5" 
                          />
                        ) : (
                          <div className="w-12 h-12 bg-white/5 flex items-center justify-center rounded-lg text-gray-400">
                            <ShoppingBag className="h-5 w-5" />
                          </div>
                        )}
                        <div className="flex-1 min-w-0">
                          <h4 className="font-bold text-xs text-white truncate leading-snug">{qtySelectProduct.name}</h4>
                          <p className="text-[10px] text-gray-400 mt-0.5">${qtySelectProduct.price.toFixed(2)} per unit</p>
                        </div>
                      </div>

                      {/* Quantity Control */}
                      <div className="flex flex-col items-center justify-center py-4 mb-4">
                        <div className="flex items-center gap-6">
                          {/* Minus Button */}
                          <button
                            onClick={() => setQtyValue(Math.max(1, qtyValue - 1))}
                            disabled={qtyValue <= 1}
                            className="w-10 h-10 rounded-full border border-white/10 bg-white/5 text-white flex items-center justify-center text-sm hover:bg-white/10 transition-colors disabled:opacity-40 disabled:pointer-events-none cursor-pointer"
                          >
                            —
                          </button>

                          {/* Quantity Display */}
                          <div className="text-center w-12">
                            <span className="text-3xl font-extrabold tracking-tighter text-white">{qtyValue}</span>
                            <span className="block text-[8px] font-bold text-gray-500 tracking-widest uppercase mt-0.5">Units</span>
                          </div>

                          {/* Plus Button */}
                          <button
                            onClick={() => setQtyValue(qtyValue + 1)}
                            className="w-10 h-10 rounded-full border border-emerald-500 bg-emerald-500/10 text-emerald-400 flex items-center justify-center text-sm hover:bg-emerald-500/20 transition-colors cursor-pointer"
                          >
                            +
                          </button>
                        </div>

                        {/* Subtotal Badge */}
                        <div className="mt-4 bg-emerald-500/10 text-emerald-400 px-3 py-1 rounded-full text-[10px] font-bold border border-emerald-500/20 flex items-center gap-1 shadow-sm">
                          <span>Subtotal:</span>
                          <span className="font-mono text-xs font-extrabold">${(qtySelectProduct.price * qtyValue).toFixed(2)}</span>
                        </div>
                      </div>

                      {/* Action Button */}
                      <button
                        onClick={async () => {
                          const selectedVal = qtyValue;
                          setQtySelectProduct(null);
                          await sendSimulatedInput(String(selectedVal));
                        }}
                        className="w-full bg-emerald-500 hover:bg-emerald-600 text-white font-bold py-2.5 px-4 rounded-xl text-xs transition-all duration-150 flex items-center justify-center gap-2 cursor-pointer shadow active:scale-[0.98] border-0"
                      >
                        <ShoppingCart className="h-4 w-4" />
                        Confirm Quantity
                      </button>

                      {/* Footer Disclaimer */}
                      <p className="text-[8px] text-gray-500 text-center mt-3 max-w-xs mx-auto leading-normal">
                        Secure checkout powered by RetailBot.
                      </p>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Debug Console Panel Column */}
        <div className={`lg:col-span-5 flex flex-col gap-6 overflow-hidden ${
          activeSimTab === 'inspector' ? 'flex' : 'hidden lg:flex'
        }`}>
          {/* Bot State Console */}
          <div className="flex-1 glass-panel rounded-2xl p-6 flex flex-col overflow-hidden border border-white/5">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <Terminal className="h-4.5 w-4.5 text-cyan-400" />
                <h3 className="font-bold text-white text-sm font-sans">Session State Inspector</h3>
              </div>
              <button
                onClick={handleResetSession}
                className="flex items-center gap-1 text-[10px] bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/20 px-2.5 py-1 rounded-lg transition-colors cursor-pointer"
              >
                <Trash2 className="h-3 w-3" />
                Reset Session
              </button>
            </div>

            <div className="flex-1 bg-black/40 p-4 rounded-xl border border-white/5 font-mono text-xs text-emerald-400 overflow-y-auto space-y-4">
              <div>
                <span className="text-gray-500">// Bot Conversation State:</span>
                <p className="mt-1">
                  Active Step: <strong className="text-white bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20">{sessionState.currentStep || 'WELCOME'}</strong>
                </p>
              </div>

              <div className="space-y-1">
                <span className="text-gray-500">// Active Session Variables:</span>
                <pre className="text-[10px] text-cyan-300 leading-normal bg-black/20 p-2.5 rounded border border-white/3 select-text overflow-x-auto">
                  {JSON.stringify(sessionState.data || {}, null, 2)}
                </pre>
              </div>

              {sessionState.expiresAt && (
                <div className="text-[10px] text-gray-500 font-mono">
                  Expiry: {new Date(sessionState.expiresAt).toLocaleTimeString()}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
