Spaces:
Paused

CBV01 commited on
Commit
60de0ac
·
1 Parent(s): 2084ad0

fix(ai-assistant): 10 leads pagination, fast dialog fetching, remove bottom bar & add AI suggestions modal

Browse files
backend/main.py CHANGED
@@ -6260,8 +6260,9 @@ async def get_account_dms(phone: str, user_id: str = Depends(get_current_user_id
6260
 
6261
  dms = []
6262
  try:
6263
- # Scan up to 500 dialogs to find all personal user chats past channels and groups
6264
- async for dialog in client.iter_dialogs(limit=500):
 
6265
  if dialog.is_user:
6266
  entity = dialog.entity
6267
  if getattr(entity, 'bot', False):
@@ -6283,7 +6284,7 @@ async def get_account_dms(phone: str, user_id: str = Depends(get_current_user_id
6283
  "date": dialog.date.isoformat() if dialog.date else None,
6284
  "unread_count": dialog.unread_count or 0
6285
  })
6286
- if len(dms) >= 150:
6287
  break
6288
  return {"dms": dms, "phone": phone, "total": len(dms)}
6289
  except Exception as e:
 
6260
 
6261
  dms = []
6262
  try:
6263
+ # Fast single MTProto round-trip: fetches top 120 recent dialogs in ~1 second
6264
+ dialogs = await client.get_dialogs(limit=120)
6265
+ for dialog in dialogs:
6266
  if dialog.is_user:
6267
  entity = dialog.entity
6268
  if getattr(entity, 'bot', False):
 
6284
  "date": dialog.date.isoformat() if dialog.date else None,
6285
  "unread_count": dialog.unread_count or 0
6286
  })
6287
+ if len(dms) >= 80:
6288
  break
6289
  return {"dms": dms, "phone": phone, "total": len(dms)}
6290
  except Exception as e:
frontend/src/app/ai-assistant/page.tsx CHANGED
@@ -21,7 +21,9 @@ import {
21
  Star,
22
  File,
23
  MessageSquare,
24
- Target
 
 
25
  } from 'lucide-react';
26
  import { apiFetch } from '@/lib/auth';
27
 
@@ -219,8 +221,12 @@ export default function AiAssistantPage() {
219
  const [searchDmTerm, setSearchDmTerm] = useState('');
220
  const [mobileView, setMobileView] = useState<'list' | 'chat'>('list');
221
 
222
- // AI Suggestions & Slide-Up Container State
223
- const [isSlideUpOpen, setIsSlideUpOpen] = useState(false);
 
 
 
 
224
  const [isAnalyzingDm, setIsAnalyzingDm] = useState(false);
225
  const [dmAnalysis, setDmAnalysis] = useState<DmAnalysisResult | null>(null);
226
  const [dmAnalysisError, setDmAnalysisError] = useState('');
@@ -345,6 +351,7 @@ export default function AiAssistantPage() {
345
  };
346
  });
347
  setDms(mappedDms);
 
348
  handleSelectContact(phone, mappedDms[0]);
