const { useState, useEffect, useMemo, useRef } = React;

const SERVER_URL = window.location.origin.includes('localhost') ? 'http://localhost:4000' : window.location.origin;

// Audio Alerts (Web Audio API)
const playSound = (type = 'message') => {
  try {
    const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    const osc = audioCtx.createOscillator();
    const gain = audioCtx.createGain();
    osc.connect(gain);
    gain.connect(audioCtx.destination);

    if (type === 'urgent') {
      osc.frequency.setValueAtTime(659.25, audioCtx.currentTime);
      osc.frequency.setValueAtTime(880, audioCtx.currentTime + 0.12);
      gain.gain.setValueAtTime(0.25, audioCtx.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.4);
      osc.start(audioCtx.currentTime);
      osc.stop(audioCtx.currentTime + 0.4);
    } else {
      osc.frequency.setValueAtTime(523.25, audioCtx.currentTime);
      osc.frequency.setValueAtTime(659.25, audioCtx.currentTime + 0.08);
      gain.gain.setValueAtTime(0.15, audioCtx.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.25);
      osc.start(audioCtx.currentTime);
      osc.stop(audioCtx.currentTime + 0.25);
    }
  } catch (e) {}
};

// Website Configuration with Official Brand Logos
const SITES_META = {
  'alpha-ahead': {
    name: 'Alpha Ahead',
    shortCode: 'AA',
    logo: 'assets/alpha-ahead-logo.png',
    badge: 'bg-blue-50 text-blue-700 border-blue-200'
  },
  'alpha-medical': {
    name: 'Alpha Medical',
    shortCode: 'AM',
    logo: 'assets/alpha-medical-logo.png',
    badge: 'bg-emerald-50 text-emerald-700 border-emerald-200'
  },
  'zingo-assist': {
    name: 'Zingo Assist',
    shortCode: 'ZA',
    logo: 'assets/zingo-assist-logo.png',
    badge: 'bg-pink-50 text-pink-700 border-pink-200'
  }
};

const getSiteMeta = (siteId) => {
  return SITES_META[siteId] || {
    name: siteId || 'General Portal',
    shortCode: 'WS',
    logo: null,
    badge: 'bg-slate-100 text-slate-700 border-slate-200'
  };
};

