'use client';

import { useState, useCallback, useEffect, useRef } from 'react';
import Link from 'next/link';
import SuccessModal from '@client/components/ui/SuccessModal';
import ConfirmModal from '@client/components/ui/ConfirmModal';
import {
  Search, Bot, CheckCircle, Clock, MessageSquare, Phone, AlertCircle,
  Download, CheckSquare, Square, X, FileSpreadsheet, ChevronDown,
  UserCheck, Trash2, ChevronLeft, ChevronRight, PhoneIncoming,
  PhoneOutgoing, Mic, PlayCircle, RotateCcw, ExternalLink,
  Zap, Globe, Mail, MessageCircle,
} from 'lucide-react';
import { toast } from 'sonner';
import {
  listConversations, updateConversation, deleteConversation,
  type Conversation,
} from '@client/api/conversations';
import { listCallLogs, type CallLog } from '@client/api/call-logs';
import { useAuth } from '@client/contexts/AuthContext';
import { usePolling, formatLastUpdated } from '@client/hooks/usePolling';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

type ActiveTab = 'conversations' | 'calls';
type ConvStatus = 'all' | 'ai' | 'human' | 'resolved';
type CallStatus = 'all' | 'completed' | 'in-progress' | 'failed' | 'missed';
type PageSize = 10 | 25 | 50;

const AGENTS = ['chat-agent-01', 'chat-agent-02', 'voice-agent-01', 'voice-agent-02'];

type TFn = (key: string, fallback: string) => string;

function makeConvStatusCfg(t: TFn) {
  return {
    ai:       { label: t('conversations.statusAI', 'AI Handling'), icon: Bot,         color: 'hsl(var(--info))',    bg: 'hsl(var(--info-bg))' },
    human:    { label: t('conversations.statusHuman', 'Needs Agent'), icon: AlertCircle, color: 'hsl(var(--warning))', bg: 'hsl(var(--warning-bg))' },
    resolved: { label: t('conversations.statusResolved', 'Resolved'), icon: CheckCircle, color: 'hsl(var(--success))', bg: 'hsl(var(--success-bg))' },
  } as const;
}


function fmtDuration(s: number): string {
  if (!s) return '—';
  const m = Math.floor(s / 60);
  const sec = s % 60;
  return m ? `${m}m ${sec}s` : `${sec}s`;
}

function fmtDate(ts: string | undefined): string {
  if (!ts) return '—';
  try { return new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); }
  catch { return '—'; }
}

function initials(name: string): string {
  return name.split(' ').map(n => n[0]).filter(Boolean).join('').slice(0, 2).toUpperCase() || '?';
}

function exportCSV(rows: string[][], headers: string[], filename: string) {
  const csv = [headers, ...rows].map(r => r.map(v => `"${String(v ?? '').replace(/"/g, '""')}"`).join(',')).join('\n');
  const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(new Blob([csv], { type: 'text/csv' })), download: filename });
  a.click();
}

function parseTranscript(raw: string | undefined): Array<{ speaker: string; text: string }> | null {
  if (!raw) return null;
  try {
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed) && parsed.length > 0) {
      return parsed.map((t: Record<string, unknown>) => ({
        speaker: String(t.speaker ?? t.role ?? 'Unknown'),
        text: String(t.text ?? t.content ?? ''),
      }));
    }
  } catch { /* not JSON */ }
  return null;
}

const CONV_STATUS_PRIORITY: Record<string, number> = { human: 0, ai: 1, resolved: 2 };
function sortByStatus<T extends { status: string }>(list: T[]): T[] {
  return [...list].sort((a, b) => (CONV_STATUS_PRIORITY[a.status] ?? 3) - (CONV_STATUS_PRIORITY[b.status] ?? 3));
}

const channelCfg: Record<string, { label: string; icon: React.ComponentType<{ size: number; className?: string }> ; bg: string; color: string }> = {
  chat:      { label: 'Chat',      icon: MessageCircle, bg: 'hsl(var(--info-bg))',     color: 'hsl(var(--info))' },
  voice:     { label: 'Voice',     icon: Phone,         bg: 'hsl(var(--success-bg))', color: 'hsl(var(--success))' },
  whatsapp:  { label: 'WhatsApp',  icon: MessageCircle, bg: 'hsl(135,60%,92%)',        color: 'hsl(135,60%,35%)' },
  email:     { label: 'Email',     icon: Mail,          bg: 'hsl(var(--muted))',       color: 'hsl(var(--muted-foreground))' },
  sms:       { label: 'SMS',       icon: MessageSquare, bg: 'hsl(270,60%,93%)',        color: 'hsl(270,60%,45%)' },
};

function ChannelPill({ channel, size = 'sm' }: { channel: string; size?: 'xs' | 'sm' }) {
  const cfg = channelCfg[channel] ?? { label: channel, icon: Globe, bg: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' };
  const Icon = cfg.icon;
  return (
    <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full font-medium" style={{
      backgroundColor: cfg.bg, color: cfg.color,
      fontSize: size === 'xs' ? '10px' : '11px',
    }}>
      <Icon size={size === 'xs' ? 9 : 10} />
      {cfg.label}
    </span>
  );
}

function RowSkeleton() {
  return (
    <tr>
      {Array.from({ length: 6 }).map((_, i) => (
        <td key={i} className="px-4 py-3"><div className="h-3.5 rounded skeleton" style={{ width: `${60 + (i % 3) * 20}%` }} /></td>
      ))}
    </tr>
  );
}

function PaginationBar({
  page, pages, total, pageSize, onPage, onPageSize, t,
}: {
  page: number; pages: number; total: number; pageSize: PageSize;
  onPage: (p: number) => void; onPageSize: (n: PageSize) => void;
  t: TFn;
}) {
  return (
    <div className="flex items-center justify-between px-4 py-3" style={{ borderTop: '1px solid hsl(var(--border))' }}>
      <div className="flex items-center gap-2">
        <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('table.rowsPerPage', 'Rows per page:')}</span>
        {([10, 25, 50] as PageSize[]).map(n => (
          <button
            key={n}
            onClick={() => onPageSize(n)}
            className="text-xs px-2 py-1 rounded-lg font-medium transition-all"
            style={{
              backgroundColor: pageSize === n ? 'hsl(var(--primary))' : 'transparent',
              color: pageSize === n ? 'white' : 'hsl(var(--muted-foreground))',
            }}
          >{n}</button>
        ))}
      </div>
      <div className="flex items-center gap-1.5">
        <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {total === 0 ? t('table.noResults', '0 results') : `${t('table.page', 'Page')} ${page} ${t('table.of', 'of')} ${pages} · ${total} ${t('table.total', 'total')}`}
        </span>
        <button
          className="w-7 h-7 rounded-lg flex items-center justify-center transition-colors disabled:opacity-40"
          style={{ backgroundColor: 'hsl(var(--muted))' }}
          onClick={() => onPage(page - 1)} disabled={page <= 1}
          aria-label={t('table.previousPage', 'Previous page')}
        ><ChevronLeft size={14} /></button>
        <button
          className="w-7 h-7 rounded-lg flex items-center justify-center transition-colors disabled:opacity-40"
          style={{ backgroundColor: 'hsl(var(--muted))' }}
          onClick={() => onPage(page + 1)} disabled={page >= pages}
          aria-label={t('table.nextPage', 'Next page')}
        ><ChevronRight size={14} /></button>
      </div>
    </div>
  );
}

