import { useState, useEffect, useCallback } from 'react';
import api from '../lib/api';
import {
  Clock,
  Download,
  Search,
  Filter,
  MoreVertical,
  Play,
  ArrowUpRight,
  CheckCircle2,
  XCircle,
  Phone,
  FileText,
  X,
  Sparkles,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface CallLogItem {
  id: string;
  sessionId: string;
  caller: string;
  duration: number;
  status: string;
  date: string;
  tier: string;
  intent: string;
  outcomeTag: string;
  aiSummary: string;
  sentiment: string;
  recordingUrl: string | null;
}

interface RawCallLog {
  _id: string;
  sessionId: string;
  callerNumber?: string;
  durationSeconds?: number;
  status?: string;
  createdAt?: string;
  startTime?: string;
  currentTier?: string;
  resolutionStatus?: string;
  outcomeTag?: string;
  aiSummary?: string;
  sentimentScore?: number;
  recordingUrl?: string;
}

interface TranscriptTurn {
  speaker: string;
  rawTranscript: string;
  timestamp: string;
}

interface CompanyOption {
  _id: string;
  companyName: string;
}

const CallLogs = () => {
  const [logs, setLogs] = useState<CallLogItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [playingId, setPlayingId] = useState<string | null>(null);
  const [audioElement, setAudioElement] = useState<HTMLAudioElement | null>(null);
  const [dropdownOpenId, setDropdownOpenId] = useState<string | null>(null);
  const [viewTranscriptId, setViewTranscriptId] = useState<string | null>(null);
  const [transcriptData, setTranscriptData] = useState<TranscriptTurn[]>([]);
  const [transcriptLoading, setTranscriptLoading] = useState(false);

  const [companies, setCompanies] = useState<CompanyOption[]>([]);
  const [selectedCompanyId, setSelectedCompanyId] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [outcomeFilter, setOutcomeFilter] = useState<string>('all');
  const [currentPage, setCurrentPage] = useState<number>(1);
  const pageSize = 15;

  const mapRawLogs = useCallback((rawData: RawCallLog[]): CallLogItem[] => {
    return rawData.map((log) => ({
      id: log._id,
      sessionId: log.sessionId,
      caller: log.callerNumber || '+1 (555) 000-0000',
      duration: log.durationSeconds || 0,
      status: log.status || 'completed',
      date: log.createdAt || log.startTime || '',
      tier: log.currentTier || 'l1',
      intent: log.resolutionStatus || 'Voice Call',
      outcomeTag: log.outcomeTag || 'general_inquiry',
      aiSummary: log.aiSummary || '',
      sentiment:
        log.sentimentScore !== undefined
          ? log.sentimentScore > 0.2
            ? 'Positive'
            : log.sentimentScore < -0.2
            ? 'Negative'
            : 'Neutral'
          : 'Neutral',
      recordingUrl: log.recordingUrl || null,
    }));
  }, []);

  useEffect(() => {
    const fetchCompanies = async () => {
      try {
        const res = await api.get<CompanyOption[]>('/company');
        setCompanies(res.data);
        if (res.data.length > 0) setSelectedCompanyId(res.data[0]._id);
      } catch (err) {
        console.error('Failed to fetch companies', err);
      }
    };
    fetchCompanies();
  }, []);

  useEffect(() => {
    let isMounted = true;
    const load = async () => {
      try {
        const url = selectedCompanyId ? `/calls?companyId=${selectedCompanyId}` : '/calls';
        const response = await api.get<RawCallLog[]>(url);
        if (isMounted) {
          setLogs(mapRawLogs(response.data));
          setLoading(false);
        }
      } catch (error) {
        console.error('Failed to fetch call logs', error);
        if (isMounted) {
          setLogs([]);
          setLoading(false);
        }
      }
    };
    load();
    return () => {
      isMounted = false;
    };
  }, [selectedCompanyId, mapRawLogs]);

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/calls/${id}`);
      setLogs(logs.filter((log) => log.id !== id));
      setDropdownOpenId(null);
    } catch (error) {
      console.error('Failed to delete log', error);
    }
  };

  const handlePlay = (id: string, url: string | null) => {
    if (!url) return;

    if (playingId === id && audioElement) {
      audioElement.pause();
      setPlayingId(null);
      return;
    }

    if (audioElement) audioElement.pause();

    const newAudio = new Audio(url);
    newAudio.onended = () => setPlayingId(null);
    newAudio.play();
    setAudioElement(newAudio);
    setPlayingId(id);
  };

  const loadTranscript = async (sessionId: string) => {
    setViewTranscriptId(sessionId);
    setTranscriptLoading(true);
    setTranscriptData([]);
    try {
      const res = await api.get<TranscriptTurn[]>(`/calls/${sessionId}/transcript`);
      setTranscriptData(res.data);
    } catch (err) {
      console.error('Failed to fetch transcript', err);
    } finally {
      setTranscriptLoading(false);
    }
  };

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}m ${secs}s`;
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    if (Number.isNaN(date.getTime())) return 'N/A';
    return new Intl.DateTimeFormat('en-US', {
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
    }).format(date);
  };

  const formatOutcomeLabel = (tag: string) => {
    switch (tag) {
      case 'booked_appointment':
        return 'Appointment Booked';
      case 'lead_qualified':
        return 'Lead Qualified';
      case 'faq_resolved':
        return 'FAQ Resolved';
      case 'escalated_transfer':
        return 'Human Escalation';
      default:
        return 'General Inquiry';
    }
  };

  const filteredLogs = logs.filter((log) => {
    const q = searchQuery.toLowerCase();
    const callerMatches = log.caller?.toLowerCase().includes(q) ?? false;
    const sessionMatches = log.sessionId?.toLowerCase().includes(q) ?? false;
    const intentMatches = log.intent?.toLowerCase().includes(q) ?? false;
    const summaryMatches = log.aiSummary?.toLowerCase().includes(q) ?? false;
    const matchesSearch = callerMatches || sessionMatches || intentMatches || summaryMatches;
    const matchesStatus = statusFilter === 'all' || log.status === statusFilter;
    const matchesOutcome = outcomeFilter === 'all' || log.outcomeTag === outcomeFilter;
    return matchesSearch && matchesStatus && matchesOutcome;
  });

  const totalPages = Math.max(1, Math.ceil(filteredLogs.length / pageSize));
  const safePage = Math.min(currentPage, totalPages);
  const paginatedLogs = filteredLogs.slice((safePage - 1) * pageSize, safePage * pageSize);

  const activeTranscriptCall = logs.find((l) => l.sessionId === viewTranscriptId);

  const handleExportCsv = () => {
    const headers = [
      'Session ID',
      'Caller',
      'Date',
      'Duration (s)',
      'Status',
      'Outcome Tag',
      'Sentiment',
      'AI Summary',
    ];
    const rows = filteredLogs.map((log) => [
      `"${(log.sessionId || '').replace(/"/g, '""')}"`,
      `"${(log.caller || '').replace(/"/g, '""')}"`,
      `"${log.date ? new Date(log.date).toISOString() : ''}"`,
      String(log.duration || 0),
      `"${log.status}"`,
      `"${log.outcomeTag}"`,
      `"${log.sentiment}"`,
      `"${(log.aiSummary || log.intent || '').replace(/"/g, '""')}"`,
    ]);
    const csvContent = [headers.join(','), ...rows.map((r) => r.join(','))].join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `call-logs-${selectedCompanyId || 'all'}-${new Date().toISOString().slice(0, 10)}.csv`;
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-6 pb-12">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight">Call Analytics & Summaries</h1>
          <p className="mt-1 text-sm text-slate-400">
            Review AI-generated call summaries, outcome tags, sentiment scores, and full transcripts.
          </p>
        </div>
        <div className="flex gap-3 flex-wrap">
          <select
            value={selectedCompanyId}
            onChange={(e) => {
              setSelectedCompanyId(e.target.value);
              setCurrentPage(1);
            }}
            aria-label="Filter by organization"
            className="px-4 py-2 bg-slate-900 border border-slate-700 rounded-xl text-sm font-medium text-slate-200 transition-colors focus:ring-2 focus:ring-indigo-500 outline-none"
          >
            {companies.map((c) => (
              <option key={c._id} value={c._id}>
                {c.companyName}
              </option>
            ))}
          </select>
          <button
            onClick={handleExportCsv}
            className="flex items-center gap-2 px-4 py-2 bg-white/5 border border-white/10 rounded-xl text-sm font-medium text-slate-300 hover:text-white hover:bg-white/10 transition-colors shadow-sm"
          >
            <Download className="w-4 h-4" />
            Export CSV
          </button>
        </div>
      </div>

      <div className="bg-white/[0.02] backdrop-blur-xl border border-white/10 rounded-2xl overflow-hidden shadow-2xl relative">
        <div className="absolute top-0 right-1/4 w-96 h-96 bg-indigo-500/5 rounded-full blur-[100px] pointer-events-none"></div>

        <div className="p-5 border-b border-white/10 flex flex-col sm:flex-row justify-between items-center gap-4 relative z-10 bg-black/20">
          <div className="relative w-full sm:w-96">
            <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
            <input
              type="text"
              placeholder="Search phone, session ID, or AI summary..."
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setCurrentPage(1);
              }}
              className="w-full pl-9 pr-4 py-2 bg-white/5 border border-white/10 focus:bg-white/10 rounded-xl text-sm text-slate-200 transition-all focus:ring-2 focus:ring-indigo-500/50 outline-none placeholder:text-slate-600 shadow-inner"
            />
          </div>
          <div className="flex items-center gap-3 w-full sm:w-auto flex-wrap">
            <div className="flex items-center gap-2 px-3 py-2 bg-white/5 border border-white/10 rounded-xl text-sm text-slate-300">
              <Sparkles className="w-4 h-4 text-indigo-400" />
              <select
                value={outcomeFilter}
                onChange={(e) => {
                  setOutcomeFilter(e.target.value);
                  setCurrentPage(1);
                }}
                aria-label="Filter by outcome tag"
                className="bg-transparent text-slate-200 font-medium outline-none cursor-pointer"
              >
                <option value="all" className="bg-slate-900">
                  All Outcomes
                </option>
                <option value="booked_appointment" className="bg-slate-900">
                  Appointment Booked
                </option>
                <option value="lead_qualified" className="bg-slate-900">
                  Lead Qualified
                </option>
                <option value="faq_resolved" className="bg-slate-900">
                  FAQ Resolved
                </option>
                <option value="escalated_transfer" className="bg-slate-900">
                  Human Escalation
                </option>
                <option value="general_inquiry" className="bg-slate-900">
                  General Inquiry
                </option>
              </select>
            </div>

            <div className="flex items-center gap-2 px-3 py-2 bg-white/5 border border-white/10 rounded-xl text-sm text-slate-300">
              <Filter className="w-4 h-4 text-slate-400" />
              <select
                value={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value);
                  setCurrentPage(1);
                }}
                aria-label="Filter by call status"
                className="bg-transparent text-slate-200 font-medium outline-none cursor-pointer"
              >
                <option value="all" className="bg-slate-900">
                  All Statuses
                </option>
                <option value="completed" className="bg-slate-900">
                  Completed
                </option>
                <option value="transferred" className="bg-slate-900">
                  Transferred
                </option>
                <option value="active_l1" className="bg-slate-900">
                  Active L1
                </option>
                <option value="failed" className="bg-slate-900">
                  Failed
                </option>
              </select>
            </div>
          </div>
        </div>

        <div className="overflow-x-auto relative z-10">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-white/5 border-b border-white/10">
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  Caller / Session
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  Date & Time
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  Duration
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  Status & Sentiment
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                  AI Outcome & Summary
                </th>
                <th className="py-4 px-6 text-xs font-semibold text-slate-400 uppercase tracking-wider text-right">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/5">
              {loading ? (
                Array.from({ length: 5 }).map((_, i) => (
                  <tr key={i} className="animate-pulse">
                    <td className="py-4 px-6">
                      <div className="h-4 bg-white/5 rounded w-32 mb-2"></div>
                      <div className="h-3 bg-white/5 rounded w-24"></div>
                    </td>
                    <td className="py-4 px-6">
                      <div className="h-4 bg-white/5 rounded w-24"></div>
                    </td>
                    <td className="py-4 px-6">
                      <div className="h-4 bg-white/5 rounded w-16"></div>
                    </td>
                    <td className="py-4 px-6">
                      <div className="h-6 bg-white/5 rounded-full w-24"></div>
                    </td>
                    <td className="py-4 px-6">
                      <div className="h-4 bg-white/5 rounded w-40"></div>
                    </td>
                    <td className="py-4 px-6">
                      <div className="h-8 bg-white/5 rounded w-8 ml-auto"></div>
                    </td>
                  </tr>
                ))
              ) : filteredLogs.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-16 text-center">
                    <div className="flex flex-col items-center justify-center text-slate-500">
                      <Search className="w-10 h-10 mb-4 opacity-20" />
                      <p className="text-sm font-medium text-slate-400">No calls found</p>
                      <p className="text-xs mt-1">Try adjusting your search or outcome filters</p>
                    </div>
                  </td>
                </tr>
              ) : (
                <AnimatePresence>
                  {paginatedLogs.map((log) => (
                    <motion.tr
                      key={log.id}
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      exit={{ opacity: 0 }}
                      className="group hover:bg-white/[0.03] transition-colors"
                    >
                      <td className="py-4 px-6">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-indigo-400">
                            <Phone className="w-4 h-4" />
                          </div>
                          <div>
                            <div className="font-medium text-slate-200">{log.caller}</div>
                            <div className="text-xs text-slate-500 font-mono mt-0.5">
                              {log.sessionId ? log.sessionId.substring(0, 12) : 'unknown'}...
                            </div>
                          </div>
                        </div>
                      </td>
                      <td className="py-4 px-6">
                        <span className="text-sm text-slate-300">{formatDate(log.date)}</span>
                      </td>
                      <td className="py-4 px-6">
                        <div className="flex items-center text-sm text-slate-300">
                          <Clock className="w-4 h-4 mr-2 text-slate-500" />
                          {formatDuration(log.duration)}
                        </div>
                      </td>
                      <td className="py-4 px-6">
                        <div className="flex flex-col items-start gap-1.5">
                          {log.status === 'completed' && (
                            <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                              <CheckCircle2 className="w-3.5 h-3.5" /> Completed
                            </span>
                          )}
                          {log.status === 'failed' && (
                            <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium bg-rose-500/10 text-rose-400 border border-rose-500/20">
                              <XCircle className="w-3.5 h-3.5" /> Failed
                            </span>
                          )}
                          {log.status === 'transferred' && (
                            <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium bg-blue-500/10 text-blue-400 border border-blue-500/20">
                              <ArrowUpRight className="w-3.5 h-3.5" /> Transferred
                            </span>
                          )}
                          {log.status === 'active_l1' && (
                            <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium bg-amber-500/10 text-amber-400 border border-amber-500/20">
                              Active L1
                            </span>
                          )}
                          <span
                            className={`text-[10px] font-semibold px-2 py-0.5 rounded ${
                              log.sentiment === 'Positive'
                                ? 'bg-emerald-500/10 text-emerald-300'
                                : log.sentiment === 'Negative'
                                ? 'bg-rose-500/10 text-rose-300'
                                : 'bg-white/5 text-slate-400'
                            }`}
                          >
                            Sentiment: {log.sentiment}
                          </span>
                        </div>
                      </td>
                      <td className="py-4 px-6 max-w-xs">
                        <div className="space-y-1">
                          <span className="inline-flex items-center gap-1 text-xs font-semibold text-indigo-300 bg-indigo-500/15 px-2.5 py-0.5 rounded-full border border-indigo-500/25">
                            <Sparkles className="w-3 h-3" />
                            {formatOutcomeLabel(log.outcomeTag)}
                          </span>
                          <p className="text-xs text-slate-400 line-clamp-2">
                            {log.aiSummary || log.intent}
                          </p>
                        </div>
                      </td>
                      <td className="py-4 px-6 text-right">
                        <div className="flex justify-end items-center gap-2">
                          <button
                            onClick={() => loadTranscript(log.sessionId)}
                            className="p-2 text-slate-400 hover:text-indigo-400 hover:bg-indigo-500/10 rounded-lg transition-colors"
                            title="View Transcript & AI Summary"
                          >
                            <FileText className="w-4 h-4" />
                          </button>
                          {log.recordingUrl && (
                            <button
                              onClick={() => handlePlay(log.id, log.recordingUrl)}
                              className={`p-2 rounded-lg transition-colors ${
                                playingId === log.id
                                  ? 'text-indigo-400 bg-indigo-500/20'
                                  : 'text-slate-400 hover:text-indigo-400 hover:bg-indigo-500/10'
                              }`}
                              title={playingId === log.id ? 'Pause Recording' : 'Play Recording'}
                            >
                              <Play className="w-4 h-4" />
                            </button>
                          )}
                          <div className="relative">
                            <button
                              onClick={() =>
                                setDropdownOpenId(dropdownOpenId === log.id ? null : log.id)
                              }
                              className="p-2 text-slate-400 hover:text-white hover:bg-white/10 rounded-lg transition-colors"
                            >
                              <MoreVertical className="w-4 h-4" />
                            </button>
                            {dropdownOpenId === log.id && (
                              <div className="absolute right-0 mt-2 w-48 bg-slate-800 border border-slate-700 rounded-xl shadow-xl overflow-hidden z-20">
                                <button
                                  onClick={() => handleDelete(log.id)}
                                  className="w-full text-left px-4 py-3 text-sm text-rose-400 hover:bg-slate-700 transition-colors flex items-center gap-2"
                                >
                                  Delete Record
                                </button>
                              </div>
                            )}
                          </div>
                        </div>
                      </td>
                    </motion.tr>
                  ))}
                </AnimatePresence>
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {!loading && filteredLogs.length > 0 && (
          <div className="p-4 border-t border-white/10 flex items-center justify-between text-sm text-slate-400 bg-black/20">
            <span>
              Showing {(safePage - 1) * pageSize + 1}–
              {Math.min(safePage * pageSize, filteredLogs.length)} of {filteredLogs.length} results
              (Page {safePage} of {totalPages})
            </span>
            <div className="flex gap-2">
              <button
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={safePage <= 1}
                className="px-3 py-1 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
              >
                Previous
              </button>
              <button
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                disabled={safePage >= totalPages}
                className="px-3 py-1 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Transcript & AI Summary Modal */}
      <AnimatePresence>
        {viewTranscriptId && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm"
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-white dark:bg-slate-800 rounded-2xl shadow-xl border border-slate-200 dark:border-slate-700 p-6 max-w-2xl w-full max-h-[85vh] flex flex-col"
            >
              <div className="flex justify-between items-center mb-4 border-b border-slate-200 dark:border-slate-700 pb-4">
                <h3 className="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-3">
                  <FileText className="text-indigo-500" />
                  Call Summary & Transcript
                </h3>
                <button
                  onClick={() => setViewTranscriptId(null)}
                  className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 transition-colors"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>

              {activeTranscriptCall && (
                <div className="mb-4 p-3.5 rounded-xl bg-indigo-500/10 border border-indigo-500/20 space-y-1">
                  <div className="flex items-center justify-between text-xs">
                    <span className="font-semibold text-indigo-300 flex items-center gap-1.5">
                      <Sparkles className="w-3.5 h-3.5" />
                      AI Post-Call Summary ({formatOutcomeLabel(activeTranscriptCall.outcomeTag)})
                    </span>
                    <span className="text-slate-400">
                      Sentiment: {activeTranscriptCall.sentiment}
                    </span>
                  </div>
                  <p className="text-xs text-slate-200 leading-relaxed">
                    {activeTranscriptCall.aiSummary || activeTranscriptCall.intent}
                  </p>
                </div>
              )}

              <div className="flex-1 overflow-y-auto space-y-4 pr-2 custom-scrollbar">
                {transcriptLoading ? (
                  <div className="flex justify-center py-10">
                    <div className="w-8 h-8 rounded-full border-2 border-indigo-500 border-t-transparent animate-spin"></div>
                  </div>
                ) : transcriptData.length === 0 ? (
                  <div className="text-center py-10 text-slate-500 dark:text-slate-400">
                    No transcript turns recorded for this call.
                  </div>
                ) : (
                  transcriptData.map((turn, index) => {
                    const isAI = turn.speaker.startsWith('ai');
                    return (
                      <div
                        key={index}
                        className={`flex flex-col ${isAI ? 'items-start' : 'items-end'}`}
                      >
                        <div className="flex items-center gap-2 mb-1">
                          <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                            {isAI ? 'Agent' : 'Customer'}
                          </span>
                          <span className="text-[10px] text-slate-400 dark:text-slate-500">
                            {new Date(turn.timestamp).toLocaleTimeString([], {
                              hour: '2-digit',
                              minute: '2-digit',
                              second: '2-digit',
                            })}
                          </span>
                        </div>
                        <div
                          className={`px-4 py-3 rounded-2xl max-w-[85%] text-sm shadow-sm ${
                            isAI
                              ? 'bg-slate-100 dark:bg-slate-700 text-slate-800 dark:text-slate-200 rounded-tl-sm'
                              : 'bg-indigo-600 text-white rounded-tr-sm'
                          }`}
                        >
                          {turn.rawTranscript || '(silence)'}
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default CallLogs;