function OmniChatConsole() {
  const [sessions, setSessions] = useState([]);
  const [activeSessionId, setActiveSessionId] = useState(null);
  const [messages, setMessages] = useState([]);
  const [siteFilter, setSiteFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [agentName, setAgentName] = useState('Support Agent');
  const [soundEnabled, setSoundEnabled] = useState(true);
  const [cannedReplies, setCannedReplies] = useState([]);
  const [inputText, setInputText] = useState('');
  const [saveStatus, setSaveStatus] = useState('Save Changes');
  const [copiedField, setCopiedField] = useState(null);

  const messagesEndRef = useRef(null);
  const activeSessionIdRef = useRef(activeSessionId);

  useEffect(() => {
    activeSessionIdRef.current = activeSessionId;
  }, [activeSessionId]);

  // Active Session
  const activeSession = useMemo(() => {
    return sessions.find(s => s.id === activeSessionId) || null;
  }, [sessions, activeSessionId]);

  // Initial Fetch
  useEffect(() => {
    fetchSessions();
    fetchCannedReplies();
  }, []);

  // Real-time EventSource Stream
  useEffect(() => {
    const eventSource = new EventSource(`${SERVER_URL}/api/events?role=admin`);

    eventSource.addEventListener('session_updated', (e) => {
      const updated = JSON.parse(e.data);
      if (activeSessionIdRef.current === updated.id) {
        updated.unreadByAdmin = 0;
      }
      setSessions(prev => {
        const idx = prev.findIndex(s => s.id === updated.id);
        if (idx !== -1) {
          const next = [...prev];
          next[idx] = updated;
          return next;
        } else {
          if (soundEnabled) playSound('urgent');
          return [updated, ...prev];
        }
      });

      if (updated.status === 'waiting_agent' && soundEnabled) {
        playSound('urgent');
      }
    });

    eventSource.addEventListener('message_new', (e) => {
      const msg = JSON.parse(e.data);
      if (activeSessionIdRef.current === msg.sessionId) {
        setMessages(prev => {
          if (prev.some(m => m.id === msg.id)) return prev;
          return [...prev, msg];
        });
        // Clear unread on backend since agent is currently in this room
        fetch(`${SERVER_URL}/api/sessions/${msg.sessionId}/read`, { method: 'POST' }).catch(() => {});
        setSessions(prev => prev.map(s => s.id === msg.sessionId ? { ...s, unreadByAdmin: 0 } : s));
      }
      if (msg.sender === 'visitor' && soundEnabled) {
        playSound('message');
      }
    });

    return () => {
      eventSource.close();
    };
  }, [soundEnabled]);

  // Auto-scroll messages
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // Fetch messages when selecting conversation
  useEffect(() => {
    if (activeSessionId) {
      fetchMessages(activeSessionId);
    }
  }, [activeSessionId]);

  const fetchSessions = async () => {
    try {
      const res = await fetch(`${SERVER_URL}/api/sessions`);
      const data = await res.json();
      if (data.success) {
        setSessions(data.sessions || []);
      }
    } catch (e) {
      console.error('Error loading sessions:', e);
    }
  };

  const fetchCannedReplies = async () => {
    try {
      const res = await fetch(`${SERVER_URL}/api/canned-responses`);
      const data = await res.json();
      if (data.success) {
        setCannedReplies(data.responses || []);
      }
    } catch (e) {
      console.error('Error loading canned replies:', e);
    }
  };

  const fetchMessages = async (sessionId) => {
    try {
      const res = await fetch(`${SERVER_URL}/api/sessions/${sessionId}/messages?role=admin`);
      const data = await res.json();
      if (data.success) {
        setMessages(data.messages || []);
      }
    } catch (e) {
      console.error('Error loading messages:', e);
    }
  };

  const handleSelectSession = (sessionId) => {
    setActiveSessionId(sessionId);
    setSessions(prev => prev.map(s => s.id === sessionId ? { ...s, unreadByAdmin: 0 } : s));
    fetch(`${SERVER_URL}/api/sessions/${sessionId}/read`, { method: 'POST' }).catch(() => {});
  };

  const handleSendMessage = async (e) => {
    if (e) e.preventDefault();
    if (!inputText.trim() || !activeSessionId) return;

    const textToSend = inputText.trim();
    setInputText('');

    try {
      await fetch(`${SERVER_URL}/api/messages/admin`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          sessionId: activeSessionId,
          text: textToSend,
          agentName
        })
      });
    } catch (err) {
      console.error('Failed to send message:', err);
    }
  };

  const handleTakeover = async () => {
    if (!activeSessionId) return;
    try {
      await fetch(`${SERVER_URL}/api/sessions/takeover`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          sessionId: activeSessionId,
          agentName
        })
      });
    } catch (err) {
      console.error('Takeover failed:', err);
    }
  };

  const handleReturnToBot = async () => {
    if (!activeSessionId) return;
    try {
      await fetch(`${SERVER_URL}/api/sessions/return-to-bot`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sessionId: activeSessionId })
      });
    } catch (err) {
      console.error('Transfer failed:', err);
    }
  };

  const handleSaveLead = async (leadUpdates) => {
    if (!activeSessionId) return;
    setSaveStatus('Saving...');
    try {
      const res = await fetch(`${SERVER_URL}/api/sessions/${activeSessionId}/lead`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(leadUpdates)
      });
      const data = await res.json();
      if (data.success) {
        setSaveStatus('Saved');
        setTimeout(() => setSaveStatus('Save Changes'), 2000);
      }
    } catch (err) {
      console.error('Failed to save lead:', err);
      setSaveStatus('Error saving');
    }
  };

  const copyText = (text, field) => {
    if (!text) return;
    navigator.clipboard.writeText(text);
    setCopiedField(field);
    setTimeout(() => setCopiedField(null), 1500);
  };

  // Filtered Sessions
  const filteredSessions = useMemo(() => {
    return sessions.filter(s => {
      if (siteFilter !== 'all' && s.siteId !== siteFilter) return false;
      if (statusFilter === 'needs_agent' && s.status !== 'waiting_agent') return false;
      if (statusFilter === 'agent' && s.status !== 'agent') return false;
      if (statusFilter === 'bot' && s.status !== 'bot') return false;

      if (searchQuery.trim()) {
        const q = searchQuery.toLowerCase();
        const name = (s.visitorName || '').toLowerCase();
        const phone = (s.phone || '').toLowerCase();
        const email = (s.email || '').toLowerCase();
        const service = (s.serviceRequested || '').toLowerCase();
        const msg = (s.lastMessage || '').toLowerCase();
        if (!name.includes(q) && !phone.includes(q) && !email.includes(q) && !service.includes(q) && !msg.includes(q)) {
          return false;
        }
      }
      return true;
    });
  }, [sessions, siteFilter, statusFilter, searchQuery]);

  // Unread message counts per site for badges
  const siteUnreadCounts = useMemo(() => {
    const counts = {
      all: 0,
      'alpha-ahead': 0,
      'alpha-medical': 0,
      'zingo-assist': 0
    };
    sessions.forEach(s => {
      const unread = s.unreadByAdmin || 0;
      if (unread > 0) {
        counts.all += unread;
        if (counts[s.siteId] !== undefined) {
          counts[s.siteId] += unread;
        }
      }
    });
    return counts;
  }, [sessions]);

  const urgentCount = useMemo(() => {
    return sessions.filter(s => s.status === 'waiting_agent').length;
  }, [sessions]);

  return (
    <div className="flex h-screen w-screen bg-slate-100 overflow-hidden">
      
      {/* ================= COLUMN 0: SLIM BRAND RAIL (72px) ================= */}
      <nav className="w-[72px] bg-slate-900 border-r border-slate-800 flex flex-col items-center py-4 justify-between shrink-0 z-20">
        <div className="flex flex-col items-center gap-5 w-full">
          
          {/* Main App Hub Icon */}
          <div className="w-11 h-11 rounded-xl bg-indigo-600 flex items-center justify-center text-white font-bold shadow-md">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
            </svg>
          </div>

          <div className="w-8 h-px bg-slate-800"></div>

          {/* Website Logo Buttons */}
          <div className="flex flex-col items-center gap-2.5 w-full px-2">
            
            {/* All Sites */}
            <button
              onClick={() => setSiteFilter('all')}
              className={`w-12 h-12 rounded-xl flex flex-col items-center justify-center text-xs font-semibold transition-all relative ${
                siteFilter === 'all'
                  ? 'bg-indigo-600 text-white shadow-sm ring-2 ring-indigo-400'
                  : 'text-slate-400 hover:text-white hover:bg-slate-800'
              }`}
              title="All Websites"
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="10"></circle>
                <line x1="2" y1="12" x2="22" y2="12"></line>
                <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path>
              </svg>
              <span className="text-[9px] mt-0.5 font-medium">All</span>
              {siteUnreadCounts.all > 0 && (
                <span className="absolute -top-1 -right-1 min-w-4 h-4 px-1 bg-rose-500 text-white rounded-full text-[9px] flex items-center justify-center font-bold shadow-sm animate-pulse">
                  {siteUnreadCounts.all}
                </span>
              )}
            </button>

            {/* Alpha Ahead Logo Button */}
            <button
              onClick={() => setSiteFilter('alpha-ahead')}
              className={`w-12 h-12 rounded-xl p-1.5 flex items-center justify-center transition-all relative bg-white border ${
                siteFilter === 'alpha-ahead'
                  ? 'ring-2 ring-blue-500 border-blue-500 shadow-md'
                  : 'border-slate-700/80 hover:border-blue-400 opacity-80 hover:opacity-100'
              }`}
              title="Alpha Ahead"
            >
              <img
                src="assets/alpha-ahead-logo.png"
                alt="Alpha Ahead"
                className="max-h-full max-w-full object-contain"
                onError={(e) => { e.target.style.display = 'none'; e.target.nextSibling.style.display = 'block'; }}
              />
              <span className="hidden text-blue-700 font-bold text-xs">AA</span>
              {siteUnreadCounts['alpha-ahead'] > 0 && (
                <span className="absolute -top-1 -right-1 min-w-4 h-4 px-1 bg-rose-500 text-white rounded-full text-[9px] flex items-center justify-center font-bold shadow-sm animate-pulse">
                  {siteUnreadCounts['alpha-ahead']}
                </span>
              )}
            </button>

            {/* Alpha Medical Logo Button */}
            <button
              onClick={() => setSiteFilter('alpha-medical')}
              className={`w-12 h-12 rounded-xl p-1.5 flex items-center justify-center transition-all relative bg-white border ${
                siteFilter === 'alpha-medical'
                  ? 'ring-2 ring-emerald-500 border-emerald-500 shadow-md'
                  : 'border-slate-700/80 hover:border-emerald-400 opacity-80 hover:opacity-100'
              }`}
              title="Alpha Medical"
            >
              <img
                src="assets/alpha-medical-logo.png"
                alt="Alpha Medical"
                className="max-h-full max-w-full object-contain"
                onError={(e) => { e.target.style.display = 'none'; e.target.nextSibling.style.display = 'block'; }}
              />
              <span className="hidden text-emerald-700 font-bold text-xs">AM</span>
              {siteUnreadCounts['alpha-medical'] > 0 && (
                <span className="absolute -top-1 -right-1 min-w-4 h-4 px-1 bg-rose-500 text-white rounded-full text-[9px] flex items-center justify-center font-bold shadow-sm animate-pulse">
                  {siteUnreadCounts['alpha-medical']}
                </span>
              )}
            </button>

            {/* Zingo Assist Logo Button */}
            <button
              onClick={() => setSiteFilter('zingo-assist')}
              className={`w-12 h-12 rounded-xl p-1.5 flex items-center justify-center transition-all relative bg-white border ${
                siteFilter === 'zingo-assist'
                  ? 'ring-2 ring-pink-500 border-pink-500 shadow-md'
                  : 'border-slate-700/80 hover:border-pink-400 opacity-80 hover:opacity-100'
              }`}
              title="Zingo Assist"
            >
              <img
                src="assets/zingo-assist-logo.png"
                alt="Zingo Assist"
                className="max-h-full max-w-full object-contain"
                onError={(e) => { e.target.style.display = 'none'; e.target.nextSibling.style.display = 'block'; }}
              />
              <span className="hidden text-pink-700 font-bold text-xs">ZA</span>
              {siteUnreadCounts['zingo-assist'] > 0 && (
                <span className="absolute -top-1 -right-1 min-w-4 h-4 px-1 bg-rose-500 text-white rounded-full text-[9px] flex items-center justify-center font-bold shadow-sm animate-pulse">
                  {siteUnreadCounts['zingo-assist']}
                </span>
              )}
            </button>
          </div>
        </div>

        {/* Bottom Actions */}
        <div className="flex flex-col items-center gap-3 w-full">
          <button
            onClick={() => setSoundEnabled(!soundEnabled)}
            className={`w-10 h-10 rounded-lg flex items-center justify-center text-sm transition-all ${
              soundEnabled ? 'text-indigo-400 hover:bg-slate-800' : 'text-slate-600 hover:bg-slate-800'
            }`}
            title={soundEnabled ? 'Audio alerts active' : 'Audio alerts muted'}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
              <path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
            </svg>
          </button>

          <div className="w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center text-white text-xs font-semibold" title={agentName}>
            <span>{agentName.slice(0, 2).toUpperCase()}</span>
          </div>
        </div>
      </nav>

      {/* ================= COLUMN 1: CONVERSATION QUEUE (320px) ================= */}
      <aside className="w-80 bg-white border-r border-slate-200 flex flex-col shrink-0">
        
        {/* Queue Header */}
        <div className="p-4 border-b border-slate-100 flex flex-col gap-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <h1 className="text-sm font-semibold text-slate-900 tracking-tight">Conversations</h1>
              <span className="text-xs px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 font-medium">
                {filteredSessions.length}
              </span>
            </div>

            {urgentCount > 0 && (
              <span className="text-[11px] font-medium px-2 py-0.5 rounded-full bg-rose-50 text-rose-700 border border-rose-200 animate-pulse">
                {urgentCount} waiting
              </span>
            )}
          </div>

          {/* Search */}
          <div className="relative">
            <span className="absolute left-3 top-2.5 text-slate-400">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
              </svg>
            </span>
            <input
              type="text"
              placeholder="Search conversations..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full bg-slate-50 border border-slate-200 rounded-lg pl-8 pr-7 py-1.5 text-xs text-slate-800 placeholder-slate-400 focus:outline-none focus:bg-white focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="absolute right-2.5 top-2 text-slate-400 hover:text-slate-600 text-xs font-bold"
              >
                ✕
              </button>
            )}
          </div>

          {/* Segmented Filter */}
          <div className="grid grid-cols-4 gap-1 p-1 bg-slate-100 rounded-lg text-[11px] font-medium text-slate-600">
            <button
              onClick={() => setStatusFilter('all')}
              className={`py-1 rounded-md text-center transition-all ${statusFilter === 'all' ? 'bg-white text-slate-900 shadow-xs font-semibold' : 'hover:text-slate-900'}`}
            >
              All
            </button>
            <button
              onClick={() => setStatusFilter('needs_agent')}
              className={`py-1 rounded-md text-center transition-all ${statusFilter === 'needs_agent' ? 'bg-white text-slate-900 shadow-xs font-semibold' : 'hover:text-slate-900'}`}
            >
              Waiting
            </button>
            <button
              onClick={() => setStatusFilter('agent')}
              className={`py-1 rounded-md text-center transition-all ${statusFilter === 'agent' ? 'bg-white text-slate-900 shadow-xs font-semibold' : 'hover:text-slate-900'}`}
            >
              Live
            </button>
            <button
              onClick={() => setStatusFilter('bot')}
              className={`py-1 rounded-md text-center transition-all ${statusFilter === 'bot' ? 'bg-white text-slate-900 shadow-xs font-semibold' : 'hover:text-slate-900'}`}
            >
              Bot
            </button>
          </div>
        </div>

        {/* Conversation List Items */}
        <div className="flex-1 overflow-y-auto divide-y divide-slate-100">
          {filteredSessions.length === 0 ? (
            <div className="p-8 text-center text-slate-400">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="mx-auto mb-2 opacity-60">
                <rect width="20" height="16" x="2" y="4" rx="2"></rect>
                <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"></path>
              </svg>
              <p className="text-xs font-medium text-slate-600">No conversations in queue</p>
              <p className="text-[11px] text-slate-400 mt-0.5">Inbound visitors will show up here.</p>
            </div>
          ) : (
            filteredSessions.map(sess => {
              const meta = getSiteMeta(sess.siteId);
              const isSelected = sess.id === activeSessionId;
              const isWaiting = sess.status === 'waiting_agent';
              const unread = sess.unreadByAdmin || 0;
              const time = sess.updatedAt ? new Date(sess.updatedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '';

              return (
                <div
                  key={sess.id}
                  onClick={() => handleSelectSession(sess.id)}
                  className={`p-3.5 cursor-pointer transition-colors flex items-start gap-3 border-l-2 ${
                    isSelected
                      ? 'bg-slate-50 border-indigo-600'
                      : isWaiting
                      ? 'bg-rose-50/40 border-rose-500 hover:bg-rose-50/80'
                      : 'border-transparent hover:bg-slate-50/80'
                  }`}
                >
                  {/* Brand Logo or Initials */}
                  <div className="w-8 h-8 rounded-lg bg-white border border-slate-200 p-1 flex items-center justify-center shrink-0 shadow-2xs">
                    {meta.logo ? (
                      <img src={meta.logo} alt={meta.name} className="max-h-full max-w-full object-contain" />
                    ) : (
                      <span className="text-[11px] font-bold text-slate-700">{meta.shortCode}</span>
                    )}
                  </div>

                  {/* Body */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between mb-0.5">
                      <span className="text-xs font-semibold text-slate-900 truncate">
                        {sess.visitorName || `Visitor #${sess.id.slice(-4)}`}
                      </span>
                      <span className="text-[10px] text-slate-400 font-mono">{time}</span>
                    </div>

                    <p className="text-xs text-slate-500 truncate mb-1.5 font-normal">
                      {sess.lastMessage || sess.serviceRequested || 'Session started'}
                    </p>

                    <div className="flex items-center gap-1.5">
                      <span className={`text-[10px] font-medium px-1.5 py-0.2 rounded border ${meta.badge}`}>
                        {meta.name}
                      </span>

                      {isWaiting && (
                        <span className="text-[10px] font-semibold text-rose-600">
                          • Needs reply
                        </span>
                      )}

                      {unread > 0 && (
                        <span className="ml-auto w-2 h-2 rounded-full bg-rose-600"></span>
                      )}
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>
      </aside>

      {/* ================= COLUMN 2: ACTIVE CONVERSATION WORKSPACE ================= */}
      <main className="flex-1 bg-white flex flex-col min-w-0">
        
        {!activeSession ? (
          <div className="flex-1 flex flex-col items-center justify-center p-8 text-center bg-slate-50/40">
            <div className="w-12 h-12 rounded-xl bg-slate-100 flex items-center justify-center text-slate-400 mb-3">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
              </svg>
            </div>
            <h2 className="text-sm font-semibold text-slate-800">Select a conversation</h2>
            <p className="text-xs text-slate-500 max-w-xs mt-1 leading-relaxed">
              Choose an active visitor from the sidebar to view chat history or send a direct response.
            </p>
          </div>
        ) : (
          <>
            {/* Conversation Header */}
            <div className="h-14 px-6 border-b border-slate-200 flex items-center justify-between shrink-0">
              <div className="flex items-center gap-3 min-w-0">
                <div className="w-8 h-8 rounded-lg bg-white border border-slate-200 p-1 flex items-center justify-center shrink-0">
                  {getSiteMeta(activeSession.siteId).logo ? (
                    <img src={getSiteMeta(activeSession.siteId).logo} alt="Logo" className="max-h-full max-w-full object-contain" />
                  ) : (
                    <span className="text-xs font-bold text-indigo-700">{getSiteMeta(activeSession.siteId).shortCode}</span>
                  )}
                </div>
                <div className="min-w-0">
                  <div className="flex items-center gap-2">
                    <h2 className="text-xs font-semibold text-slate-900 truncate">
                      {activeSession.visitorName || `Visitor #${activeSession.id.slice(-4)}`}
                    </h2>
                    <span className={`text-[10px] font-medium px-2 py-0.2 rounded-full border ${getSiteMeta(activeSession.siteId).badge}`}>
                      {getSiteMeta(activeSession.siteId).name}
                    </span>
                  </div>
                  <p className="text-[11px] text-slate-500 truncate">
                    {activeSession.serviceRequested || 'General Exploration'}
                  </p>
                </div>
              </div>

              {/* Mode Action Button */}
              <div className="flex items-center gap-2">
                {activeSession.status === 'agent' ? (
                  <button
                    onClick={handleReturnToBot}
                    className="px-3 py-1.5 rounded-lg bg-slate-50 hover:bg-slate-100 border border-slate-300 text-xs font-medium text-slate-700 transition-all flex items-center gap-1.5"
                  >
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="1 4 1 10 7 10"></polyline>
                      <path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path>
                    </svg>
                    <span>Transfer to Bot</span>
                  </button>
                ) : (
                  <button
                    onClick={handleTakeover}
                    className="px-3.5 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-medium transition-all flex items-center gap-1.5 shadow-xs"
                  >
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                      <circle cx="12" cy="7" r="4"></circle>
                    </svg>
                    <span>Take Over</span>
                  </button>
                )}
              </div>
            </div>

            {/* Message Thread */}
            <div className="flex-1 overflow-y-auto p-6 space-y-4 bg-slate-50/30">
              {messages.map((msg, index) => {
                const isVisitor = msg.sender === 'visitor';
                const isBot = msg.sender === 'bot';
                const isAgent = msg.sender === 'agent';
                const isSystem = msg.sender === 'system';
                const time = msg.timestamp ? new Date(msg.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '';

                if (isSystem) {
                  return (
                    <div key={msg.id || index} className="flex justify-center my-2">
                      <span className="system-chip">{msg.text}</span>
                    </div>
                  );
                }

                return (
                  <div
                    key={msg.id || index}
                    className={`flex flex-col max-w-[75%] ${isVisitor ? 'mr-auto items-start' : isBot ? 'mr-auto items-start' : 'ml-auto items-end'}`}
                  >
                    <span className="text-[10px] font-medium text-slate-400 mb-1 px-1">
                      {isVisitor ? (activeSession.visitorName || 'Visitor') : isBot ? 'Automated Assistant' : (activeSession.assignedAgent || agentName)} • {time}
                    </span>

                    <div
                      className={`p-3 text-xs leading-relaxed ${
                        isVisitor
                          ? 'msg-bubble-visitor'
                          : isBot
                          ? 'msg-bubble-bot'
                          : 'msg-bubble-agent'
                      }`}
                    >
                      <p className="whitespace-pre-line">{msg.text}</p>

                      {msg.options && (
                        <div className="mt-2.5 pt-2 border-t border-slate-200/80 flex flex-wrap gap-1.5">
                          {msg.options.map((opt, i) => (
                            <span key={i} className="text-[10.5px] px-2 py-0.5 rounded bg-indigo-50 text-indigo-700 font-medium">
                              {opt.text || opt.name}
                            </span>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
              <div ref={messagesEndRef} />
            </div>

            {/* Composer Footer */}
            <div className="p-4 border-t border-slate-200 bg-white">
              
              {/* Quick Saved Replies */}
              <div className="flex items-center gap-1.5 mb-2 overflow-x-auto pb-1 scrollbar-none">
                <span className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider shrink-0 mr-1">
                  Saved replies:
                </span>
                {cannedReplies.map(c => (
                  <button
                    key={c.id}
                    onClick={() => setInputText(c.text.replace('[Agent]', agentName.split(' ')[0]))}
                    className="px-2.5 py-1 rounded bg-slate-100 hover:bg-slate-200 text-[11px] text-slate-700 whitespace-nowrap transition-colors"
                  >
                    {c.title}
                  </button>
                ))}
              </div>

              {/* Text Input Box */}
              <form onSubmit={handleSendMessage} className="flex items-end gap-2">
                <div className="flex-1 bg-slate-50 border border-slate-200 rounded-lg p-2 focus-within:bg-white focus-within:border-indigo-500 focus-within:ring-1 focus-within:ring-indigo-500 transition-colors">
                  <textarea
                    rows="2"
                    placeholder="Write a message..."
                    value={inputText}
                    onChange={(e) => setInputText(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        handleSendMessage();
                      }
                    }}
                    className="w-full bg-transparent text-xs text-slate-900 placeholder-slate-400 resize-none outline-none"
                  />
                </div>
                <button
                  type="submit"
                  disabled={!inputText.trim()}
                  className={`h-10 px-4 rounded-lg text-xs font-medium transition-colors ${
                    inputText.trim()
                      ? 'bg-indigo-600 hover:bg-indigo-700 text-white'
                      : 'bg-slate-100 text-slate-400 cursor-not-allowed'
                  }`}
                >
                  Send
                </button>
              </form>
            </div>
          </>
        )}
      </main>

      {/* ================= COLUMN 3: CUSTOMER & LEAD DETAILS (320px) ================= */}
      {activeSession && (
        <aside className="w-80 bg-slate-50 border-l border-slate-200 flex flex-col shrink-0 overflow-y-auto p-4 space-y-4">
          
          <div className="flex items-center justify-between pb-3 border-b border-slate-200">
            <h3 className="text-xs font-semibold text-slate-900">
              Customer Details
            </h3>
            <span className="text-[10px] font-medium px-2 py-0.5 rounded-full bg-white border border-slate-200 text-slate-600">
              Inbound Record
            </span>
          </div>

          {/* Service Inquiry */}
          <div className="p-3 bg-white border border-slate-200 rounded-lg space-y-2">
            <span className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider">
              Service Requested
            </span>
            <div className="text-xs font-semibold text-slate-900">
              {activeSession.serviceRequested || 'General Exploration'}
            </div>

            {activeSession.collectedData && Object.keys(activeSession.collectedData).length > 0 && (
              <div className="space-y-1 pt-2 border-t border-slate-100">
                <span className="text-[10px] font-medium text-slate-400 uppercase tracking-wider">Inquiry Parameters:</span>
                {Object.entries(activeSession.collectedData).map(([k, v]) => (
                  <div key={k} className="flex items-start justify-between text-xs py-0.5">
                    <span className="text-slate-500 capitalize">{k.replace('_', ' ')}:</span>
                    <span className="font-medium text-slate-800 text-right max-w-[60%] truncate">{v}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Contact Record */}
          <div className="p-3 bg-white border border-slate-200 rounded-lg space-y-2">
            <span className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider">
              Contact Information
            </span>

            <div className="flex items-center justify-between text-xs py-1 border-b border-slate-100">
              <span className="text-slate-500">Name:</span>
              <span className="font-medium text-slate-900">{activeSession.visitorName || 'Unspecified'}</span>
            </div>

            <div className="flex items-center justify-between text-xs py-1 border-b border-slate-100">
              <span className="text-slate-500">Phone:</span>
              <div className="flex items-center gap-1.5">
                <span className="font-mono text-slate-900">{activeSession.phone || 'None'}</span>
                {activeSession.phone && (
                  <button
                    onClick={() => copyText(activeSession.phone, 'phone')}
                    className="text-[10px] text-indigo-600 hover:underline"
                  >
                    {copiedField === 'phone' ? 'Copied' : 'Copy'}
                  </button>
                )}
              </div>
            </div>

            <div className="flex items-center justify-between text-xs py-1">
              <span className="text-slate-500">Email:</span>
              <div className="flex items-center gap-1.5">
                <span className="font-mono text-slate-900">{activeSession.email || 'None'}</span>
                {activeSession.email && (
                  <button
                    onClick={() => copyText(activeSession.email, 'email')}
                    className="text-[10px] text-indigo-600 hover:underline"
                  >
                    {copiedField === 'email' ? 'Copied' : 'Copy'}
                  </button>
                )}
              </div>
            </div>
          </div>

          {/* Status Stage & Internal Notes */}
          <div className="p-3 bg-white border border-slate-200 rounded-lg space-y-3">
            <span className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider">
              Stage & Notes
            </span>

            <div>
              <label className="text-[11px] text-slate-500 font-medium block mb-1">Deal Stage:</label>
              <select
                defaultValue={activeSession.leadStatus || 'new'}
                id="lead-status-select"
                className="w-full bg-slate-50 border border-slate-200 rounded-md p-1.5 text-xs text-slate-800 outline-none focus:bg-white focus:border-indigo-500"
              >
                <option value="new">New Lead</option>
                <option value="contacted">Contacted / In Progress</option>
                <option value="proposal">Proposal Provided</option>
                <option value="booked">Won / Confirmed</option>
                <option value="closed">Closed / Archived</option>
              </select>
            </div>

            <div>
              <label className="text-[11px] text-slate-500 font-medium block mb-1">Internal Notes:</label>
              <textarea
                id="lead-notes-area"
                defaultValue={activeSession.internalNotes || ''}
                placeholder="Add private note for the team..."
                rows="3"
                className="w-full bg-slate-50 border border-slate-200 rounded-md p-1.5 text-xs text-slate-800 outline-none focus:bg-white focus:border-indigo-500 resize-none"
              />
            </div>

            <button
              onClick={() => {
                const status = document.getElementById('lead-status-select').value;
                const notes = document.getElementById('lead-notes-area').value;
                handleSaveLead({ leadStatus: status, internalNotes: notes });
              }}
              className="w-full py-1.5 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-xs font-medium transition-colors"
            >
              {saveStatus}
            </button>
          </div>

          {/* Telemetry */}
          <div className="text-[10px] text-slate-400 space-y-0.5 font-mono px-1">
            <div>Session ID: {activeSession.id}</div>
            <div>Source: {activeSession.siteId}</div>
          </div>

        </aside>
      )}

    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<OmniChatConsole />);