function ChatPanel({
  conv: initialConv,
  onClose,
  onUpdate,
  userEmail,
  t,
}: {
  conv: Conversation;
  onClose: () => void;
  onUpdate: (c: Conversation) => void;
  userEmail: string;
  t: TFn;
}) {
  const [conv, setConv] = useState(initialConv);
  const [msgTab, setMsgTab] = useState<'messages' | 'info' | 'actions'>('messages');
  const [actioning, setActioning] = useState<'takeover' | 'resolve' | null>(null);
  const msgEndRef = useRef<HTMLDivElement>(null);
  const isVoice = conv.channel === 'voice';

  useEffect(() => { setConv(initialConv); }, [initialConv]);
  useEffect(() => {
    msgEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [conv.id, msgTab]);

  const handleTakeOver = async () => {
    setActioning('takeover');
    try {
      const { conversation } = await updateConversation(conv.id, { status: 'human', assigned_agent: userEmail });
      setConv(conversation);
      onUpdate(conversation);
      toast.success(t('conversations.takenOver', 'Chat taken over — you are now the assigned agent'));
    } catch (err: unknown) {
      toast.error(t('common.failedPrefix', 'Failed: ') + (err as Error).message);
    } finally {
      setActioning(null);
    }
  };

  const handleResolve = async () => {
    setActioning('resolve');
    try {
      const { conversation } = await updateConversation(conv.id, { status: 'resolved' });
      setConv(conversation);
      onUpdate(conversation);
      toast.success(t('conversations.markedResolved', 'Conversation marked as resolved'));
    } catch (err: unknown) {
      toast.error(t('common.failedPrefix', 'Failed: ') + (err as Error).message);
    } finally {
      setActioning(null);
    }
  };

  const convStatusCfgT = makeConvStatusCfg(t);
  const status = (conv.status as keyof typeof convStatusCfgT) in convStatusCfgT
    ? convStatusCfgT[conv.status as keyof typeof convStatusCfgT]
    : { label: conv.status, color: 'hsl(var(--muted-foreground))', bg: 'hsl(var(--muted))', icon: MessageSquare };
  const StatusIcon = status.icon;

  return (
    <div className="fixed inset-y-0 right-0 z-50 flex flex-col" style={{ width: 'min(520px, 100vw)', backgroundColor: 'hsl(var(--surface))', borderLeft: '1px solid hsl(var(--border))', boxShadow: 'var(--shadow-xl)' }}>
      <div className="flex items-center justify-between px-5 py-4" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
        <div className="flex items-center gap-3 min-w-0">
          <div className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0" style={{ background: isVoice ? 'hsl(var(--success-bg))' : 'linear-gradient(135deg, hsl(var(--primary)), hsl(22, 89%, 36%))' }}>
            {isVoice
              ? <Phone size={18} style={{ color: 'hsl(var(--success))' }} />
              : <span className="text-sm font-bold text-white">{initials(conv.customerName)}</span>
            }
          </div>
          <div className="min-w-0">
            <p className="font-semibold text-sm truncate" style={{ color: 'hsl(var(--foreground))' }}>{conv.customerName}</p>
            <div className="flex items-center gap-1.5 mt-0.5 flex-wrap">
              <span className="text-xs px-2 py-0.5 rounded-full font-medium" style={{ backgroundColor: status.bg, color: status.color }}>
                <StatusIcon size={9} className="inline mr-0.5" />{status.label}
              </span>
              <ChannelPill channel={conv.channel} size="xs" />
            </div>
          </div>
        </div>
        <button onClick={onClose} className="w-8 h-8 rounded-lg flex items-center justify-center transition-colors shrink-0" style={{ color: 'hsl(var(--muted-foreground))' }} onMouseEnter={e => (e.currentTarget.style.backgroundColor = 'hsl(var(--muted))')} onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}>
          <X size={16} />
        </button>
      </div>

      <div className="flex gap-0 px-5 pt-3" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
        {([
          { key: 'messages', label: isVoice ? t('conversations.transcript', 'Transcript') : t('conversations.messages', 'Messages') },
          { key: 'info', label: t('conversations.info', 'Info') },
          { key: 'actions', label: t('conversations.actions', 'Actions') },
        ] as const).map(tab => (
          <button
            key={tab.key}
            onClick={() => setMsgTab(tab.key)}
            className="px-4 py-2 text-xs font-semibold transition-colors border-b-2"
            style={{
              borderColor: msgTab === tab.key ? 'hsl(var(--primary))' : 'transparent',
              color: msgTab === tab.key ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))',
            }}
          >{tab.label}</button>
        ))}
      </div>

      <div className="flex-1 overflow-y-auto">
        {msgTab === 'messages' ? (
          <div className="flex flex-col gap-3 p-4">
            {conv.messages.length === 0 ? (
              <div className="text-center py-12">
                {isVoice
                  ? <Mic size={32} className="mx-auto mb-2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                  : <MessageSquare size={32} className="mx-auto mb-2" style={{ color: 'hsl(var(--muted-foreground))' }} />}
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{isVoice ? t('conversations.noTranscriptYet', 'No transcript yet') : t('conversations.noMessagesYet', 'No messages yet')}</p>
              </div>
            ) : isVoice ? (
              conv.messages.map((msg, i) => {
                const isAgent = ['ai', 'assistant', 'agent', 'system'].includes(msg.sender.toLowerCase());
                return (
                  <div key={i} className={`flex gap-2 ${isAgent ? 'flex-row' : 'flex-row-reverse'}`}>
                    <div
                      className="w-6 h-6 rounded-full flex items-center justify-center shrink-0 text-[9px] font-bold text-white"
                      style={{ background: isAgent ? 'linear-gradient(135deg, hsl(var(--info)), hsl(210,80%,40%))' : 'linear-gradient(135deg, hsl(var(--primary)), hsl(22,89%,36%))' }}
                    >
                      {isAgent ? 'AI' : 'C'}
                    </div>
                    <div
                      className="flex-1 px-3 py-2 rounded-xl text-xs leading-relaxed"
                      style={{
                        backgroundColor: isAgent ? 'hsl(var(--muted))' : 'hsl(var(--primary) / 0.1)',
                        color: 'hsl(var(--foreground))',
                        borderTopRightRadius: isAgent ? '12px' : '2px',
                        borderTopLeftRadius: isAgent ? '2px' : '12px',
                      }}
                    >
                      <span className="block text-[10px] font-semibold mb-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {isAgent ? t('conversations.agentLabel', 'Agent') : conv.customerName}
                        {msg.time ? ` · ${fmtDate(msg.time)}` : ''}
                      </span>
                      {msg.text}
                    </div>
                  </div>
                );
              })
            ) : (
              conv.messages.map((msg, i) => {
                const isUser = ['user', 'customer'].includes(msg.sender.toLowerCase());
                return (
                  <div key={i} className={`flex gap-2 ${isUser ? 'flex-row-reverse' : 'flex-row'}`}>
                    <div
                      className="w-7 h-7 rounded-full flex items-center justify-center shrink-0 text-xs font-bold text-white"
                      style={{ background: isUser ? 'linear-gradient(135deg, hsl(var(--primary)), hsl(22,89%,36%))' : 'linear-gradient(135deg, hsl(var(--info)), hsl(210,80%,40%))' }}
                    >
                      {isUser ? initials(conv.customerName) : 'AI'}
                    </div>
                    <div className="flex flex-col gap-0.5 max-w-[78%]" style={{ alignItems: isUser ? 'flex-end' : 'flex-start' }}>
                      <div
                        className="px-3 py-2 rounded-2xl text-xs leading-relaxed"
                        style={{
                          backgroundColor: isUser ? 'hsl(var(--primary))' : 'hsl(var(--muted))',
                          color: isUser ? 'white' : 'hsl(var(--foreground))',
                          borderTopRightRadius: isUser ? '4px' : '16px',
                          borderTopLeftRadius: isUser ? '16px' : '4px',
                        }}
                      >
                        {msg.text}
                      </div>
                      {msg.time && (
                        <span className="text-[10px]" style={{ color: 'hsl(var(--muted-foreground))' }}>
                          {fmtDate(msg.time)}
                        </span>
                      )}
                    </div>
                  </div>
                );
              })
            )}
            <div ref={msgEndRef} />
          </div>
        ) : msgTab === 'info' ? (
          <div className="p-4 space-y-0">
            {[
              { label: t('conversations.infoTopic', 'Topic'), value: conv.topic ?? t('conversations.topicGeneral', 'General') },
              { label: t('conversations.infoPhone', 'Phone'), value: conv.customerPhone ?? '—' },
              { label: t('conversations.infoEmail', 'Email'), value: conv.customerEmail ?? '—' },
              { label: t('conversations.infoChannel', 'Channel'), value: channelCfg[conv.channel]?.label ?? conv.channel },
              { label: t('conversations.infoAssignedAgent', 'Assigned Agent'), value: conv.assignedAgent ?? t('conversations.none', 'None') },
              ...(isVoice ? [] : [{ label: t('conversations.infoUnread', 'Unread Messages'), value: String(conv.unreadCount) }]),
              { label: t('conversations.infoStarted', 'Started'), value: fmtDate(conv.createdAt) },
              { label: t('conversations.infoLastActivity', 'Last Activity'), value: fmtDate(conv.updatedAt) },
            ].map(({ label, value }) => (
              <div key={label} className="flex items-start justify-between gap-4 py-2" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                <span className="text-xs font-medium shrink-0" style={{ color: 'hsl(var(--muted-foreground))' }}>{label}</span>
                <span className="text-xs text-right" style={{ color: 'hsl(var(--foreground))' }}>{value}</span>
              </div>
            ))}
            <div className="flex items-start justify-between gap-4 py-2">
              <span className="text-xs font-medium shrink-0" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.aiConfidence', 'AI Confidence')}</span>
              {conv.aiConfidence != null ? (
                <div className="flex items-center gap-2">
                  <div className="w-24 h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'hsl(var(--border))' }}>
                    <div
                      className="h-full rounded-full transition-all"
                      style={{
                        width: `${conv.aiConfidence}%`,
                        backgroundColor: conv.aiConfidence >= 70 ? 'hsl(var(--success))' : conv.aiConfidence >= 40 ? 'hsl(var(--warning))' : 'hsl(var(--danger))',
                      }}
                    />
                  </div>
                  <span className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{conv.aiConfidence}%</span>
                </div>
              ) : (
                <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>—</span>
              )}
            </div>
          </div>
        ) : (
          <div className="p-5 space-y-3">
            {conv.status !== 'resolved' && (
              <div className="rounded-xl p-4 space-y-3" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.agentActions', 'Agent Actions')}</p>
                {(conv.status === 'ai' || conv.status === 'human') && (
                  <button
                    onClick={handleTakeOver}
                    disabled={!!actioning}
                    className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold transition-all"
                    style={{
                      backgroundColor: conv.status === 'human' ? 'hsl(var(--warning))' : 'hsl(var(--primary))',
                      color: 'white',
                      opacity: actioning ? 0.6 : 1,
                    }}
                  >
                    <Zap size={15} />
                    {actioning === 'takeover' ? t('conversations.takingOver', 'Taking over…') : conv.status === 'human' ? t('conversations.assignToMe', 'Assign to Me') : t('conversations.takeOverFromAI', 'Take Over from AI')}
                  </button>
                )}
                <button
                  onClick={handleResolve}
                  disabled={!!actioning}
                  className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold transition-all border"
                  style={{
                    backgroundColor: 'transparent',
                    color: 'hsl(var(--success))',
                    borderColor: 'hsl(var(--success))',
                    opacity: actioning ? 0.6 : 1,
                  }}
                >
                  <CheckCircle size={15} />
                  {actioning === 'resolve' ? t('conversations.resolving', 'Resolving…') : t('conversations.markAsResolved', 'Mark as Resolved')}
                </button>
              </div>
            )}
            {conv.status === 'resolved' && (
              <div className="rounded-xl p-4 text-center" style={{ backgroundColor: 'hsl(var(--success-bg))', border: '1px solid hsl(var(--success) / 0.2)' }}>
                <CheckCircle size={20} className="mx-auto mb-1.5" style={{ color: 'hsl(var(--success))' }} />
                <p className="text-sm font-semibold" style={{ color: 'hsl(var(--success))' }}>{t('conversations.statusResolved', 'Resolved')}</p>
                <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.conversationClosed', 'This conversation has been closed')}</p>
              </div>
            )}
            <div className="rounded-xl overflow-hidden" style={{ border: '1px solid hsl(var(--border))' }}>
              <Link
                href={`/conversations/${conv.id}`}
                className="flex items-center justify-between px-4 py-3 text-sm font-medium transition-colors"
                style={{ color: 'hsl(var(--foreground))', backgroundColor: 'hsl(var(--surface))' }}
                onMouseEnter={e => (e.currentTarget.style.backgroundColor = 'hsl(var(--muted))')}
                onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'hsl(var(--surface))')}
              >
                <span>{t('conversations.openFull', 'Open full conversation')}</span>
                <ExternalLink size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
              </Link>
            </div>
          </div>
        )}
      </div>

      <div className="px-5 py-3.5 flex items-center justify-between" style={{ borderTop: '1px solid hsl(var(--border))' }}>
        <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {conv.messages.length} message{conv.messages.length !== 1 ? 's' : ''}
        </span>
        <Link
          href={`/conversations/${conv.id}`}
          className="flex items-center gap-1.5 text-xs font-semibold"
          style={{ color: 'hsl(var(--primary))' }}
        >
          {t('conversations.fullView', 'Full view')} <ExternalLink size={11} />
        </Link>
      </div>
    </div>
  );
}