349
  } else {
350
  setDms(DEMO_LEADS);
@@ -364,7 +371,7 @@ export default function AiAssistantPage() {
364
  const handleSelectContact = async (phone: string, contact: DmContact) => {
365
  setSelectedContact(contact);
366
  setDmAnalysis(null);
367
- setIsSlideUpOpen(false);
368
  setCopiedIdx(null);
369
  setDmAnalysisError('');
370
 
@@ -502,12 +509,8 @@ export default function AiAssistantPage() {
502
  }
503
  };
504
 
505
- const handleToggleSlideUp = () => {
506
- if (isSlideUpOpen) {
507
- setIsSlideUpOpen(false);
508
- return;
509
- }
510
- setIsSlideUpOpen(true);
511
  if (!dmAnalysis && !isAnalyzingDm && selectedContact) {
512
  triggerDmAnalysis(messages, selectedContact.name);
513
  }
@@ -521,7 +524,7 @@ export default function AiAssistantPage() {
521
  }, 2500);
522
  };
523
 
524
- // Calculate contacts to display (all messages shown, filtered by search query)
525
  const currentLeadsList = dms.length > 0 ? dms : DEMO_LEADS;
526
  const filteredLeads = currentLeadsList.filter(d => {
527
  const query = searchDmTerm.toLowerCase();
@@ -531,6 +534,9 @@ export default function AiAssistantPage() {
531
  (d.last_message && d.last_message.toLowerCase().includes(query));
532
  });
533
 
 
 
 
534
  return (
535
  <div className="h-full max-h-full w-full flex-1 min-h-0 overflow-hidden bg-background text-foreground flex font-sans rounded-2xl border border-border/80 shadow-xl">
536
  {/* ------------------------------------------------ */}
@@ -609,13 +615,16 @@ export default function AiAssistantPage() {
609
  type="text"
610
  placeholder="Search leads & messages..."
611
  value={searchDmTerm}
612
- onChange={(e) => setSearchDmTerm(e.target.value)}
 
 
 
613
  className="w-full bg-background/80 border border-border/70 rounded-xl pl-8.5 pr-3 py-1.5 text-xs text-foreground placeholder:text-foreground/35 outline-none focus:ring-1 focus:ring-cyan-500/30 focus:border-cyan-500/40"
614
  />
615
  </div>
616
  </div>
617
 
618
- {/* 4. Contacts / Leads List (Independent Scroll) */}
619
  <div className="flex-1 min-h-0 overflow-y-auto divide-y divide-border/40 custom-scrollbar overscroll-contain">
620
  {fetchingDms && (
621
  <div className="p-8 text-center text-foreground/40 text-xs">
@@ -630,7 +639,7 @@ export default function AiAssistantPage() {
630
  </div>
631
  )}
632
 
633
- {filteredLeads.map(lead => {
634
  const isSelected = selectedContact?.id === lead.id;
635
  return (
636
  <button
@@ -683,6 +692,29 @@ export default function AiAssistantPage() {
683
  );
684
  })}
685
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
686
  </div>
687
 
688
  {/* ------------------------------------------------ */}
@@ -734,12 +766,12 @@ export default function AiAssistantPage() {
734
  {/* Header Quick Actions */}
735
  <div className="flex items-center gap-2">
736
  <button
737
- onClick={handleToggleSlideUp}
738
- className="px-3 py-1.5 rounded-xl bg-cyan-500/10 hover:bg-cyan-500/20 text-cyan-400 border border-cyan-500/30 text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer shadow-xs"
739
- title="AI Reply Assistance"
740
  >
741
  <Sparkles size={13} className={isAnalyzingDm ? 'animate-spin text-cyan-400' : ''} />
742
- <span>{isSlideUpOpen ? 'Hide Suggestions' : 'AI Suggestions'}</span>
743
  </button>
744
 
745
  <button
@@ -920,210 +952,238 @@ export default function AiAssistantPage() {
920
  <div ref={messagesEndRef} />
921
  </div>
922
 
923
- {/* BOTTOM ACTION BAR (NO REPLY TEXTBOX - ONLY CLEAN AI TRIGGER BUTTON) */}
924
- <div className="p-3 sm:p-4 border-t border-border/80 bg-card/70 backdrop-blur-sm flex items-center justify-between gap-3 shrink-0">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
925
  <div className="flex items-center gap-2.5 min-w-0">
926
- <div className="w-8 h-8 rounded-xl bg-cyan-500/10 border border-cyan-500/20 text-cyan-400 flex items-center justify-center shrink-0">
927
- <Sparkles size={15} />
928
  </div>
929
  <div className="min-w-0">
930
- <span className="text-xs font-bold text-foreground block truncate">
931
- Telegram Conversation Assistant
932
- </span>
933
- <span className="text-[10px] text-foreground/50 truncate block">
934
- {messages.length > 0
935
- ? `Assistance ready for ${selectedContact.name} • Copy replies to Telegram`
936
- : "No messages exchanged yet"}
937
- </span>
 
 
 
938
  </div>
939
  </div>
940
 
941
- <button
942
- type="button"
943
- onClick={handleToggleSlideUp}
944
- className={`px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-2 cursor-pointer shadow-sm ${
945
- isSlideUpOpen
946
- ? 'bg-foreground/10 text-foreground border border-border/80 hover:bg-foreground/15'
947
- : 'bg-gradient-to-r from-cyan-500 to-blue-600 hover:from-cyan-400 hover:to-blue-500 text-white shadow-cyan-500/20 hover:scale-[1.02] active:scale-95'
948
- }`}
949
- >
950
- <Sparkles size={14} className={isAnalyzingDm ? 'animate-spin' : ''} />
951
- <span>{isSlideUpOpen ? 'Hide Suggestions' : 'AI Reply Suggestions'}</span>
952
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
953
  </div>
954
 
955
- {/* SLIDE-UP CONTAINER (SLIDES UP OVER CONVERSATION STREAM) */}
956
- {isSlideUpOpen && (
957
- <div className="absolute bottom-0 inset-x-0 z-30 max-h-[70%] sm:max-h-[65%] flex flex-col bg-card/95 backdrop-blur-xl border-t border-border/80 rounded-t-3xl shadow-2xl animate-in slide-in-from-bottom duration-300">
958
- {/* Slide-Up Header */}
959
- <div className="p-3.5 px-4 sm:px-5 border-b border-border/70 flex items-center justify-between bg-card/90 shrink-0">
960
- <div className="flex items-center gap-2.5 min-w-0">
961
- <div className="w-7 h-7 rounded-lg bg-cyan-500/15 text-cyan-400 border border-cyan-500/30 flex items-center justify-center shrink-0">
962
- <Sparkles size={14} />
963
- </div>
964
- <div className="min-w-0">
965
- <h3 className="text-xs sm:text-sm font-extrabold text-foreground truncate">
966
- AI Reply Suggestions
967
- </h3>
968
- <p className="text-[10px] text-foreground/50 font-medium truncate">
969
- Contextual responses tailored to latest message from {selectedContact.name}
970
- </p>
971
  </div>
972
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
973
 
974
- <div className="flex items-center gap-2">
 
 
 
 
 
 
 
 
 
 
975
  <button
976
  type="button"
977
- onClick={() => triggerDmAnalysis(messages, selectedContact.name)}
978
- disabled={isAnalyzingDm}
979
- className="px-2.5 py-1.5 rounded-xl bg-foreground/5 hover:bg-foreground/10 text-foreground/70 hover:text-foreground text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer disabled:opacity-40"
980
- title="Re-generate suggestions"
 
981
  >
982
- <RefreshCw size={12} className={isAnalyzingDm ? 'animate-spin text-cyan-400' : ''} />
983
- <span className="hidden sm:inline">Refresh</span>
984
  </button>
985
  <button
986
  type="button"
987
- onClick={() => setIsSlideUpOpen(false)}
988
- className="w-7 h-7 rounded-lg bg-foreground/5 hover:bg-foreground/10 text-foreground/60 hover:text-foreground flex items-center justify-center transition-all cursor-pointer"
989
- title="Close suggestions panel"
990
  >
991
- <X size={14} />
992
  </button>
993
  </div>
994
  </div>
 
995
 
996
- {/* Slide-Up Content Stream */}
997
- <div className="flex-1 overflow-y-auto p-4 sm:p-5 space-y-4 custom-scrollbar">
998
- {isAnalyzingDm && (
999
- <div className="py-8 px-4 text-center space-y-3.5 max-w-md mx-auto">
1000
- <div className="relative w-14 h-14 mx-auto flex items-center justify-center">
1001
- <div className="absolute inset-0 rounded-2xl bg-gradient-to-tr from-cyan-500 to-purple-600 animate-pulse opacity-30 blur-sm" />
1002
- <div className="relative w-12 h-12 rounded-2xl bg-card border border-cyan-500/40 text-cyan-400 flex items-center justify-center shadow-md shadow-cyan-500/20">
1003
- <Sparkles size={22} className="animate-spin" />
1004
- </div>
1005
- </div>
1006
- <div>
1007
- <h4 className="text-sm font-extrabold text-foreground">
1008
- {scanPhaseText || "Reading conversation stream..."}
1009
- </h4>
1010
- <p className="text-xs text-foreground/50 mt-1">
1011
- Analyzing chat thread & targeting {selectedContact.name}&apos;s last statement
1012
- </p>
1013
- </div>
1014
- <div className="w-full bg-foreground/10 rounded-full h-2 overflow-hidden">
1015
- <div
1016
- className="h-full bg-gradient-to-r from-cyan-400 via-purple-500 to-blue-500 transition-all duration-300"
1017
- style={{ width: `${Math.min(100, Math.max(25, Math.round(((scannedMsgIndex + 1) / Math.max(1, messages.length)) * 100)))}%` }}
1018
- />
1019
- </div>
1020
- <span className="text-[10px] text-cyan-400 font-mono font-bold block animate-pulse">
1021
- Inspecting message {Math.min(scannedMsgIndex + 1, messages.length)} of {messages.length}...
1022
  </span>
 
1023
  </div>
1024
  )}
1025
 
1026
- {!isAnalyzingDm && dmAnalysisError && (
1027
- <div className="p-4 bg-rose-500/10 border border-rose-500/20 rounded-2xl text-rose-400 text-xs space-y-2">
1028
- <div className="flex items-center gap-2 font-bold">
1029
- <AlertCircle size={15} className="shrink-0" />
1030
- <span>{dmAnalysisError}</span>
1031
- </div>
1032
- {!aiKey && (
1033
- <button
1034
- type="button"
1035
- onClick={() => setIsConfigModalOpen(true)}
1036
- className="px-3 py-1.5 rounded-xl bg-rose-500/20 hover:bg-rose-500/30 text-rose-300 font-bold text-xs transition-colors cursor-pointer"
1037
  >
1038
- Connect OpenRouter Key Now
1039
- </button>
1040
- )}
1041
- </div>
1042
- )}
 
 
 
 
 
 
 
 
1043
 
1044
- {!isAnalyzingDm && dmAnalysis && (
1045
- <div className="space-y-3.5">
1046
- {dmAnalysis.conversation_summary && (
1047
- <div className="px-3.5 py-2 rounded-xl bg-cyan-500/5 border border-cyan-500/20 text-xs text-foreground/80 flex items-center gap-2">
1048
- <span className="font-bold text-cyan-400 shrink-0">Context:</span>
1049
- <span className="truncate">{dmAnalysis.conversation_summary}</span>
1050
- </div>
1051
- )}
1052
-
1053
- <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
1054
- {dmAnalysis.suggested_replies.map((rep, idx) => {
1055
- const isCopied = copiedIdx === idx;
1056
- return (
1057
- <div
1058
- key={idx}
1059
- className="p-4 rounded-2xl bg-background/90 hover:bg-background border border-border/80 hover:border-cyan-500/40 transition-all flex flex-col justify-between gap-3 shadow-xs"
1060
  >
1061
- <div className="space-y-2">
1062
- <div className="flex items-center justify-between">
1063
- <span className="text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded-md bg-cyan-500/10 text-cyan-400 border border-cyan-500/20">
1064
- {rep.angle || `Option ${idx + 1}`}
1065
- </span>
1066
- <span className="text-[10px] text-foreground/40 font-mono">
1067
- {rep.text.length} chars
1068
- </span>
1069
- </div>
1070
- <p className="text-xs text-foreground/90 leading-relaxed font-sans whitespace-pre-wrap select-all">
1071
- {rep.text}
1072
- </p>
1073
- </div>
1074
-
1075
- <div className="flex items-center justify-between gap-2 pt-2 border-t border-border/50">
1076
- <span className="text-[10px] text-foreground/40 font-medium hidden sm:inline">
1077
- Reply assistance
1078
- </span>
1079
- <button
1080
- type="button"
1081
- onClick={() => handleCopySuggestion(rep.text, idx)}
1082
- className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all cursor-pointer shadow-xs flex items-center gap-1.5 ml-auto ${
1083
- isCopied
1084
- ? 'bg-emerald-600 text-white shadow-emerald-600/20'
1085
- : 'bg-cyan-600 hover:bg-cyan-500 text-white shadow-cyan-600/20 hover:scale-[1.02] active:scale-95'
1086
- }`}
1087
- >
1088
- {isCopied ? <Check size={12} className="text-white" /> : <Copy size={12} />}
1089
- <span>{isCopied ? 'Copied to Clipboard!' : 'Copy Suggestion'}</span>
1090
- </button>
1091
- </div>
1092
- </div>
1093
- );
1094
- })}
1095
- </div>
1096
- </div>
1097
- )}
1098
 
1099
- {!isAnalyzingDm && !dmAnalysis && !dmAnalysisError && (
1100
- <div className="py-8 text-center space-y-3">
1101
- <p className="text-xs text-foreground/60 max-w-sm mx-auto">
1102
- Click below to generate context-aware Telegram reply suggestions based on this conversation.
1103
- </p>
1104
- <button
1105
- type="button"
1106
- onClick={() => triggerDmAnalysis(messages, selectedContact.name)}
1107
- className="px-4 py-2 rounded-xl bg-cyan-600 hover:bg-cyan-500 text-white font-bold text-xs shadow-xs cursor-pointer"
1108
- >
1109
- Generate AI Reply Suggestions
1110
- </button>
1111
- </div>
1112
- )}
 
 
 
 
 
1113
  </div>
1114
- </div>
1115
- )}
1116
- </>
1117
- ) : (
1118
- <div className="flex-1 flex flex-col items-center justify-center text-center p-8 space-y-3 text-foreground/40">
1119
- <MessageSquare size={36} className="opacity-40" />
1120
- <h3 className="text-sm font-bold text-foreground">Select a lead to monitor conversation</h3>
1121
- <p className="text-xs max-w-sm">
1122
- Click any contact on the left to inspect conversation history and get context-aware reply suggestions.
1123
- </p>
 
 
 
 
 
 
1124
  </div>
1125
- )}
1126
- </div>
 
1127
 
1128
  {/* ==================================================== */}
1129
  {/* AI CONFIGURATION MODAL */}
 
21
  Star,
22
  File,
23
  MessageSquare,
24
+ Target,
25
+ ChevronLeft,
26
+ ChevronRight
27
  } from 'lucide-react';
28
  import { apiFetch } from '@/lib/auth';
29
 
 
221
  const [searchDmTerm, setSearchDmTerm] = useState('');
222
  const [mobileView, setMobileView] = useState<'list' | 'chat'>('list');
223
 
224
+ // 10 Leads Per Page Pagination
225
+ const [leadsPage, setLeadsPage] = useState(1);
226
+ const LEADS_PER_PAGE = 10;
227
+
228
+ // AI Suggestions Modal State
229
+ const [isSuggestionModalOpen, setIsSuggestionModalOpen] = useState(false);
230
  const [isAnalyzingDm, setIsAnalyzingDm] = useState(false);
231
  const [dmAnalysis, setDmAnalysis] = useState<DmAnalysisResult | null>(null);
232
  const [dmAnalysisError, setDmAnalysisError] = useState('');
 
351
  };
352
  });
353
  setDms(mappedDms);
354
+ setLeadsPage(1);
355
  handleSelectContact(phone, mappedDms[0]);
356
  } else {
357
  setDms(DEMO_LEADS);
 
371
  const handleSelectContact = async (phone: string, contact: DmContact) => {
372
  setSelectedContact(contact);
373
  setDmAnalysis(null);
374
+ setIsSuggestionModalOpen(false);
375
  setCopiedIdx(null);
376
  setDmAnalysisError('');
377
 
 
509
  }
510
  };
511
 
512
+ const handleOpenSuggestionsModal = () => {
513
+ setIsSuggestionModalOpen(true);
 
 
 
 
514
  if (!dmAnalysis && !isAnalyzingDm && selectedContact) {
515
  triggerDmAnalysis(messages, selectedContact.name);
516
  }
 
524
  }, 2500);
525
  };
526
 
527
+ // Calculate contacts to display (strictly 10 leads per page, filtered by search query)
528
  const currentLeadsList = dms.length > 0 ? dms : DEMO_LEADS;
529
  const filteredLeads = currentLeadsList.filter(d => {
530
  const query = searchDmTerm.toLowerCase();
 
534
  (d.last_message && d.last_message.toLowerCase().includes(query));
535
  });
536
 
537
+ const totalLeadsPages = Math.max(1, Math.ceil(filteredLeads.length / LEADS_PER_PAGE));
538
+ const pagedLeads = filteredLeads.slice((leadsPage - 1) * LEADS_PER_PAGE, leadsPage * LEADS_PER_PAGE);
539
+
540
  return (
541
  <div className="h-full max-h-full w-full flex-1 min-h-0 overflow-hidden bg-background text-foreground flex font-sans rounded-2xl border border-border/80 shadow-xl">
542
  {/* ------------------------------------------------ */}
 
615
  type="text"
616
  placeholder="Search leads & messages..."
617
  value={searchDmTerm}
618
+ onChange={(e) => {
619
+ setSearchDmTerm(e.target.value);
620
+ setLeadsPage(1);
621
+ }}
622
  className="w-full bg-background/80 border border-border/70 rounded-xl pl-8.5 pr-3 py-1.5 text-xs text-foreground placeholder:text-foreground/35 outline-none focus:ring-1 focus:ring-cyan-500/30 focus:border-cyan-500/40"
623
  />
624
  </div>
625
  </div>
626
 
627
+ {/* 4. Contacts / Leads List (Fixed viewport height, scrolls within 10 items) */}
628
  <div className="flex-1 min-h-0 overflow-y-auto divide-y divide-border/40 custom-scrollbar overscroll-contain">
629
  {fetchingDms && (
630
  <div className="p-8 text-center text-foreground/40 text-xs">
 
639
  </div>
640
  )}
641
 
642
+ {pagedLeads.map(lead => {
643
  const isSelected = selectedContact?.id === lead.id;
644
  return (
645
  <button
 
692
  );
693
  })}
694
  </div>
695
+
696
+ {/* 5. Pagination Footer: Exactly 10 leads per page */}
697
+ <div className="p-2.5 px-3 border-t border-border/70 bg-card/70 flex items-center justify-between shrink-0 text-xs">
698
+ <button
699
+ onClick={() => setLeadsPage(prev => Math.max(1, prev - 1))}
700
+ disabled={leadsPage <= 1}
701
+ className="px-2.5 py-1 rounded-lg bg-foreground/5 hover:bg-foreground/10 text-foreground/70 hover:text-foreground font-semibold flex items-center gap-1 transition-all cursor-pointer disabled:opacity-30 disabled:pointer-events-none"
702
+ >
703
+ <ChevronLeft size={13} />
704
+ <span>Prev</span>
705
+ </button>
706
+ <span className="font-mono text-[11px] text-foreground/50 font-bold">
707
+ Page {leadsPage} of {totalLeadsPages} ({filteredLeads.length})
708
+ </span>
709
+ <button
710
+ onClick={() => setLeadsPage(prev => Math.min(totalLeadsPages, prev + 1))}
711
+ disabled={leadsPage >= totalLeadsPages}
712
+ className="px-2.5 py-1 rounded-lg bg-foreground/5 hover:bg-foreground/10 text-foreground/70 hover:text-foreground font-semibold flex items-center gap-1 transition-all cursor-pointer disabled:opacity-30 disabled:pointer-events-none"
713
+ >
714
+ <span>Next</span>
715
+ <ChevronRight size={13} />
716
+ </button>
717
+ </div>
718
  </div>
719
 
720
  {/* ------------------------------------------------ */}
 
766
  {/* Header Quick Actions */}
767
  <div className="flex items-center gap-2">
768
  <button
769
+ onClick={handleOpenSuggestionsModal}
770
+ className="px-3.5 py-1.5 rounded-xl bg-gradient-to-r from-cyan-500/20 to-blue-500/20 hover:from-cyan-500/30 hover:to-blue-500/30 text-cyan-400 border border-cyan-500/40 text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer shadow-sm hover:scale-[1.02] active:scale-95"
771
+ title="Open AI Reply Suggestions Modal"
772
  >
773
  <Sparkles size={13} className={isAnalyzingDm ? 'animate-spin text-cyan-400' : ''} />
774
+ <span>AI Suggestions</span>
775
  </button>
776
 
777
  <button
 
952
  <div ref={messagesEndRef} />
953
  </div>
954
 
955
+ </>
956
+ ) : (
957
+ <div className="flex-1 flex flex-col items-center justify-center text-center p-8 space-y-3 text-foreground/40">
958
+ <MessageSquare size={36} className="opacity-40" />
959
+ <h3 className="text-sm font-bold text-foreground">Select a lead to monitor conversation</h3>
960
+ <p className="text-xs text-foreground/50 max-w-xs">
961
+ Select a thread from the inbox on the left to read history and generate AI suggestions.
962
+ </p>
963
+ </div>
964
+ )}
965
+ </div>
966
+
967
+ {/* ------------------------------------------------ */}
968
+ {/* DEDICATED AI SUGGESTION MODAL DIALOG */}
969
+ {/* ------------------------------------------------ */}
970
+ {isSuggestionModalOpen && selectedContact && (
971
+ <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-5 bg-black/80 backdrop-blur-md animate-in fade-in duration-200">
972
+ <div
973
+ className="fixed inset-0 cursor-pointer"
974
+ onClick={() => setIsSuggestionModalOpen(false)}
975
+ />
976
+ <div className="relative w-full max-w-3xl bg-card border border-border/80 rounded-3xl shadow-2xl flex flex-col max-h-[85vh] animate-in zoom-in-95 duration-200 overflow-hidden z-10">
977
+ {/* Glowing top line */}
978
+ <div className="absolute top-0 inset-x-0 h-[2px] bg-gradient-to-r from-transparent via-cyan-400 to-transparent" />
979
+
980
+ {/* Modal Header */}
981
+ <div className="p-4 sm:p-5 border-b border-border/70 flex items-center justify-between gap-3 bg-card/90 shrink-0">
982
  <div className="flex items-center gap-2.5 min-w-0">
983
+ <div className="w-9 h-9 rounded-xl bg-cyan-500/15 text-cyan-400 border border-cyan-500/30 flex items-center justify-center shrink-0 shadow-sm">
984
+ <Sparkles size={17} />
985
  </div>
986
  <div className="min-w-0">
987
+ <div className="flex items-center gap-2 flex-wrap">
988
+ <h3 className="text-sm sm:text-base font-extrabold text-foreground">
989
+ AI Reply Suggestions
990
+ </h3>
991
+ <span className="text-[10px] px-2.5 py-0.5 rounded-full bg-cyan-500/10 text-cyan-400 border border-cyan-500/20 font-bold">
992
+ {selectedContact.name}
993
+ </span>
994
+ </div>
995
+ <p className="text-[11px] text-foreground/50 font-medium truncate mt-0.5">
996
+ Context-aware response suggestions tailored to the conversation
997
+ </p>
998
  </div>
999
  </div>
1000
 
1001
+ <div className="flex items-center gap-2 shrink-0">
1002
+ <span className="hidden sm:inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-foreground/5 border border-border/60 text-[10px] font-mono text-foreground/60">
1003
+ <Cpu size={11} className="text-cyan-400" />
1004
+ <span>{(aiModel.split('/')[1] || aiModel).slice(0, 16)}</span>
1005
+ </span>
1006
+ <button
1007
+ type="button"
1008
+ onClick={() => triggerDmAnalysis(messages, selectedContact.name)}
1009
+ disabled={isAnalyzingDm}
1010
+ className="px-2.5 py-1.5 rounded-xl bg-foreground/5 hover:bg-foreground/10 text-foreground/70 hover:text-foreground text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer disabled:opacity-40 border border-border/60"
1011
+ title="Re-generate suggestions"
1012
+ >
1013
+ <RefreshCw size={12} className={isAnalyzingDm ? 'animate-spin text-cyan-400' : ''} />
1014
+ <span className="hidden xs:inline">Re-scan</span>
1015
+ </button>
1016
+ <button
1017
+ type="button"
1018
+ onClick={() => setIsSuggestionModalOpen(false)}
1019
+ className="w-8 h-8 rounded-xl bg-foreground/5 hover:bg-foreground/10 text-foreground/60 hover:text-foreground flex items-center justify-center transition-all cursor-pointer"
1020
+ title="Close suggestions modal"
1021
+ >
1022
+ <X size={15} />
1023
+ </button>
1024
+ </div>
1025
  </div>
1026
 
1027
+ {/* Modal Body */}
1028
+ <div className="flex-1 min-h-0 overflow-y-auto p-4 sm:p-6 space-y-4 custom-scrollbar overscroll-contain">
1029
+ {/* Live Scanning HUD */}
1030
+ {isAnalyzingDm && (
1031
+ <div className="py-10 px-4 text-center space-y-4 max-w-md mx-auto">
1032
+ <div className="relative w-16 h-16 mx-auto flex items-center justify-center">
1033
+ <div className="absolute inset-0 rounded-2xl bg-gradient-to-tr from-cyan-500 to-purple-600 animate-ping opacity-25" />
1034
+ <div className="relative w-14 h-14 rounded-2xl bg-card border border-cyan-500/40 text-cyan-400 flex items-center justify-center shadow-lg shadow-cyan-500/25">
1035
+ <Sparkles size={26} className="animate-spin text-cyan-400" />
 
 
 
 
 
 
 
1036
  </div>
1037
  </div>
1038
+ <div>
1039
+ <h4 className="text-base font-extrabold text-foreground">
1040
+ {scanPhaseText || "Reading conversation stream..."}
1041
+ </h4>
1042
+ <p className="text-xs text-foreground/50 mt-1">
1043
+ Scanning context and extracting buyer intent for {selectedContact.name}
1044
+ </p>
1045
+ </div>
1046
+ <div className="w-full bg-foreground/10 rounded-full h-2 overflow-hidden">
1047
+ <div
1048
+ className="h-full bg-gradient-to-r from-cyan-400 via-purple-500 to-blue-500 transition-all duration-300"
1049
+ style={{ width: `${Math.min(100, Math.max(20, Math.round(((scannedMsgIndex + 1) / Math.max(1, messages.length)) * 100)))}%` }}
1050
+ />
1051
+ </div>
1052
+ <span className="text-[11px] text-cyan-400 font-mono font-bold block animate-pulse">
1053
+ Evaluating context ({Math.min(scannedMsgIndex + 1, messages.length)} of {messages.length} messages checked)
1054
+ </span>
1055
+ </div>
1056
+ )}
1057
 
1058
+ {/* Free Model Rate Limit Alert */}
1059
+ {!isAnalyzingDm && dmAnalysisError && (
1060
+ <div className="p-4 sm:p-5 bg-rose-500/10 border border-rose-500/30 rounded-2xl text-rose-300 space-y-3">
1061
+ <div className="flex items-center gap-2 font-bold text-sm text-rose-400">
1062
+ <AlertCircle size={18} className="shrink-0" />
1063
+ <span>{dmAnalysisError}</span>
1064
+ </div>
1065
+ <p className="text-xs text-rose-300/80 leading-relaxed">
1066
+ OpenRouter free models enforce strict request-per-minute and daily usage quotas. If this model limit is exhausted, switch models in settings or add credits.
1067
+ </p>
1068
+ <div className="flex items-center gap-2 pt-1">
1069
  <button
1070
  type="button"
1071
+ onClick={() => {
1072
+ setIsSuggestionModalOpen(false);
1073
+ setIsConfigModalOpen(true);
1074
+ }}
1075
+ className="px-3.5 py-2 rounded-xl bg-rose-500/20 hover:bg-rose-500/30 text-white font-bold text-xs transition-colors cursor-pointer border border-rose-500/40"
1076
  >
1077
+ Switch AI Model / Key
 
1078
  </button>
1079
  <button
1080
  type="button"
1081
+ onClick={() => triggerDmAnalysis(messages, selectedContact.name)}
1082
+ className="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 text-foreground font-semibold text-xs transition-colors cursor-pointer"
 
1083
  >
1084
+ Retry
1085
  </button>
1086
  </div>
1087
  </div>
1088
+ )}
1089
 
1090
+ {/* Suggestions Loaded View */}
1091
+ {!isAnalyzingDm && dmAnalysis && (
1092
+ <div className="space-y-4">
1093
+ {/* Conversation Context Brief */}
1094
+ {dmAnalysis.conversation_summary && (
1095
+ <div className="p-3.5 rounded-2xl bg-cyan-500/5 border border-cyan-500/20 text-xs text-foreground/85 flex items-start gap-2.5">
1096
+ <span className="font-extrabold text-cyan-400 uppercase tracking-wider text-[10px] px-2 py-0.5 rounded-md bg-cyan-500/10 border border-cyan-500/20 shrink-0">
1097
+ Context Summary
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1098
  </span>
1099
+ <span className="leading-relaxed mt-0.5">{dmAnalysis.conversation_summary}</span>
1100
  </div>
1101
  )}
1102
 
1103
+ {/* 3 Strategic Reply Cards */}
1104
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3.5">
1105
+ {dmAnalysis.suggested_replies.map((rep, idx) => {
1106
+ const isCopied = copiedIdx === idx;
1107
+ return (
1108
+ <div
1109
+ key={idx}
1110
+ className="p-4 sm:p-4.5 rounded-2xl bg-card border border-border/80 hover:border-cyan-500/40 transition-all flex flex-col justify-between gap-3 shadow-md group hover:shadow-cyan-500/5"
 
 
 
1111
  >
1112
+ <div className="space-y-2.5">
1113
+ <div className="flex items-center justify-between">
1114
+ <span className="text-[10px] font-black uppercase tracking-wider px-2.5 py-0.5 rounded-md bg-cyan-500/10 text-cyan-400 border border-cyan-500/20">
1115
+ {rep.angle || `Option ${idx + 1}`}
1116
+ </span>
1117
+ <span className="text-[10px] text-foreground/40 font-mono">
1118
+ {rep.text.length} chars
1119
+ </span>
1120
+ </div>
1121
+ <p className="text-xs text-foreground/90 leading-relaxed font-sans whitespace-pre-wrap select-all">
1122
+ {rep.text}
1123
+ </p>
1124
+ </div>
1125
 
1126
+ <div className="pt-2 border-t border-border/50 flex items-center justify-end">
1127
+ <button
1128
+ type="button"
1129
+ onClick={() => handleCopySuggestion(rep.text, idx)}
1130
+ className={`w-full py-2 px-3 rounded-xl text-xs font-bold transition-all cursor-pointer shadow-xs flex items-center justify-center gap-1.5 ${
1131
+ isCopied
1132
+ ? 'bg-emerald-600 text-white shadow-emerald-600/25'
1133
+ : 'bg-cyan-600 hover:bg-cyan-500 text-white shadow-cyan-600/20 hover:scale-[1.01] active:scale-95'
1134
+ }`}
 
 
 
 
 
 
 
1135
  >
1136
+ {isCopied ? <Check size={13} className="text-white" /> : <Copy size={13} />}
1137
+ <span>{isCopied ? 'Copied to Clipboard!' : 'Copy Reply'}</span>
1138
+ </button>
1139
+ </div>
1140
+ </div>
1141
+ );
1142
+ })}
1143
+ </div>
1144
+ </div>
1145
+ )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1146
 
1147
+ {/* Fallback empty state if no analysis yet */}
1148
+ {!isAnalyzingDm && !dmAnalysis && !dmAnalysisError && (
1149
+ <div className="py-12 text-center space-y-3.5">
1150
+ <div className="w-12 h-12 rounded-2xl bg-cyan-500/10 border border-cyan-500/20 text-cyan-400 flex items-center justify-center mx-auto">
1151
+ <Sparkles size={20} />
1152
+ </div>
1153
+ <div>
1154
+ <h4 className="text-sm font-bold text-foreground">Generate Context-Aware Replies</h4>
1155
+ <p className="text-xs text-foreground/50 max-w-sm mx-auto mt-1">
1156
+ The AI assistant will review the latest conversation statements with {selectedContact.name} and provide 3 response options.
1157
+ </p>
1158
+ </div>
1159
+ <button
1160
+ type="button"
1161
+ onClick={() => triggerDmAnalysis(messages, selectedContact.name)}
1162
+ className="px-4 py-2 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-600 text-white font-bold text-xs shadow-md shadow-cyan-500/20 hover:scale-105 transition-all cursor-pointer"
1163
+ >
1164
+ Scan & Generate Suggestions
1165
+ </button>
1166
  </div>
1167
+ )}
1168
+ </div>
1169
+
1170
+ {/* Modal Footer */}
1171
+ <div className="p-3.5 px-5 border-t border-border/70 bg-card/90 flex items-center justify-between text-xs shrink-0">
1172
+ <span className="text-[11px] text-foreground/50">
1173
+ Click copy on any reply option to paste into Telegram
1174
+ </span>
1175
+ <button
1176
+ type="button"
1177
+ onClick={() => setIsSuggestionModalOpen(false)}
1178
+ className="px-3.5 py-1.5 rounded-xl bg-foreground/5 hover:bg-foreground/10 text-foreground font-semibold text-xs transition-colors cursor-pointer"
1179
+ >
1180
+ Close
1181
+ </button>
1182
+ </div>
1183
  </div>
1184
+ </div>
1185
+ )}
1186
+
1187
 
1188
  {/* ==================================================== */}
1189
  {/* AI CONFIGURATION MODAL */}