function CallPanel({ callLog, onClose, t }: { callLog: CallLog; onClose: () => void; t: TFn }) {
  const turns = parseTranscript(callLog.transcript);
  const isInbound = callLog.direction === 'inbound';

  return (
    <div className="fixed inset-y-0 right-0 z-50 flex flex-col" style={{ width: 'min(520px, 100vw)', backgroundColor: 'hsl(var(--surface))', borderLeft: '1px solid hsl(var(--border))', boxShadow: 'var(--shadow-xl)' }}>
      <div className="flex items-center justify-between px-5 py-4" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
        <div className="flex items-center gap-3 min-w-0">
          <div className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0" style={{ backgroundColor: isInbound ? 'hsl(var(--success-bg))' : 'hsl(var(--info-bg))' }}>
            {isInbound ? <PhoneIncoming size={18} style={{ color: 'hsl(var(--success))' }} /> : <PhoneOutgoing size={18} style={{ color: 'hsl(var(--info))' }} />}
          </div>
          <div className="min-w-0">
            <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>
              {callLog.customerName ?? (isInbound ? callLog.fromNumber : callLog.toNumber) ?? 'Unknown Caller'}
            </p>
            <div className="flex items-center gap-1.5 mt-0.5">
              <span className="text-xs px-2 py-0.5 rounded-full font-medium capitalize" style={{
                backgroundColor: isInbound ? 'hsl(var(--success-bg))' : 'hsl(var(--info-bg))',
                color: isInbound ? 'hsl(var(--success))' : 'hsl(var(--info))',
              }}>
                {callLog.direction}
              </span>
              <ChannelPill channel="voice" size="xs" />
              <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{fmtDate(callLog.createdAt)}</span>
            </div>
          </div>
        </div>
        <button onClick={onClose} className="w-8 h-8 rounded-lg flex items-center justify-center transition-colors shrink-0" style={{ color: 'hsl(var(--muted-foreground))' }} onMouseEnter={e => (e.currentTarget.style.backgroundColor = 'hsl(var(--muted))')} onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}>
          <X size={16} />
        </button>
      </div>

      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {(callLog.customerName || callLog.customerPhone || callLog.customerEmail) && (
          <div className="rounded-xl p-3 flex items-center gap-3" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
            <div className="w-9 h-9 rounded-full flex items-center justify-center text-white text-xs font-bold shrink-0" style={{ background: 'linear-gradient(135deg, hsl(var(--primary)), hsl(22,89%,36%))' }}>
              {callLog.customerName ? initials(callLog.customerName) : '?'}
            </div>
            <div className="min-w-0">
              {callLog.customerName && <p className="text-sm font-semibold truncate" style={{ color: 'hsl(var(--foreground))' }}>{callLog.customerName}</p>}
              {callLog.customerPhone && <p className="text-xs font-mono truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>{callLog.customerPhone}</p>}
              {callLog.customerEmail && <p className="text-xs truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>{callLog.customerEmail}</p>}
            </div>
          </div>
        )}

        <div className="grid grid-cols-2 gap-3">
          {[
            { label: t('calls.duration', 'Duration'), value: fmtDuration(callLog.durationSeconds) },
            { label: t('common.status', 'Status'), value: callLog.status },
            { label: t('calls.from', 'From'), value: callLog.fromNumber ?? '—' },
            { label: t('calls.to', 'To'), value: callLog.toNumber ?? '—' },
            { label: t('calls.aiHandled', 'AI Handled'), value: callLog.aiHandled ? t('common.yes', 'Yes') : t('common.no', 'No') },
            { label: t('calls.escalated', 'Escalated'), value: callLog.escalatedToHuman ? t('common.yes', 'Yes') : t('common.no', 'No') },
          ].map(({ label, value }) => (
            <div key={label} className="rounded-xl p-3" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              <p className="text-[10px] font-medium mb-1 uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))' }}>{label}</p>
              <p className="text-sm font-semibold capitalize" style={{ color: 'hsl(var(--foreground))' }}>{value}</p>
            </div>
          ))}
        </div>

        {callLog.escalationReason && (
          <div className="rounded-xl p-3" style={{ backgroundColor: 'hsl(var(--warning-bg))', border: '1px solid hsl(var(--warning) / 0.2)' }}>
            <p className="text-xs font-medium mb-1" style={{ color: 'hsl(var(--warning))' }}>{t('calls.escalationReason', 'Escalation Reason')}</p>
            <p className="text-xs" style={{ color: 'hsl(var(--foreground))' }}>{callLog.escalationReason}</p>
          </div>
        )}

        {callLog.recordingUrl && (
          <div className="rounded-xl p-3" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
            <div className="flex items-center justify-between mb-2">
              <p className="text-xs font-medium flex items-center gap-1.5" style={{ color: 'hsl(var(--foreground))' }}>
                <PlayCircle size={14} style={{ color: 'hsl(var(--primary))' }} /> {t('calls.callRecording', 'Call Recording')}
              </p>
              <a
                href={callLog.recordingUrl}
                download
                className="flex items-center gap-1 text-xs font-medium"
                style={{ color: 'hsl(var(--primary))' }}
              >
                <Download size={11} /> {t('common.download', 'Download')}
              </a>
            </div>
            <audio controls className="w-full" style={{ height: '32px' }}>
              <source src={callLog.recordingUrl} type="audio/mpeg" />
            </audio>
          </div>
        )}

        {callLog.transcript ? (
          <div>
            <p className="text-xs font-semibold mb-2 flex items-center gap-1.5" style={{ color: 'hsl(var(--foreground))' }}>
              <Mic size={13} style={{ color: 'hsl(var(--primary))' }} /> {t('conversations.transcript', 'Transcript')}
            </p>
            {turns ? (
              <div className="space-y-3">
                {turns.map((turn, i) => {
                  const isAgent = ['ai', 'assistant', 'agent'].includes(turn.speaker.toLowerCase());
                  return (
                    <div key={i} className={`flex gap-2 ${isAgent ? 'flex-row' : 'flex-row-reverse'}`}>
                      <div
                        className="w-6 h-6 rounded-full flex items-center justify-center shrink-0 text-[9px] font-bold text-white"
                        style={{ background: isAgent ? 'linear-gradient(135deg, hsl(var(--info)), hsl(210,80%,40%))' : 'linear-gradient(135deg, hsl(var(--primary)), hsl(22,89%,36%))' }}
                      >
                        {isAgent ? 'AI' : 'C'}
                      </div>
                      <div
                        className="flex-1 px-3 py-2 rounded-xl text-xs leading-relaxed"
                        style={{
                          backgroundColor: isAgent ? 'hsl(var(--muted))' : 'hsl(var(--primary) / 0.1)',
                          color: 'hsl(var(--foreground))',
                          borderTopRightRadius: isAgent ? '12px' : '2px',
                          borderTopLeftRadius: isAgent ? '2px' : '12px',
                        }}
                      >
                        <span className="block text-[10px] font-semibold mb-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{turn.speaker}</span>
                        {turn.text}
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="space-y-2">
                {callLog.transcript.split('\n').filter(l => l.trim()).map((line, i) => {
                  const speakerMatch = line.match(/^(AI|Agent|Customer|User|Caller|System)\s*:\s*(.*)/i);
                  const speaker = speakerMatch ? speakerMatch[1] : (i % 2 === 0 ? 'Agent' : 'Customer');
                  const text = speakerMatch ? speakerMatch[2] : line;
                  const isAgent = ['ai', 'agent', 'system'].includes(speaker.toLowerCase());
                  return (
                    <div key={i} className={`flex gap-2 ${isAgent ? 'flex-row' : 'flex-row-reverse'}`}>
                      <div className="w-6 h-6 rounded-full flex items-center justify-center shrink-0 text-[9px] font-bold text-white"
                        style={{ background: isAgent ? 'linear-gradient(135deg, hsl(var(--info)), hsl(210,80%,40%))' : 'linear-gradient(135deg, hsl(var(--primary)), hsl(22,89%,36%))' }}>
                        {isAgent ? 'AI' : 'C'}
                      </div>
                      <div className="flex-1 px-3 py-2 rounded-xl text-xs leading-relaxed"
                        style={{ backgroundColor: isAgent ? 'hsl(var(--muted))' : 'hsl(var(--primary) / 0.1)', color: 'hsl(var(--foreground))', borderTopRightRadius: isAgent ? '12px' : '2px', borderTopLeftRadius: isAgent ? '2px' : '12px' }}>
                        <span className="block text-[10px] font-semibold mb-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{speaker}</span>
                        {text}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        ) : (
          <div className="text-center py-8">
            <Mic size={28} className="mx-auto mb-2" style={{ color: 'hsl(var(--muted-foreground))' }} />
            <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.noTranscriptAvailable', 'No transcript available')}</p>
          </div>
        )}

        {callLog.conversationTopic && (
          <div className="rounded-xl p-3" style={{ backgroundColor: 'hsl(var(--muted))' }}>
            <p className="text-[10px] font-medium mb-1 uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.infoTopic', 'Topic')}</p>
            <p className="text-xs font-medium" style={{ color: 'hsl(var(--foreground))' }}>{callLog.conversationTopic}</p>
          </div>
        )}
      </div>

      {callLog.conversationId && (
        <div className="px-5 py-4 flex items-center justify-end" style={{ borderTop: '1px solid hsl(var(--border))' }}>
          <Link
            href={`/conversations/${callLog.conversationId}`}
            className="flex items-center gap-1.5 text-xs font-semibold"
            style={{ color: 'hsl(var(--primary))' }}
          >
            {t('calls.viewLinkedConversation', 'View linked conversation')} <ExternalLink size={12} />
          </Link>
        </div>
      )}
    </div>
  );
}

export default function ConversationsPage() {
  const { t } = useLanguage();
  usePageHeader(t('nav.conversations', 'Conversations'), t('nav.conversationsSubtitle', 'Manage AI and human-handled customer conversations'));
  const { restaurantId, user, userRecord } = useAuth();
  const userEmail = user?.email ?? 'agent';
  const agentName: string = userRecord?.name ?? userEmail;

  const [activeTab, setActiveTab] = useState<ActiveTab>('conversations');

  const [convList, setConvList] = useState<Conversation[]>([]);
  const [convTotal, setConvTotal] = useState(0);
  const [convPages, setConvPages] = useState(1);
  const [convPage, setConvPage] = useState(1);
  const [convPageSize, setConvPageSize] = useState<PageSize>(25);
  const [convStatus, setConvStatus] = useState<ConvStatus>('all');
  const [convChannel, setConvChannel] = useState('all');
  const [convSearch, setConvSearch] = useState('');
  const [convDateFrom, setConvDateFrom] = useState('');
  const [convDateTo, setConvDateTo] = useState('');
  const [convLoading, setConvLoading] = useState(true);

  const [convStats, setConvStats] = useState({ total: 0, ai: 0, human: 0, unread: 0 });
  const statsLoadedRef = useRef(false);

  const [callList, setCallList] = useState<CallLog[]>([]);
  const [callTotal, setCallTotal] = useState(0);
  const [callPages, setCallPages] = useState(1);
  const [callPage, setCallPage] = useState(1);
  const [callPageSize, setCallPageSize] = useState<PageSize>(25);
  const [callDirection, setCallDirection] = useState('all');
  const [callStatus, setCallStatus] = useState<CallStatus>('all');
  const [callSearch, setCallSearch] = useState('');
  const [callDateFrom, setCallDateFrom] = useState('');
  const [callDateTo, setCallDateTo] = useState('');
  const [callLoading, setCallLoading] = useState(false);
  const [callStats, setCallStats] = useState({ total: 0, inbound: 0, outbound: 0, aiHandled: 0 });
  const callStatsLoadedRef = useRef(false);

  const [chatPanel, setChatPanel] = useState<Conversation | null>(null);
  const [callPanel, setCallPanel] = useState<CallLog | null>(null);

  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [exportMenuOpen, setExportMenuOpen] = useState(false);
  const [assignMenuOpen, setAssignMenuOpen] = useState(false);
  const [statusMenuOpen, setStatusMenuOpen] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [successModal, setSuccessModal] = useState<{ open: boolean; title: string; onUndo?: () => void }>({ open: false, title: '' });
  const [lastFetched, setLastFetched] = useState<Date | null>(null);

  const loadConversations = useCallback(async (skeleton = true) => {
    if (!restaurantId) { setConvLoading(false); return; }
    if (skeleton) setConvLoading(true);
    try {
      const p: Record<string, string> = { page: String(convPage), limit: String(convPageSize) };
      if (convStatus !== 'all') p.status = convStatus;
      if (convChannel !== 'all') p.channel = convChannel;
      if (convSearch) p.search = convSearch;
      if (convDateFrom) p.start_date = convDateFrom;
      if (convDateTo) p.end_date = convDateTo;
      const r = await listConversations(p);
      setConvList(sortByStatus(r.conversations));
      setConvTotal(r.total);
      setConvPages(r.pages);
      if (skeleton) setLastFetched(new Date());
    } catch (err: unknown) {
      if (skeleton) toast.error(t('conversations.failedToLoad', 'Failed to load conversations: ') + (err as Error).message);
    } finally {
      setConvLoading(false);
    }
  }, [restaurantId, convPage, convPageSize, convStatus, convChannel, convSearch, convDateFrom, convDateTo]);

  const loadStats = useCallback(async () => {
    if (!restaurantId || statsLoadedRef.current) return;
    statsLoadedRef.current = true;
    try {
      const r = await listConversations({ limit: '200' });
      const all = r.conversations;
      setConvStats({
        total: r.total,
        ai: all.filter(c => c.status === 'ai').length,
        human: all.filter(c => c.status === 'human').length,
        unread: all.reduce((s, c) => s + c.unreadCount, 0),
      });
    } catch { /* ignore */ }
  }, [restaurantId]);

  const loadCallStats = useCallback(async () => {
    if (!restaurantId || callStatsLoadedRef.current) return;
    callStatsLoadedRef.current = true;
    try {
      const r = await listCallLogs({ limit: '200' });
      const all = r.callLogs;
      setCallStats({
        total: r.total,
        inbound: all.filter(c => c.direction === 'inbound').length,
        outbound: all.filter(c => c.direction === 'outbound').length,
        aiHandled: all.filter(c => c.aiHandled).length,
      });
    } catch { /* ignore */ }
  }, [restaurantId]);

  const loadCalls = useCallback(async (skeleton = true) => {
    if (!restaurantId) { setCallLoading(false); return; }
    if (skeleton) setCallLoading(true);
    try {
      const p: Record<string, string> = { page: String(callPage), limit: String(callPageSize) };
      if (callDirection !== 'all') p.direction = callDirection;
      if (callStatus !== 'all') p.status = callStatus;
      if (callSearch) p.search = callSearch;
      if (callDateFrom) p.date_from = callDateFrom;
      if (callDateTo) p.date_to = callDateTo;
      const r = await listCallLogs(p);
      setCallList(r.callLogs);
      setCallTotal(r.total);
      setCallPages(r.pages);
    } catch (err: unknown) {
      if (skeleton) toast.error(t('calls.failedToLoad', 'Failed to load calls: ') + (err as Error).message);
    } finally {
      setCallLoading(false);
    }
  }, [restaurantId, callPage, callPageSize, callDirection, callStatus, callSearch, callDateFrom, callDateTo]);

  useEffect(() => {
    if (restaurantId) { loadConversations(); loadStats(); }
  // loadStats has its own ref-guard; loadConversations captures all filter deps
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loadConversations]);

  useEffect(() => {
    if (restaurantId && activeTab === 'calls') { loadCalls(); loadCallStats(); }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loadCalls, activeTab]);

  const silentPoll = useCallback(async () => {
    if (activeTab === 'conversations') await loadConversations(false);
    else await loadCalls(false);
  }, [activeTab, loadConversations, loadCalls]);

  const { lastUpdated, trigger: manualRefresh } = usePolling(silentPoll, { intervalMs: 10000, enabled: !!restaurantId, runOnMount: false });

  const displayLastUpdated = lastUpdated && lastFetched
    ? (lastUpdated > lastFetched ? lastUpdated : lastFetched)
    : (lastUpdated ?? lastFetched);

  const handleConvStatus = (s: ConvStatus) => { setConvStatus(s); setConvPage(1); };
  const handleConvChannel = (c: string) => { setConvChannel(c); setConvPage(1); };
  const handleConvSearch = (s: string) => { setConvSearch(s); setConvPage(1); };
  const handleCallDir = (d: string) => { setCallDirection(d); setCallPage(1); };
  const handleCallStatus = (s: CallStatus) => { setCallStatus(s); setCallPage(1); };
  const handleCallSearch = (s: string) => { setCallSearch(s); setCallPage(1); };

  const toggleRow = (id: string) => setSelectedIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  const toggleAll = () => setSelectedIds(selectedIds.length === convList.length && convList.length > 0 ? [] : convList.map(c => c.id));

  const handleBulkUpdateStatus = async (newStatus: 'resolved' | 'human') => {
    const snapshot = [...convList];
    try {
      await Promise.all(selectedIds.map(id => updateConversation(id, { status: newStatus })));
      setConvList(prev => prev.map(c => selectedIds.includes(c.id) ? { ...c, status: newStatus } : c));
      const count = selectedIds.length;
      setSelectedIds([]); setStatusMenuOpen(false);
      setSuccessModal({
        open: true,
        title: newStatus === 'resolved'
          ? t('conversations.bulkResolved', `${count} conversation${count > 1 ? 's' : ''} marked as resolved`)
          : t('conversations.bulkEscalated', `${count} conversation${count > 1 ? 's' : ''} escalated to human`),
        onUndo: () => { setConvList(snapshot); toast.success(t('common.undone', 'Undone')); },
      });
    } catch (err: unknown) { toast.error(t('common.failed', 'Failed') + ': ' + (err as Error).message); }
  };

  const handleBulkAssign = async (agent: string) => {
    const snapshot = [...convList];
    try {
      await Promise.all(selectedIds.map(id => updateConversation(id, { assigned_agent: agent })));
      setConvList(prev => prev.map(c => selectedIds.includes(c.id) ? { ...c, assignedAgent: agent } : c));
      const count = selectedIds.length;
      setSelectedIds([]); setAssignMenuOpen(false);
      setSuccessModal({ open: true, title: t('conversations.bulkAssigned', `${count} conversation${count > 1 ? 's' : ''} assigned to ${agent}`), onUndo: () => setConvList(snapshot) });
    } catch (err: unknown) { toast.error(t('common.failed', 'Failed') + ': ' + (err as Error).message); }
  };

  const handleBulkDelete = async () => {
    const snapshot = [...convList];
    try {
      await Promise.all(selectedIds.map(id => deleteConversation(id)));
      setConvList(prev => prev.filter(c => !selectedIds.includes(c.id)));
      const count = selectedIds.length;
      setSelectedIds([]); setConfirmDelete(false);
      setSuccessModal({ open: true, title: t('conversations.bulkDeleted', `${count} conversation${count > 1 ? 's' : ''} deleted`), onUndo: () => setConvList(snapshot) });
    } catch (err: unknown) { toast.error(t('common.failed', 'Failed') + ': ' + (err as Error).message); }
  };

  const handleExportConvCSV = () => {
    const data = selectedIds.length > 0 ? convList.filter(c => selectedIds.includes(c.id)) : convList;
    exportCSV(
      data.map(c => [c.id, c.customerName, c.channel, c.status, c.topic ?? '', String(c.unreadCount), String(c.aiConfidence ?? ''), c.createdAt]),
      ['ID', 'Customer', 'Channel', 'Status', 'Topic', 'Unread', 'AI Confidence', 'Created'],
      `conversations-${new Date().toISOString().slice(0, 10)}.csv`
    );
    setExportMenuOpen(false);
    toast.success(t('conversations.exported', `Exported ${data.length} conversations`));
  };

  const handleExportCallCSV = () => {
    exportCSV(
      callList.map(c => [c.id, c.customerName ?? '', c.direction, c.fromNumber ?? '', c.toNumber ?? '', String(c.durationSeconds), c.status, c.createdAt]),
      ['ID', 'Customer', 'Direction', 'From', 'To', 'Duration (s)', 'Status', 'Created'],
      `calls-${new Date().toISOString().slice(0, 10)}.csv`
    );
    toast.success(t('calls.exported', `Exported ${callList.length} call logs`));
  };

  return (
    <>
      {(chatPanel || callPanel) && (
        <div
          className="fixed inset-0 z-40"
          style={{ backgroundColor: 'rgba(0,0,0,0.2)' }}
          onClick={() => { setChatPanel(null); setCallPanel(null); }}
        />
      )}
      {chatPanel && (
        <ChatPanel
          conv={chatPanel}
          onClose={() => setChatPanel(null)}
          userEmail={agentName}
          t={t}
          onUpdate={updated => {
            setConvList(prev => sortByStatus(prev.map(c => c.id === updated.id ? updated : c)));
            setChatPanel(updated);
          }}
        />
      )}
      {callPanel && <CallPanel callLog={callPanel} onClose={() => setCallPanel(null)} t={t} />}

      {(() => {
        const TEN_MIN = 10 * 60 * 1000;
        const recentHuman = convList.filter(c =>
          c.status === 'human' && (Date.now() - new Date(c.updatedAt).getTime()) < TEN_MIN
        );
        return activeTab === 'conversations' && recentHuman.length > 0 ? (
          <div className="sticky top-0 z-30 flex items-center gap-3 px-4 py-3 rounded-xl mb-4" style={{ backgroundColor: 'hsl(var(--warning) / 0.12)', border: '1px solid hsl(var(--warning) / 0.35)', backdropFilter: 'blur(8px)' }}>
            <span className="relative flex-shrink-0">
              <span className="w-2.5 h-2.5 rounded-full block" style={{ backgroundColor: 'hsl(var(--warning))' }} />
              <span className="absolute inset-0 rounded-full animate-ping" style={{ backgroundColor: 'hsl(var(--warning))', opacity: 0.5 }} />
            </span>
            <div className="flex-1 min-w-0">
              <span className="text-sm font-semibold" style={{ color: 'hsl(var(--warning))' }}>
                {t('conversations.needsAgentBanner', 'Needs Agent')} — {recentHuman.length} {recentHuman.length === 1 ? t('conversations.conversationSingular', 'conversation') : t('conversations.conversationPlural', 'conversations')} {recentHuman.length === 1 ? t('conversations.awaits', 'awaits') : t('conversations.await', 'await')} {t('conversations.humanAssistance', 'human assistance')}
              </span>
              <span className="ml-2 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.bannerHint', 'Click "Take Over" to assign yourself or "Assign Me" to assist')}</span>
            </div>
          </div>
        ) : null;
      })()}

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
        {[
          { label: activeTab === 'conversations' ? t('conversations.totalConversations', 'Total Conversations') : t('calls.totalCalls', 'Total Calls'), value: activeTab === 'conversations' ? convStats.total : callStats.total, icon: activeTab === 'conversations' ? MessageSquare : Phone, color: 'hsl(var(--primary))' },
          { label: activeTab === 'conversations' ? t('conversations.statusAI', 'AI Handling') : t('calls.inbound', 'Inbound'), value: activeTab === 'conversations' ? convStats.ai : callStats.inbound, icon: activeTab === 'conversations' ? Bot : PhoneIncoming, color: 'hsl(var(--info))' },
          { label: activeTab === 'conversations' ? t('conversations.needAgent', 'Need Agent') : t('calls.outbound', 'Outbound'), value: activeTab === 'conversations' ? convStats.human : callStats.outbound, icon: activeTab === 'conversations' ? AlertCircle : PhoneOutgoing, color: 'hsl(var(--warning))' },
          { label: activeTab === 'conversations' ? t('conversations.unread', 'Unread') : t('conversations.statusAI', 'AI Handled'), value: activeTab === 'conversations' ? convStats.unread : callStats.aiHandled, icon: activeTab === 'conversations' ? Clock : Bot, color: 'hsl(var(--danger))' },
        ].map(stat => {
          const Icon = stat.icon;
          return (
            <div key={stat.label} className="card p-4 flex items-center gap-3">
              <div className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0" style={{ backgroundColor: stat.color + '18' }}>
                <Icon size={18} style={{ color: stat.color }} />
              </div>
              <div>
                <p className="text-xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>{stat.value}</p>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{stat.label}</p>
              </div>
            </div>
          );
        })}
      </div>

      <div className="flex items-center gap-0 mb-4 p-1 rounded-xl self-start" style={{ backgroundColor: 'hsl(var(--muted))', width: 'fit-content' }}>
        {([
          { key: 'conversations', label: t('nav.conversations', 'Conversations'), icon: MessageSquare },
          { key: 'calls', label: t('calls.callLogs', 'Call Logs'), icon: Phone },
        ] as { key: ActiveTab; label: string; icon: React.ComponentType<{ size: number; style?: React.CSSProperties }> }[]).map(tab => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key)}
            className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-semibold transition-all"
            style={{
              backgroundColor: activeTab === tab.key ? 'hsl(var(--surface))' : 'transparent',
              color: activeTab === tab.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))',
              boxShadow: activeTab === tab.key ? 'var(--shadow-sm)' : 'none',
            }}
          >
            <tab.icon size={14} style={{ color: activeTab === tab.key ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))' }} />
            {tab.label}
            <span className="text-xs px-1.5 py-0.5 rounded-full font-bold ml-0.5" style={{
              backgroundColor: activeTab === tab.key ? 'hsl(var(--primary))' : 'hsl(var(--border))',
              color: activeTab === tab.key ? 'white' : 'hsl(var(--muted-foreground))',
            }}>
              {tab.key === 'conversations' ? convTotal : callTotal}
            </span>
          </button>
        ))}
      </div>

      <div className="flex flex-wrap gap-3 mb-4">
        <div className="relative flex-1 min-w-[200px] max-w-xs">
          <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
          <input
            className="input-base pl-9"
            placeholder={activeTab === 'conversations' ? t('conversations.searchPlaceholder', 'Search by name, topic or phone…') : t('calls.searchPlaceholder', 'Search by name or number…')}
            value={activeTab === 'conversations' ? convSearch : callSearch}
            onChange={e => activeTab === 'conversations' ? handleConvSearch(e.target.value) : handleCallSearch(e.target.value)}
          />
        </div>

        {activeTab === 'conversations' && (
          <>
            <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              {(['all', 'chat', 'voice'] as const).map(ch => (
                <button key={ch} onClick={() => handleConvChannel(ch)}
                  className={`flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${convChannel === ch ? 'bg-white shadow-sm' : ''}`}
                  style={{ color: convChannel === ch ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
                >
                  {ch === 'chat' ? <MessageSquare size={11} /> : ch === 'voice' ? <Phone size={11} /> : null}
                  {ch === 'all' ? t('common.all', 'All') : ch === 'chat' ? t('channel.chat', 'Chat') : t('channel.voice', 'Voice')}
                </button>
              ))}
            </div>
            <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              {([
                { key: 'all', label: t('common.all', 'All') },
                { key: 'ai', label: t('conversations.statusAIShort', 'AI') },
                { key: 'human', label: t('conversations.statusHuman', 'Needs Agent') },
                { key: 'resolved', label: t('conversations.statusResolved', 'Resolved') },
              ] as { key: ConvStatus; label: string }[]).map(f => (
                <button key={f.key} onClick={() => handleConvStatus(f.key)}
                  className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${convStatus === f.key ? 'bg-white shadow-sm' : ''}`}
                  style={{ color: convStatus === f.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
                >{f.label}</button>
              ))}
            </div>
          </>
        )}

        {activeTab === 'calls' && (
          <>
            <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              {(['all', 'inbound', 'outbound'] as const).map(d => (
                <button key={d} onClick={() => handleCallDir(d)}
                  className={`flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${callDirection === d ? 'bg-white shadow-sm' : ''}`}
                  style={{ color: callDirection === d ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
                >
                  {d === 'inbound' ? <PhoneIncoming size={11} /> : d === 'outbound' ? <PhoneOutgoing size={11} /> : null}
                  {d === 'all' ? t('common.all', 'All') : d === 'inbound' ? t('calls.inbound', 'Inbound') : t('calls.outbound', 'Outbound')}
                </button>
              ))}
            </div>
            <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              {([
                { key: 'all', label: t('common.all', 'All') },
                { key: 'completed', label: t('calls.completed', 'Completed') },
                { key: 'in-progress', label: t('calls.inProgress', 'In Progress') },
                { key: 'failed', label: t('calls.failed', 'Failed') },
                { key: 'missed', label: t('calls.missed', 'Missed') },
              ] as { key: CallStatus; label: string }[]).map(f => (
                <button key={f.key} onClick={() => handleCallStatus(f.key)}
                  className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${callStatus === f.key ? 'bg-white shadow-sm' : ''}`}
                  style={{ color: callStatus === f.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
                >{f.label}</button>
              ))}
            </div>
          </>
        )}

        <div className="flex items-center gap-2">
          <input
            type="date"
            className="input-base text-xs py-1.5"
            style={{ width: '130px' }}
            value={activeTab === 'conversations' ? convDateFrom : callDateFrom}
            onChange={e => activeTab === 'conversations' ? (setConvDateFrom(e.target.value), setConvPage(1)) : (setCallDateFrom(e.target.value), setCallPage(1))}
            title={t('conversations.dateFrom', 'Date from')}
          />
          <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.to', 'to')}</span>
          <input
            type="date"
            className="input-base text-xs py-1.5"
            style={{ width: '130px' }}
            value={activeTab === 'conversations' ? convDateTo : callDateTo}
            onChange={e => activeTab === 'conversations' ? (setConvDateTo(e.target.value), setConvPage(1)) : (setCallDateTo(e.target.value), setCallPage(1))}
            title={t('conversations.dateTo', 'Date to')}
          />
        </div>

        <div className="flex items-center gap-2 ml-auto">
          {displayLastUpdated && (
            <div className="flex items-center gap-1.5">
              <span className="w-1.5 h-1.5 rounded-full shrink-0" style={{ backgroundColor: 'hsl(var(--success))', animation: 'pulse 2s infinite' }} />
              <span className="text-xs whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>{formatLastUpdated(displayLastUpdated)}</span>
            </div>
          )}
          <button className="btn-secondary" onClick={manualRefresh}>
            <RotateCcw size={14} /> {t('common.refresh', 'Refresh')}
          </button>
          {activeTab === 'conversations' ? (
            <div className="relative">
              <button onClick={() => setExportMenuOpen(v => !v)} className="btn-secondary text-xs flex items-center gap-1.5">
                <Download size={14} /> {t('common.export', 'Export')} <ChevronDown size={12} />
              </button>
              {exportMenuOpen && (
                <div className="absolute right-0 top-full mt-1.5 w-48 rounded-xl shadow-lg z-30 overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                  <button onClick={handleExportConvCSV} className="w-full flex items-center gap-2.5 px-4 py-2.5 text-xs font-medium transition-colors text-left" style={{ color: 'hsl(var(--foreground))' }} onMouseEnter={e => (e.currentTarget.style.backgroundColor = 'hsl(var(--muted))')} onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}>
                    <FileSpreadsheet size={14} style={{ color: 'hsl(var(--success))' }} /> {t('common.exportCSV', 'Export as CSV')}
                    {selectedIds.length > 0 && <span className="ml-auto opacity-60">({selectedIds.length})</span>}
                  </button>
                </div>
              )}
            </div>
          ) : (
            <button className="btn-secondary text-xs flex items-center gap-1.5" onClick={handleExportCallCSV}>
              <Download size={14} /> {t('common.exportCSV', 'Export CSV')}
            </button>
          )}
        </div>
      </div>

      <div className="card overflow-hidden">
        {activeTab === 'conversations' ? (
          <>
            <div className="overflow-x-auto">
              <table className="w-full text-xs">
                <thead>
                  <tr style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
                    <th className="px-4 py-3 text-left w-10">
                      <button onClick={toggleAll}>
                        {selectedIds.length === convList.length && convList.length > 0
                          ? <CheckSquare size={14} style={{ color: 'hsl(var(--primary))' }} />
                          : <Square size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                      </button>
                    </th>
                    {[t('conversations.colCustomer', 'Customer'), t('conversations.colChannel', 'Channel'), t('conversations.colStatus', 'Status'), t('conversations.colTopic', 'Topic'), t('conversations.colAIConf', 'AI Conf'), t('conversations.colDate', 'Date / Time'), t('conversations.colLastActivity', 'Last Activity'), ''].map(h => (
                      <th key={h} className="px-4 py-3 text-left font-semibold" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {convLoading ? (
                    Array.from({ length: 5 }).map((_, i) => <RowSkeleton key={i} />)
                  ) : convList.length === 0 ? (
                    <tr>
                      <td colSpan={9}>
                        <div className="py-16 text-center">
                          <MessageSquare size={28} className="mx-auto mb-2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                          <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('conversations.noConversationsFound', 'No conversations found')}</p>
                          <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.tryAdjustingFilters', 'Try adjusting your filters')}</p>
                        </div>
                      </td>
                    </tr>
                  ) : (
                    convList.map(conv => {
                      const _convStatusCfg = makeConvStatusCfg(t);
                      const cfg = (conv.status as keyof typeof _convStatusCfg) in _convStatusCfg
                        ? _convStatusCfg[conv.status as keyof typeof _convStatusCfg]
                        : { label: conv.status, color: 'hsl(var(--muted-foreground))', bg: 'hsl(var(--muted))', icon: MessageSquare };
                      const StatusIcon = cfg.icon;
                      const isSelected = selectedIds.includes(conv.id);
                      return (
                        <tr
                          key={conv.id}
                          className="transition-colors"
                          style={{
                            borderBottom: '1px solid hsl(var(--border))',
                            backgroundColor: isSelected ? 'hsl(var(--primary-light))' : conv.unreadCount > 0 ? 'hsl(var(--primary-light) / 0.3)' : 'transparent',
                            cursor: 'pointer',
                          }}
                        >
                          <td className="px-4 py-3">
                            <button onClick={e => { e.stopPropagation(); toggleRow(conv.id); }}>
                              {isSelected
                                ? <CheckSquare size={14} style={{ color: 'hsl(var(--primary))' }} />
                                : <Square size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                            </button>
                          </td>
                          <td
                            className="px-4 py-3"
                            onClick={() => { setChatPanel(conv); setCallPanel(null); }}
                          >
                            <div className="flex items-center gap-2.5">
                              <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold shrink-0" style={{ background: 'linear-gradient(135deg, hsl(var(--primary)), hsl(22,89%,36%))' }}>
                                {initials(conv.customerName)}
                              </div>
                              <div>
                                <span className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{conv.customerName}</span>
                                {conv.unreadCount > 0 && (
                                  <span className="ml-2 inline-flex items-center justify-center w-4 h-4 rounded-full text-white text-[10px] font-bold" style={{ backgroundColor: 'hsl(var(--danger))' }}>{conv.unreadCount}</span>
                                )}
                              </div>
                            </div>
                          </td>
                          <td className="px-4 py-3" onClick={() => { setChatPanel(conv); setCallPanel(null); }}>
                            <ChannelPill channel={conv.channel} />
                          </td>
                          <td className="px-4 py-3" onClick={() => { setChatPanel(conv); setCallPanel(null); }}>
                            <div className="flex items-center gap-1.5">
                              {conv.status === 'human' && (
                                <span className="relative flex-shrink-0 inline-flex w-2 h-2">
                                  <span className="w-2 h-2 rounded-full block" style={{ backgroundColor: 'hsl(var(--warning))' }} />
                                  <span className="absolute inset-0 rounded-full animate-ping" style={{ backgroundColor: 'hsl(var(--warning))', opacity: 0.6 }} />
                                </span>
                              )}
                              <span className="flex items-center gap-1 px-2 py-0.5 rounded-full font-medium" style={{ backgroundColor: cfg.bg, color: cfg.color, width: 'fit-content' }}>
                                <StatusIcon size={9} />{cfg.label}
                              </span>
                            </div>
                          </td>
                          <td className="px-4 py-3 max-w-[180px]" onClick={() => { setChatPanel(conv); setCallPanel(null); }}>
                            <span className="truncate block" style={{ color: 'hsl(var(--foreground))' }}>{conv.topic ?? t('conversations.topicGeneral', 'General')}</span>
                          </td>
                          <td className="px-4 py-3" onClick={() => { setChatPanel(conv); setCallPanel(null); }}>
                            <span style={{ color: conv.aiConfidence ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}>
                              {conv.aiConfidence ? `${conv.aiConfidence}%` : '—'}
                            </span>
                          </td>
                          <td className="px-4 py-3" onClick={() => { setChatPanel(conv); setCallPanel(null); }}>
                            <span className="whitespace-nowrap" style={{ color: 'hsl(var(--foreground))' }}>{fmtDate(conv.createdAt)}</span>
                          </td>
                          <td className="px-4 py-3" onClick={() => { setChatPanel(conv); setCallPanel(null); }}>
                            <span style={{ color: 'hsl(var(--muted-foreground))' }}>{fmtDate(conv.updatedAt)}</span>
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-1.5">
                              <button
                                onClick={e => { e.stopPropagation(); setChatPanel(conv); setCallPanel(null); }}
                                className="text-xs font-medium px-2.5 py-1 rounded-lg transition-colors"
                                style={{ color: 'hsl(var(--primary))', backgroundColor: 'hsl(var(--primary) / 0.08)' }}
                              >{t('common.view', 'View')}</button>
                              {(conv.status === 'ai' || conv.status === 'human') && (
                                <button
                                  onClick={async e => {
                                    e.stopPropagation();
                                    try {
                                      const { conversation: updated } = await updateConversation(conv.id, { status: 'human', assigned_agent: agentName });
                                      setConvList(prev => sortByStatus(prev.map(c => c.id === updated.id ? updated : c)));
                                      toast.success(t('conversations.takenOver', 'Chat taken over'));
                                    } catch (err: unknown) {
                                      toast.error(t('common.failedPrefix', 'Failed: ') + (err as Error).message);
                                    }
                                  }}
                                  className="text-xs font-medium px-2.5 py-1 rounded-lg transition-colors flex items-center gap-1"
                                  style={{ color: 'hsl(var(--warning))', backgroundColor: 'hsl(var(--warning) / 0.1)' }}
                                  title={conv.status === 'ai' ? t('conversations.takeOverFromAI', 'Take over from AI') : t('conversations.assignToMe', 'Assign to me')}
                                >
                                  <Zap size={11} />{conv.status === 'ai' ? t('conversations.takeOver', 'Take Over') : t('conversations.assignMe', 'Assign Me')}
                                </button>
                              )}
                            </div>
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>
            <PaginationBar page={convPage} pages={convPages} total={convTotal} pageSize={convPageSize} onPage={setConvPage} onPageSize={p => { setConvPageSize(p); setConvPage(1); }} t={t} />
          </>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full text-xs">
                <thead>
                  <tr style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
                    {[t('calls.direction', 'Direction'), t('conversations.colCustomer', 'Customer'), t('calls.from', 'From'), t('calls.to', 'To'), t('calls.duration', 'Duration'), t('common.status', 'Status'), t('calls.recording', 'Recording'), t('calls.handledBy', 'Handled By'), t('common.date', 'Date'), ''].map(h => (
                      <th key={h} className="px-4 py-3 text-left font-semibold" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {callLoading ? (
                    Array.from({ length: 5 }).map((_, i) => <RowSkeleton key={i} />)
                  ) : callList.length === 0 ? (
                    <tr>
                      <td colSpan={10}>
                        <div className="py-16 text-center">
                          <Phone size={28} className="mx-auto mb-2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                          <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('calls.noCallLogsFound', 'No call logs found')}</p>
                          <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('calls.noCallLogsSub', 'Call logs from voice interactions will appear here')}</p>
                        </div>
                      </td>
                    </tr>
                  ) : (
                    callList.map(cl => {
                      const isIn = cl.direction === 'inbound';
                      return (
                        <tr
                          key={cl.id}
                          className="transition-colors"
                          style={{ borderBottom: '1px solid hsl(var(--border))', cursor: 'pointer' }}
                          onClick={() => { setCallPanel(cl); setChatPanel(null); }}
                          onMouseEnter={e => (e.currentTarget.style.backgroundColor = 'hsl(var(--muted))')}
                          onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}
                        >
                          <td className="px-4 py-3">
                            <span className="flex items-center gap-1.5 font-medium capitalize" style={{
                              color: isIn ? 'hsl(var(--success))' : 'hsl(var(--info))',
                            }}>
                              {isIn ? <PhoneIncoming size={13} /> : <PhoneOutgoing size={13} />}
                              {cl.direction}
                            </span>
                          </td>
                          <td className="px-4 py-3">
                            <span style={{ color: 'hsl(var(--foreground))' }}>{cl.customerName ?? '—'}</span>
                          </td>
                          <td className="px-4 py-3">
                            <span className="font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>{cl.fromNumber ?? '—'}</span>
                          </td>
                          <td className="px-4 py-3">
                            <span className="font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>{cl.toNumber ?? '—'}</span>
                          </td>
                          <td className="px-4 py-3">
                            <span style={{ color: 'hsl(var(--foreground))' }}>{fmtDuration(cl.durationSeconds)}</span>
                          </td>
                          <td className="px-4 py-3">
                            <span className="px-2 py-0.5 rounded-full font-medium capitalize" style={{
                              backgroundColor: cl.status === 'completed' ? 'hsl(var(--success-bg))' : cl.escalatedToHuman ? 'hsl(var(--warning-bg))' : 'hsl(var(--muted))',
                              color: cl.status === 'completed' ? 'hsl(var(--success))' : cl.escalatedToHuman ? 'hsl(var(--warning))' : 'hsl(var(--muted-foreground))',
                            }}>{cl.status}</span>
                          </td>
                          <td className="px-4 py-3">
                            {cl.recordingUrl ? (
                              <span className="inline-flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded-full" style={{ backgroundColor: 'hsl(var(--primary) / 0.1)', color: 'hsl(var(--primary))' }}>
                                <Mic size={10} /> {t('calls.recording', 'Recording')}
                              </span>
                            ) : (
                              <span style={{ color: 'hsl(var(--border))' }}>—</span>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            {cl.escalatedToHuman ? (
                              <span className="inline-flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded-full" style={{ backgroundColor: 'hsl(var(--warning-bg))', color: 'hsl(var(--warning))' }}>
                                {t('conversations.human', 'Human')}
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded-full" style={{ backgroundColor: 'hsl(var(--info-bg))', color: 'hsl(var(--info))' }}>
                                {t('conversations.statusAIShort', 'AI')}
                              </span>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            <span style={{ color: 'hsl(var(--muted-foreground))' }}>{fmtDate(cl.createdAt)}</span>
                          </td>
                          <td className="px-4 py-3">
                            <button
                              onClick={e => { e.stopPropagation(); setCallPanel(cl); setChatPanel(null); }}
                              className="text-xs font-medium px-2.5 py-1 rounded-lg transition-colors"
                              style={{ color: 'hsl(var(--primary))', backgroundColor: 'hsl(var(--primary) / 0.08)' }}
                            >{t('common.view', 'View')}</button>
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>
            <PaginationBar page={callPage} pages={callPages} total={callTotal} pageSize={callPageSize} onPage={setCallPage} onPageSize={p => { setCallPageSize(p); setCallPage(1); }} t={t} />
          </>
        )}
      </div>

      {selectedIds.length > 0 && activeTab === 'conversations' && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 px-4 py-2.5 rounded-xl shadow-xl slide-up" style={{ backgroundColor: 'hsl(var(--accent))', border: '1px solid rgba(255,255,255,0.1)' }}>
          <span className="text-sm font-semibold text-white mr-1">{selectedIds.length} {t('common.selected', 'selected')}</span>
          <div className="w-px h-4 bg-white/20" />
          <div className="relative">
            <button onClick={() => { setStatusMenuOpen(v => !v); setAssignMenuOpen(false); }} className="flex items-center gap-1.5 text-xs font-semibold text-white/80 hover:text-white px-2 py-1 rounded-lg hover:bg-white/10 transition-colors">
              {t('conversations.changeStatus', 'Change Status')} <ChevronDown size={11} />
            </button>
            {statusMenuOpen && (
              <div className="absolute bottom-full mb-2 left-0 w-44 rounded-xl shadow-lg z-50 overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <button onClick={() => handleBulkUpdateStatus('resolved')} className="w-full text-left px-4 py-2 text-xs font-medium transition-colors" style={{ color: 'hsl(var(--foreground))' }} onMouseEnter={e => (e.currentTarget.style.backgroundColor = 'hsl(var(--muted))')} onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}>{t('conversations.markAsResolved', 'Mark as Resolved')}</button>
                <button onClick={() => handleBulkUpdateStatus('human')} className="w-full text-left px-4 py-2 text-xs font-medium transition-colors" style={{ color: 'hsl(var(--foreground))' }} onMouseEnter={e => (e.currentTarget.style.backgroundColor = 'hsl(var(--muted))')} onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}>{t('conversations.escalateToHuman', 'Escalate to Human')}</button>
              </div>
            )}
          </div>
          <div className="relative">
            <button onClick={() => { setAssignMenuOpen(v => !v); setStatusMenuOpen(false); }} className="flex items-center gap-1.5 text-xs font-semibold text-white/80 hover:text-white px-2 py-1 rounded-lg hover:bg-white/10 transition-colors">
              <UserCheck size={12} /> {t('conversations.assign', 'Assign')} <ChevronDown size={11} />
            </button>
            {assignMenuOpen && (
              <div className="absolute bottom-full mb-2 left-0 w-44 rounded-xl shadow-lg z-50 overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                {AGENTS.map(agent => (
                  <button key={agent} onClick={() => handleBulkAssign(agent)} className="w-full text-left px-4 py-2 text-xs font-medium transition-colors" style={{ color: 'hsl(var(--foreground))' }} onMouseEnter={e => (e.currentTarget.style.backgroundColor = 'hsl(var(--muted))')} onMouseLeave={e => (e.currentTarget.style.backgroundColor = 'transparent')}>{agent}</button>
                ))}
              </div>
            )}
          </div>
          <div className="w-px h-4 bg-white/20" />
          <button onClick={() => setConfirmDelete(true)} className="text-xs font-semibold px-2 py-1 rounded-lg hover:bg-white/10 transition-colors" style={{ color: 'hsl(0,84%,70%)' }}>
            <Trash2 size={12} className="inline mr-1" /> {t('common.delete', 'Delete')}
          </button>
          <button onClick={() => setSelectedIds([])} className="p-1 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-colors"><X size={14} /></button>
        </div>
      )}

      <SuccessModal isOpen={successModal.open} onClose={() => setSuccessModal(s => ({ ...s, open: false }))} title={successModal.title} onUndo={successModal.onUndo} />
      <ConfirmModal isOpen={confirmDelete} onClose={() => setConfirmDelete(false)} onConfirm={handleBulkDelete} title={t('conversations.deleteTitle', `Delete ${selectedIds.length} conversation${selectedIds.length > 1 ? 's' : ''}?`)} description={t('conversations.deleteDescription', 'This will permanently remove the selected conversations. This action cannot be undone.')} confirmLabel={t('conversations.deleteConfirmLabel', 'Delete Conversations')} variant="danger" />
    </>
  );
}
