CBV01 commited on
Commit
0cea1f8
·
1 Parent(s): d26ae7a

feat: Add Fleet Comparator for cross-account group sync & sidebar collapsible divider

Browse files
backend/main.py CHANGED
@@ -957,15 +957,22 @@ async def get_dialogs(req: FetchDialogsRequest, user_id: str = Depends(get_curre
957
 
958
  # Fix for Telethon Megagroups (Supergroups)
959
  is_supergroup = False
 
 
960
  try:
961
- if is_channel and hasattr(dialog.entity, 'megagroup'):
962
- is_supergroup = bool(dialog.entity.megagroup) # type: ignore
 
 
 
963
  except: pass
964
 
965
  dialogs_list.append({
966
  "id": did,
967
  "name": title,
968
  "title": title,
 
 
969
  "is_group": is_group or is_supergroup,
970
  "is_channel": is_channel and not is_supergroup
971
  })
@@ -994,6 +1001,155 @@ async def get_dialogs(req: FetchDialogsRequest, user_id: str = Depends(get_curre
994
  return {"dialogs": [], "error": str(e)}
995
 
996
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
997
  @app.post("/api/telegram/qr/init")
998
  async def qr_init(user_id: str = Depends(get_current_user_id)):
999
  try:
 
957
 
958
  # Fix for Telethon Megagroups (Supergroups)
959
  is_supergroup = False
960
+ username = None
961
+ participants_count = None
962
  try:
963
+ if hasattr(dialog, 'entity') and dialog.entity:
964
+ username = getattr(dialog.entity, 'username', None)
965
+ participants_count = getattr(dialog.entity, 'participants_count', None)
966
+ if is_channel and hasattr(dialog.entity, 'megagroup'):
967
+ is_supergroup = bool(dialog.entity.megagroup) # type: ignore
968
  except: pass
969
 
970
  dialogs_list.append({
971
  "id": did,
972
  "name": title,
973
  "title": title,
974
+ "username": username,
975
+ "participants_count": participants_count,
976
  "is_group": is_group or is_supergroup,
977
  "is_channel": is_channel and not is_supergroup
978
  })
 
1001
  return {"dialogs": [], "error": str(e)}
1002
 
1003
 
1004
+ class CompareAccountsRequest(BaseModel):
1005
+ phone_a: str
1006
+ phone_b: str
1007
+
1008
+ class SingleJoinRequest(BaseModel):
1009
+ phone_number: str
1010
+ target: str
1011
+
1012
+ def _normalize_tg_id(raw_id: Any) -> str:
1013
+ s = str(raw_id).strip()
1014
+ if s.startswith("-100"):
1015
+ return s[4:]
1016
+ if s.startswith("-"):
1017
+ return s[1:]
1018
+ return s
1019
+
1020
+ def _dialogs_match(a: Dict[str, Any], b: Dict[str, Any]) -> bool:
1021
+ id_a = _normalize_tg_id(a.get("id", ""))
1022
+ id_b = _normalize_tg_id(b.get("id", ""))
1023
+ if id_a and id_b and id_a == id_b:
1024
+ return True
1025
+ u_a = (a.get("username") or "").lower().strip().lstrip("@")
1026
+ u_b = (b.get("username") or "").lower().strip().lstrip("@")
1027
+ if u_a and u_b and u_a == u_b:
1028
+ return True
1029
+ return False
1030
+
1031
+ @app.post("/api/telegram/compare")
1032
+ async def compare_accounts(req: CompareAccountsRequest, user_id: str = Depends(get_current_user_id)):
1033
+ """Compare groups and channels between two logged-in accounts."""
1034
+ phone_a = req.phone_a.strip()
1035
+ phone_b = req.phone_b.strip()
1036
+ if not phone_a or not phone_b:
1037
+ raise HTTPException(status_code=400, detail="Please select both Account A and Account B to compare.")
1038
+
1039
+ if phone_a == phone_b:
1040
+ raise HTTPException(status_code=400, detail="Please select two different accounts to compare.")
1041
+
1042
+ client_a = await POOL.get_client(user_id, phone_a)
1043
+ client_b = await POOL.get_client(user_id, phone_b)
1044
+
1045
+ async def _fetch_clean_dialogs(client, phone):
1046
+ items = []
1047
+ async with async_timeout(120):
1048
+ async for dialog in client.iter_dialogs(ignore_migrated=False):
1049
+ if dialog.is_group or dialog.is_channel:
1050
+ did = str(dialog.id)
1051
+ title = getattr(dialog, 'name', '') or getattr(dialog, 'title', '') or did
1052
+ is_group = bool(dialog.is_group)
1053
+ is_channel = bool(dialog.is_channel)
1054
+ is_supergroup = False
1055
+ username = None
1056
+ participants_count = None
1057
+ try:
1058
+ if hasattr(dialog, 'entity') and dialog.entity:
1059
+ username = getattr(dialog.entity, 'username', None)
1060
+ participants_count = getattr(dialog.entity, 'participants_count', None)
1061
+ if is_channel and hasattr(dialog.entity, 'megagroup'):
1062
+ is_supergroup = bool(dialog.entity.megagroup)
1063
+ except: pass
1064
+ items.append({
1065
+ "id": did,
1066
+ "title": title,
1067
+ "name": title,
1068
+ "username": username,
1069
+ "participants_count": participants_count,
1070
+ "is_group": is_group or is_supergroup,
1071
+ "is_channel": is_channel and not is_supergroup
1072
+ })
1073
+ return items
1074
+
1075
+ try:
1076
+ dialogs_a, dialogs_b = await asyncio.gather(
1077
+ _fetch_clean_dialogs(client_a, phone_a),
1078
+ _fetch_clean_dialogs(client_b, phone_b)
1079
+ )
1080
+ except Exception as e:
1081
+ log_debug(f"COMPARE_FETCH_ERR: {e}")
1082
+ raise HTTPException(status_code=500, detail=f"Failed to fetch account dialogs: {str(e)}")
1083
+
1084
+ only_in_a = []
1085
+ in_both = []
1086
+ for item in dialogs_a:
1087
+ match_in_b = next((b for b in dialogs_b if _dialogs_match(item, b)), None)
1088
+ if match_in_b:
1089
+ in_both.append({
1090
+ **item,
1091
+ "present_in": [phone_a, phone_b],
1092
+ "missing_in": [],
1093
+ "can_join_with": None,
1094
+ "join_target": f"@{item['username']}" if item.get("username") else item["id"]
1095
+ })
1096
+ else:
1097
+ only_in_a.append({
1098
+ **item,
1099
+ "present_in": [phone_a],
1100
+ "missing_in": [phone_b],
1101
+ "can_join_with": phone_b,
1102
+ "join_target": f"@{item['username']}" if item.get("username") else item["id"]
1103
+ })
1104
+
1105
+ only_in_b = []
1106
+ for item in dialogs_b:
1107
+ match_in_a = next((a for a in dialogs_a if _dialogs_match(item, a)), None)
1108
+ if not match_in_a:
1109
+ only_in_b.append({
1110
+ **item,
1111
+ "present_in": [phone_b],
1112
+ "missing_in": [phone_a],
1113
+ "can_join_with": phone_a,
1114
+ "join_target": f"@{item['username']}" if item.get("username") else item["id"]
1115
+ })
1116
+
1117
+ return {
1118
+ "status": "success",
1119
+ "account_a": {
1120
+ "phone_number": phone_a,
1121
+ "count": len(dialogs_a)
1122
+ },
1123
+ "account_b": {
1124
+ "phone_number": phone_b,
1125
+ "count": len(dialogs_b)
1126
+ },
1127
+ "stats": {
1128
+ "total_a": len(dialogs_a),
1129
+ "total_b": len(dialogs_b),
1130
+ "only_a_count": len(only_in_a),
1131
+ "only_b_count": len(only_in_b),
1132
+ "both_count": len(in_both)
1133
+ },
1134
+ "only_in_a": only_in_a,
1135
+ "only_in_b": only_in_b,
1136
+ "in_both": in_both
1137
+ }
1138
+
1139
+ @app.post("/api/telegram/join")
1140
+ async def join_single_target(req: SingleJoinRequest, user_id: str = Depends(get_current_user_id)):
1141
+ """Join a single group or channel with a specific account."""
1142
+ client = await POOL.get_client(user_id, req.phone_number)
1143
+ try:
1144
+ await smart_join(client, req.target, user_id, req.phone_number)
1145
+ return {"status": "success", "message": f"Successfully joined {req.target}"}
1146
+ except Exception as e:
1147
+ err_msg = str(e)
1148
+ if "flood" in err_msg.lower():
1149
+ raise HTTPException(status_code=429, detail="Telegram rate limit (FloodWait). Please wait a few moments before joining again.")
1150
+ raise HTTPException(status_code=400, detail=f"Join failed: {err_msg}")
1151
+
1152
+
1153
  @app.post("/api/telegram/qr/init")
1154
  async def qr_init(user_id: str = Depends(get_current_user_id)):
1155
  try:
frontend/src/app/accounts/page.tsx CHANGED
@@ -1,6 +1,7 @@
1
  "use client";
2
 
3
  import React, { useState, useEffect } from 'react';
 
4
  import {
5
  Phone,
6
  KeyRound,
@@ -16,7 +17,8 @@ import {
16
  Check,
17
  Search,
18
  ChevronRight,
19
- ChevronDown
 
20
  } from 'lucide-react';
21
  import { apiFetch } from '@/lib/auth';
22
  import { Preloader } from '@/components/Preloader';
@@ -353,6 +355,15 @@ export default function AccountsPage() {
353
  </div>
354
  </div>
355
 
 
 
 
 
 
 
 
 
 
356
  {/* Connect Button */}
357
  <button
358
  onClick={() => {
 
1
  "use client";
2
 
3
  import React, { useState, useEffect } from 'react';
4
+ import Link from 'next/link';
5
  import {
6
  Phone,
7
  KeyRound,
 
17
  Check,
18
  Search,
19
  ChevronRight,
20
+ ChevronDown,
21
+ ArrowLeftRight
22
  } from 'lucide-react';
23
  import { apiFetch } from '@/lib/auth';
24
  import { Preloader } from '@/components/Preloader';
 
355
  </div>
356
  </div>
357
 
358
+ {/* Compare Fleet Button */}
359
+ <Link
360
+ href="/compare"
361
+ className="bg-card hover:bg-foreground/5 border border-border/80 text-foreground/80 hover:text-foreground px-4 py-2.5 rounded-xl text-xs font-semibold shadow-xs transition-all flex items-center gap-2 shrink-0 cursor-pointer"
362
+ >
363
+ <ArrowLeftRight size={15} className="text-indigo-400" />
364
+ <span>Compare Fleet</span>
365
+ </Link>
366
+
367
  {/* Connect Button */}
368
  <button
369
  onClick={() => {
frontend/src/app/compare/page.tsx ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import React, { useState, useEffect } from 'react';
4
+ import {
5
+ ArrowLeftRight,
6
+ Users,
7
+ CheckCircle2,
8
+ AlertCircle,
9
+ Loader2,
10
+ Search,
11
+ Filter,
12
+ Share2,
13
+ ExternalLink,
14
+ Plus,
15
+ Check,
16
+ Radio,
17
+ Layers,
18
+ Zap,
19
+ ShieldCheck,
20
+ Copy,
21
+ UserCheck,
22
+ RefreshCw,
23
+ SlidersHorizontal,
24
+ Tv,
25
+ MessageSquare
26
+ } from 'lucide-react';
27
+ import Link from 'next/link';
28
+ import { apiFetch } from '@/lib/auth';
29
+ import { Preloader } from '@/components/Preloader';
30
+
31
+ interface DialogItem {
32
+ id: string;
33
+ title: string;
34
+ name?: string;
35
+ username?: string | null;
36
+ participants_count?: number | null;
37
+ is_group: boolean;
38
+ is_channel: boolean;
39
+ present_in: string[];
40
+ missing_in: string[];
41
+ can_join_with?: string | null;
42
+ join_target?: string;
43
+ }
44
+
45
+ interface AccountItem {
46
+ id: number;
47
+ phone_number: string;
48
+ first_name?: string;
49
+ last_name?: string;
50
+ username?: string;
51
+ status: string;
52
+ country?: string;
53
+ }
54
+
55
+ export default function ComparePage() {
56
+ const [accounts, setAccounts] = useState<AccountItem[]>([]);
57
+ const [phoneA, setPhoneA] = useState<string>('');
58
+ const [phoneB, setPhoneB] = useState<string>('');
59
+ const [loadingAccounts, setLoadingAccounts] = useState(true);
60
+ const [comparing, setComparing] = useState(false);
61
+ const [error, setError] = useState<string>('');
62
+ const [successMsg, setSuccessMsg] = useState<string>('');
63
+
64
+ // Comparison Results
65
+ const [resultData, setResultData] = useState<{
66
+ stats: {
67
+ total_a: number;
68
+ total_b: number;
69
+ only_a_count: number;
70
+ only_b_count: number;
71
+ both_count: number;
72
+ };
73
+ only_in_a: DialogItem[];
74
+ only_in_b: DialogItem[];
75
+ in_both: DialogItem[];
76
+ } | null>(null);
77
+
78
+ // Filter and Tab state
79
+ const [activeTab, setActiveTab] = useState<'only_a' | 'only_b' | 'all_diff' | 'both'>('only_a');
80
+ const [searchTerm, setSearchTerm] = useState('');
81
+ const [filterType, setFilterType] = useState<'all' | 'groups' | 'channels'>('all');
82
+
83
+ // Action States (for single item joining & batch joining)
84
+ const [joiningId, setJoiningId] = useState<string | null>(null);
85
+ const [batchJoining, setBatchJoining] = useState(false);
86
+ const [batchProgress, setBatchProgress] = useState<{ current: number; total: number; msg: string } | null>(null);
87
+ const [copiedTarget, setCopiedTarget] = useState<string | null>(null);
88
+
89
+ // Fetch accounts on mount
90
+ useEffect(() => {
91
+ fetchAccounts();
92
+ }, []);
93
+
94
+ const fetchAccounts = async () => {
95
+ setLoadingAccounts(true);
96
+ try {
97
+ const res = await apiFetch('/api/telegram/accounts');
98
+ if (res.ok) {
99
+ const data = await res.json();
100
+ const list: AccountItem[] = data.accounts || [];
101
+ setAccounts(list);
102
+ if (list.length >= 2) {
103
+ setPhoneA(list[0].phone_number);
104
+ setPhoneB(list[1].phone_number);
105
+ } else if (list.length === 1) {
106
+ setPhoneA(list[0].phone_number);
107
+ }
108
+ }
109
+ } catch (err: any) {
110
+ console.error("Failed to load accounts", err);
111
+ } finally {
112
+ setLoadingAccounts(false);
113
+ }
114
+ };
115
+
116
+ const runComparison = async (overrideA?: string, overrideB?: string) => {
117
+ const targetA = overrideA || phoneA;
118
+ const targetB = overrideB || phoneB;
119
+
120
+ if (!targetA || !targetB) {
121
+ setError("Please select both Account A and Account B to compare.");
122
+ return;
123
+ }
124
+
125
+ if (targetA === targetB) {
126
+ setError("Please select two distinct accounts to compare.");
127
+ return;
128
+ }
129
+
130
+ setError('');
131
+ setSuccessMsg('');
132
+ setComparing(true);
133
+
134
+ try {
135
+ const res = await apiFetch('/api/telegram/compare', {
136
+ method: 'POST',
137
+ body: JSON.stringify({
138
+ phone_a: targetA,
139
+ phone_b: targetB
140
+ })
141
+ });
142
+
143
+ const data = await res.json();
144
+ if (res.ok && data.status === 'success') {
145
+ setResultData({
146
+ stats: data.stats,
147
+ only_in_a: data.only_in_a || [],
148
+ only_in_b: data.only_in_b || [],
149
+ in_both: data.in_both || []
150
+ });
151
+ // Default to whichever side has items to join
152
+ if ((data.only_in_a || []).length > 0) {
153
+ setActiveTab('only_a');
154
+ } else if ((data.only_in_b || []).length > 0) {
155
+ setActiveTab('only_b');
156
+ } else {
157
+ setActiveTab('both');
158
+ }
159
+ } else {
160
+ setError(data.detail || data.error || "Failed to compare accounts.");
161
+ }
162
+ } catch (err: any) {
163
+ setError(err.message || "Network error occurred while comparing.");
164
+ } finally {
165
+ setComparing(false);
166
+ }
167
+ };
168
+
169
+ const handleSwap = () => {
170
+ const newA = phoneB;
171
+ const newB = phoneA;
172
+ setPhoneA(newA);
173
+ setPhoneB(newB);
174
+ if (resultData) {
175
+ runComparison(newA, newB);
176
+ }
177
+ };
178
+
179
+ const handleJoinSingle = async (targetPhone: string, groupItem: DialogItem) => {
180
+ const target = groupItem.join_target || (groupItem.username ? `@${groupItem.username}` : groupItem.id);
181
+ setJoiningId(groupItem.id);
182
+ setError('');
183
+
184
+ try {
185
+ const res = await apiFetch('/api/telegram/join', {
186
+ method: 'POST',
187
+ body: JSON.stringify({
188
+ phone_number: targetPhone,
189
+ target: target
190
+ })
191
+ });
192
+
193
+ const data = await res.json();
194
+ if (res.ok) {
195
+ setSuccessMsg(`Joined "${groupItem.title}" with account ${targetPhone}`);
196
+ // Move item from missing to in_both in local state for instantaneous UI gratification
197
+ if (resultData) {
198
+ const updatedOnlyA = resultData.only_in_a.filter(i => i.id !== groupItem.id);
199
+ const updatedOnlyB = resultData.only_in_b.filter(i => i.id !== groupItem.id);
200
+ const joinedItem: DialogItem = {
201
+ ...groupItem,
202
+ present_in: [phoneA, phoneB],
203
+ missing_in: [],
204
+ can_join_with: null
205
+ };
206
+ setResultData({
207
+ stats: {
208
+ ...resultData.stats,
209
+ only_a_count: updatedOnlyA.length,
210
+ only_b_count: updatedOnlyB.length,
211
+ both_count: resultData.stats.both_count + 1
212
+ },
213
+ only_in_a: updatedOnlyA,
214
+ only_in_b: updatedOnlyB,
215
+ in_both: [joinedItem, ...resultData.in_both]
216
+ });
217
+ }
218
+ setTimeout(() => setSuccessMsg(''), 4000);
219
+ } else {
220
+ setError(data.detail || "Join request was declined by Telegram.");
221
+ }
222
+ } catch (err: any) {
223
+ setError(err.message || "Failed to join group.");
224
+ } finally {
225
+ setJoiningId(null);
226
+ }
227
+ };
228
+
229
+ const handleBatchJoin = async (targetPhone: string, itemsToJoin: DialogItem[]) => {
230
+ if (!itemsToJoin.length) return;
231
+ if (!confirm(`Are you sure you want ${targetPhone} to sequentially join ${itemsToJoin.length} missing groups/channels?`)) return;
232
+
233
+ setBatchJoining(true);
234
+ setError('');
235
+ setSuccessMsg('');
236
+ setBatchProgress({ current: 0, total: itemsToJoin.length, msg: 'Initializing batch synchronization...' });
237
+
238
+ let joinedCount = 0;
239
+ let failCount = 0;
240
+
241
+ for (let i = 0; i < itemsToJoin.length; i++) {
242
+ const item = itemsToJoin[i];
243
+ const target = item.join_target || (item.username ? `@${item.username}` : item.id);
244
+ setBatchProgress({
245
+ current: i + 1,
246
+ total: itemsToJoin.length,
247
+ msg: `Joining (${i + 1}/${itemsToJoin.length}): ${item.title}...`
248
+ });
249
+
250
+ try {
251
+ const res = await apiFetch('/api/telegram/join', {
252
+ method: 'POST',
253
+ body: JSON.stringify({
254
+ phone_number: targetPhone,
255
+ target: target
256
+ })
257
+ });
258
+ if (res.ok) {
259
+ joinedCount++;
260
+ } else {
261
+ failCount++;
262
+ }
263
+ } catch (e) {
264
+ failCount++;
265
+ }
266
+
267
+ // Small delay to protect account safety
268
+ if (i < itemsToJoin.length - 1) {
269
+ await new Promise(r => setTimeout(r, 4000));
270
+ }
271
+ }
272
+
273
+ setBatchJoining(false);
274
+ setBatchProgress(null);
275
+ setSuccessMsg(`Batch completed: ${joinedCount} groups joined, ${failCount} skipped or restricted.`);
276
+ // Refresh comparison
277
+ runComparison();
278
+ };
279
+
280
+ const copyToClipboard = (text: string, id: string) => {
281
+ navigator.clipboard.writeText(text);
282
+ setCopiedTarget(id);
283
+ setTimeout(() => setCopiedTarget(null), 2000);
284
+ };
285
+
286
+ // Current tab items computation
287
+ let currentItems: DialogItem[] = [];
288
+ if (resultData) {
289
+ if (activeTab === 'only_a') {
290
+ currentItems = resultData.only_in_a;
291
+ } else if (activeTab === 'only_b') {
292
+ currentItems = resultData.only_in_b;
293
+ } else if (activeTab === 'all_diff') {
294
+ currentItems = [...resultData.only_in_a, ...resultData.only_in_b];
295
+ } else {
296
+ currentItems = resultData.in_both;
297
+ }
298
+ }
299
+
300
+ const filteredItems = currentItems.filter(item => {
301
+ const matchesSearch =
302
+ item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
303
+ (item.username || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
304
+ item.id.includes(searchTerm);
305
+
306
+ if (filterType === 'groups') return matchesSearch && item.is_group;
307
+ if (filterType === 'channels') return matchesSearch && item.is_channel;
308
+ return matchesSearch;
309
+ });
310
+
311
+ const accountAObj = accounts.find(a => a.phone_number === phoneA);
312
+ const accountBObj = accounts.find(a => a.phone_number === phoneB);
313
+
314
+ return (
315
+ <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
316
+ {/* Sticky Header Section */}
317
+ <header className="sticky top-16 md:top-0 z-20 bg-background/90 backdrop-blur-md pt-2 pb-5 mb-6 border-b border-border/50 transition-all flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
318
+ <div>
319
+ <div className="flex items-center gap-2.5">
320
+ <div className="w-8 h-8 rounded-xl bg-indigo-500/10 flex items-center justify-center text-indigo-500 border border-indigo-500/20">
321
+ <ArrowLeftRight size={18} />
322
+ </div>
323
+ <h2 className="text-2xl font-bold tracking-tight text-foreground">
324
+ Fleet <span className="text-indigo-500">Comparator</span>
325
+ </h2>
326
+ <span className="px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-indigo-500/10 text-indigo-400 border border-indigo-500/20">
327
+ Sync Engine
328
+ </span>
329
+ </div>
330
+ <p className="text-xs text-foreground/50 font-medium mt-1">
331
+ Compare group & channel memberships between accounts. Identify missing targets and auto-sync memberships in 1 click.
332
+ </p>
333
+ </div>
334
+
335
+ <div className="flex items-center gap-3">
336
+ <Link
337
+ href="/accounts"
338
+ className="bg-card hover:bg-foreground/5 border border-border/80 text-foreground/80 hover:text-foreground px-4 py-2 rounded-xl text-xs font-semibold transition-all flex items-center gap-2 shadow-xs cursor-pointer"
339
+ >
340
+ <Users size={14} />
341
+ <span>Manage Fleet</span>
342
+ </Link>
343
+ </div>
344
+ </header>
345
+
346
+ {/* Error & Success Banners */}
347
+ {error && (
348
+ <div className="p-4 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-500 text-xs font-medium flex items-center justify-between animate-in fade-in">
349
+ <div className="flex items-center gap-2">
350
+ <AlertCircle size={16} />
351
+ <span>{error}</span>
352
+ </div>
353
+ <button onClick={() => setError('')} className="text-rose-500/60 hover:text-rose-500 text-xs">Dismiss</button>
354
+ </div>
355
+ )}
356
+
357
+ {successMsg && (
358
+ <div className="p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs font-medium flex items-center justify-between animate-in fade-in">
359
+ <div className="flex items-center gap-2">
360
+ <CheckCircle2 size={16} />
361
+ <span>{successMsg}</span>
362
+ </div>
363
+ <button onClick={() => setSuccessMsg('')} className="text-emerald-400/60 hover:text-emerald-400 text-xs">Dismiss</button>
364
+ </div>
365
+ )}
366
+
367
+ {/* Account Comparison Selection Card */}
368
+ <div className="bg-card border border-border/80 rounded-2xl p-6 shadow-sm relative overflow-hidden">
369
+ <div className="absolute top-0 right-0 w-96 h-96 bg-indigo-500/5 rounded-full blur-3xl pointer-events-none" />
370
+
371
+ <div className="flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-6 relative z-10">
372
+ {/* Account A Card */}
373
+ <div className="flex-1 bg-background/50 border border-border/70 rounded-xl p-4.5 transition-all focus-within:border-indigo-500/50">
374
+ <div className="flex items-center justify-between mb-2">
375
+ <span className="text-[10px] font-black uppercase tracking-wider text-indigo-400 bg-indigo-500/10 px-2 py-0.5 rounded-md border border-indigo-500/20">
376
+ Primary Account A
377
+ </span>
378
+ {accountAObj && (
379
+ <span className="text-[11px] font-medium text-foreground/40">
380
+ {accountAObj.country || 'Telegram Node'}
381
+ </span>
382
+ )}
383
+ </div>
384
+ <select
385
+ value={phoneA}
386
+ onChange={(e) => setPhoneA(e.target.value)}
387
+ className="w-full bg-card border border-border rounded-lg py-2.5 px-3 text-xs font-semibold text-foreground focus:ring-2 focus:ring-indigo-500/20 outline-none transition-all cursor-pointer"
388
+ disabled={loadingAccounts || comparing}
389
+ >
390
+ <option value="">Select Account A...</option>
391
+ {accounts.map(acc => (
392
+ <option key={`a-${acc.phone_number}`} value={acc.phone_number}>
393
+ {acc.first_name ? `${acc.first_name} (${acc.phone_number})` : acc.phone_number}
394
+ </option>
395
+ ))}
396
+ </select>
397
+ {resultData && (
398
+ <p className="text-[11px] text-foreground/50 mt-2 font-medium">
399
+ Total Memberships: <span className="text-foreground font-bold">{resultData.stats.total_a}</span> groups & channels
400
+ </p>
401
+ )}
402
+ </div>
403
+
404
+ {/* Swap & Compare Action Center */}
405
+ <div className="flex flex-row lg:flex-col items-center justify-center gap-3">
406
+ <button
407
+ onClick={handleSwap}
408
+ disabled={comparing || !phoneA || !phoneB}
409
+ className="w-10 h-10 rounded-xl bg-card border border-border/80 hover:border-indigo-500/50 text-foreground/60 hover:text-indigo-400 flex items-center justify-center transition-all active:scale-95 shadow-xs cursor-pointer disabled:opacity-40"
410
+ title="Swap Account A & B"
411
+ >
412
+ <ArrowLeftRight size={18} />
413
+ </button>
414
+ </div>
415
+
416
+ {/* Account B Card */}
417
+ <div className="flex-1 bg-background/50 border border-border/70 rounded-xl p-4.5 transition-all focus-within:border-indigo-500/50">
418
+ <div className="flex items-center justify-between mb-2">
419
+ <span className="text-[10px] font-black uppercase tracking-wider text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded-md border border-purple-500/20">
420
+ Target Account B
421
+ </span>
422
+ {accountBObj && (
423
+ <span className="text-[11px] font-medium text-foreground/40">
424
+ {accountBObj.country || 'Telegram Node'}
425
+ </span>
426
+ )}
427
+ </div>
428
+ <select
429
+ value={phoneB}
430
+ onChange={(e) => setPhoneB(e.target.value)}
431
+ className="w-full bg-card border border-border rounded-lg py-2.5 px-3 text-xs font-semibold text-foreground focus:ring-2 focus:ring-indigo-500/20 outline-none transition-all cursor-pointer"
432
+ disabled={loadingAccounts || comparing}
433
+ >
434
+ <option value="">Select Account B...</option>
435
+ {accounts.map(acc => (
436
+ <option key={`b-${acc.phone_number}`} value={acc.phone_number}>
437
+ {acc.first_name ? `${acc.first_name} (${acc.phone_number})` : acc.phone_number}
438
+ </option>
439
+ ))}
440
+ </select>
441
+ {resultData && (
442
+ <p className="text-[11px] text-foreground/50 mt-2 font-medium">
443
+ Total Memberships: <span className="text-foreground font-bold">{resultData.stats.total_b}</span> groups & channels
444
+ </p>
445
+ )}
446
+ </div>
447
+
448
+ {/* Run Button */}
449
+ <div className="flex items-center">
450
+ <button
451
+ onClick={() => runComparison()}
452
+ disabled={comparing || !phoneA || !phoneB}
453
+ className="w-full lg:w-auto bg-gradient-to-r from-indigo-500 to-indigo-600 hover:from-indigo-600 hover:to-indigo-700 text-white font-semibold px-6 py-4 rounded-xl text-xs shadow-lg shadow-indigo-500/25 transition-all flex items-center justify-center gap-2.5 active:scale-95 cursor-pointer disabled:opacity-50"
454
+ >
455
+ {comparing ? (
456
+ <>
457
+ <Loader2 size={16} className="animate-spin" />
458
+ <span>Scanning Fleet...</span>
459
+ </>
460
+ ) : (
461
+ <>
462
+ <Zap size={16} />
463
+ <span>Compare Accounts</span>
464
+ </>
465
+ )}
466
+ </button>
467
+ </div>
468
+ </div>
469
+ </div>
470
+
471
+ {/* Results Section */}
472
+ {comparing ? (
473
+ <Preloader message="Scanning and intersecting Telegram membership telemetry..." />
474
+ ) : resultData ? (
475
+ <div className="space-y-6">
476
+ {/* KPI Summary Cards */}
477
+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3.5">
478
+ <div className="bg-card border border-border/80 rounded-2xl p-4 flex flex-col justify-between">
479
+ <span className="text-[10px] font-bold text-foreground/40 uppercase tracking-wider">Account A Total</span>
480
+ <div className="flex items-baseline gap-2 mt-2">
481
+ <span className="text-2xl font-black text-foreground">{resultData.stats.total_a}</span>
482
+ <span className="text-[10px] font-medium text-foreground/40">groups</span>
483
+ </div>
484
+ <div className="text-[10px] text-indigo-400 font-semibold truncate mt-1">{phoneA}</div>
485
+ </div>
486
+
487
+ <div className="bg-card border border-border/80 rounded-2xl p-4 flex flex-col justify-between">
488
+ <span className="text-[10px] font-bold text-foreground/40 uppercase tracking-wider">Account B Total</span>
489
+ <div className="flex items-baseline gap-2 mt-2">
490
+ <span className="text-2xl font-black text-foreground">{resultData.stats.total_b}</span>
491
+ <span className="text-[10px] font-medium text-foreground/40">groups</span>
492
+ </div>
493
+ <div className="text-[10px] text-purple-400 font-semibold truncate mt-1">{phoneB}</div>
494
+ </div>
495
+
496
+ <div className="bg-card border border-amber-500/30 bg-amber-500/5 rounded-2xl p-4 flex flex-col justify-between">
497
+ <span className="text-[10px] font-bold text-amber-400 uppercase tracking-wider flex items-center gap-1">
498
+ <AlertCircle size={12} />
499
+ Missing in B
500
+ </span>
501
+ <div className="flex items-baseline gap-2 mt-2">
502
+ <span className="text-2xl font-black text-amber-400">{resultData.stats.only_a_count}</span>
503
+ <span className="text-[10px] font-medium text-amber-400/60">can join</span>
504
+ </div>
505
+ <span className="text-[10px] text-foreground/40 font-medium mt-1">In Account A only</span>
506
+ </div>
507
+
508
+ <div className="bg-card border border-rose-500/30 bg-rose-500/5 rounded-2xl p-4 flex flex-col justify-between">
509
+ <span className="text-[10px] font-bold text-rose-400 uppercase tracking-wider flex items-center gap-1">
510
+ <AlertCircle size={12} />
511
+ Missing in A
512
+ </span>
513
+ <div className="flex items-baseline gap-2 mt-2">
514
+ <span className="text-2xl font-black text-rose-400">{resultData.stats.only_b_count}</span>
515
+ <span className="text-[10px] font-medium text-rose-400/60">can join</span>
516
+ </div>
517
+ <span className="text-[10px] text-foreground/40 font-medium mt-1">In Account B only</span>
518
+ </div>
519
+
520
+ <div className="bg-card border border-emerald-500/30 bg-emerald-500/5 rounded-2xl p-4 flex flex-col justify-between col-span-2 sm:col-span-1">
521
+ <span className="text-[10px] font-bold text-emerald-400 uppercase tracking-wider flex items-center gap-1">
522
+ <ShieldCheck size={12} />
523
+ Synchronized
524
+ </span>
525
+ <div className="flex items-baseline gap-2 mt-2">
526
+ <span className="text-2xl font-black text-emerald-400">{resultData.stats.both_count}</span>
527
+ <span className="text-[10px] font-medium text-emerald-400/60">shared</span>
528
+ </div>
529
+ <span className="text-[10px] text-foreground/40 font-medium mt-1">Both accounts member</span>
530
+ </div>
531
+ </div>
532
+
533
+ {/* Batch Synchronization Banner */}
534
+ {batchProgress && (
535
+ <div className="p-4 rounded-2xl bg-indigo-500/10 border border-indigo-500/20 space-y-2 animate-in fade-in">
536
+ <div className="flex items-center justify-between text-xs font-semibold text-indigo-400">
537
+ <div className="flex items-center gap-2">
538
+ <Loader2 size={15} className="animate-spin" />
539
+ <span>{batchProgress.msg}</span>
540
+ </div>
541
+ <span>{batchProgress.current} / {batchProgress.total}</span>
542
+ </div>
543
+ <div className="h-1.5 w-full bg-foreground/5 rounded-full overflow-hidden">
544
+ <div
545
+ className="h-full bg-indigo-500 transition-all duration-300"
546
+ style={{ width: `${Math.round((batchProgress.current / batchProgress.total) * 100)}%` }}
547
+ />
548
+ </div>
549
+ </div>
550
+ )}
551
+
552
+ {/* Tab Navigation and Action Bar */}
553
+ <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4 bg-card border border-border/80 p-3.5 rounded-2xl">
554
+ {/* Segmented Filter Pills */}
555
+ <div className="flex flex-wrap items-center gap-1.5 bg-background/60 p-1 rounded-xl border border-border/60">
556
+ <button
557
+ onClick={() => setActiveTab('only_a')}
558
+ className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center gap-1.5 cursor-pointer ${activeTab === 'only_a' ? 'bg-indigo-500 text-white shadow-xs' : 'text-foreground/60 hover:text-foreground'}`}
559
+ >
560
+ <span>Missing in B</span>
561
+ <span className={`text-[10px] px-1.5 py-0.2 rounded-md ${activeTab === 'only_a' ? 'bg-white/20 text-white' : 'bg-foreground/5 text-foreground/50'}`}>
562
+ {resultData.stats.only_a_count}
563
+ </span>
564
+ </button>
565
+
566
+ <button
567
+ onClick={() => setActiveTab('only_b')}
568
+ className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center gap-1.5 cursor-pointer ${activeTab === 'only_b' ? 'bg-indigo-500 text-white shadow-xs' : 'text-foreground/60 hover:text-foreground'}`}
569
+ >
570
+ <span>Missing in A</span>
571
+ <span className={`text-[10px] px-1.5 py-0.2 rounded-md ${activeTab === 'only_b' ? 'bg-white/20 text-white' : 'bg-foreground/5 text-foreground/50'}`}>
572
+ {resultData.stats.only_b_count}
573
+ </span>
574
+ </button>
575
+
576
+ <button
577
+ onClick={() => setActiveTab('all_diff')}
578
+ className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center gap-1.5 cursor-pointer ${activeTab === 'all_diff' ? 'bg-indigo-500 text-white shadow-xs' : 'text-foreground/60 hover:text-foreground'}`}
579
+ >
580
+ <span>All Differences</span>
581
+ <span className={`text-[10px] px-1.5 py-0.2 rounded-md ${activeTab === 'all_diff' ? 'bg-white/20 text-white' : 'bg-foreground/5 text-foreground/50'}`}>
582
+ {resultData.stats.only_a_count + resultData.stats.only_b_count}
583
+ </span>
584
+ </button>
585
+
586
+ <button
587
+ onClick={() => setActiveTab('both')}
588
+ className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center gap-1.5 cursor-pointer ${activeTab === 'both' ? 'bg-indigo-500 text-white shadow-xs' : 'text-foreground/60 hover:text-foreground'}`}
589
+ >
590
+ <span>Shared in Both</span>
591
+ <span className={`text-[10px] px-1.5 py-0.2 rounded-md ${activeTab === 'both' ? 'bg-white/20 text-white' : 'bg-foreground/5 text-foreground/50'}`}>
592
+ {resultData.stats.both_count}
593
+ </span>
594
+ </button>
595
+ </div>
596
+
597
+ {/* Batch Action Buttons */}
598
+ <div className="flex flex-wrap items-center gap-2 w-full md:w-auto justify-end">
599
+ {activeTab === 'only_a' && resultData.stats.only_a_count > 0 && (
600
+ <button
601
+ onClick={() => handleBatchJoin(phoneB, resultData.only_in_a)}
602
+ disabled={batchJoining}
603
+ className="bg-amber-500 hover:bg-amber-600 text-white px-3.5 py-2 rounded-xl text-xs font-bold shadow-md shadow-amber-500/20 flex items-center gap-2 transition-all active:scale-95 cursor-pointer disabled:opacity-50"
604
+ >
605
+ <Zap size={14} />
606
+ <span>Sync All to Account B ({resultData.stats.only_a_count})</span>
607
+ </button>
608
+ )}
609
+
610
+ {activeTab === 'only_b' && resultData.stats.only_b_count > 0 && (
611
+ <button
612
+ onClick={() => handleBatchJoin(phoneA, resultData.only_in_b)}
613
+ disabled={batchJoining}
614
+ className="bg-rose-500 hover:bg-rose-600 text-white px-3.5 py-2 rounded-xl text-xs font-bold shadow-md shadow-rose-500/20 flex items-center gap-2 transition-all active:scale-95 cursor-pointer disabled:opacity-50"
615
+ >
616
+ <Zap size={14} />
617
+ <span>Sync All to Account A ({resultData.stats.only_b_count})</span>
618
+ </button>
619
+ )}
620
+ </div>
621
+ </div>
622
+
623
+ {/* Filter & Search Bar */}
624
+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
625
+ <div className="relative flex-1 group">
626
+ <div className="absolute left-3.5 top-1/2 -translate-y-1/2 text-foreground/30 group-focus-within:text-indigo-500 transition-colors">
627
+ <Search size={15} />
628
+ </div>
629
+ <input
630
+ type="text"
631
+ placeholder="Search by group title, @username, or Telegram ID..."
632
+ value={searchTerm}
633
+ onChange={(e) => setSearchTerm(e.target.value)}
634
+ className="w-full bg-card border border-border/80 rounded-xl py-2 pl-10 pr-4 text-xs text-foreground placeholder:text-foreground/30 focus:ring-2 focus:ring-indigo-500/20 outline-none transition-all shadow-xs"
635
+ />
636
+ </div>
637
+
638
+ <div className="flex items-center gap-1.5 bg-card border border-border/80 p-1 rounded-xl shrink-0 self-end sm:self-auto">
639
+ <button
640
+ onClick={() => setFilterType('all')}
641
+ className={`px-2.5 py-1 rounded-lg text-xs font-medium cursor-pointer transition-all ${filterType === 'all' ? 'bg-indigo-500 text-white' : 'text-foreground/50 hover:text-foreground'}`}
642
+ >
643
+ All
644
+ </button>
645
+ <button
646
+ onClick={() => setFilterType('groups')}
647
+ className={`px-2.5 py-1 rounded-lg text-xs font-medium cursor-pointer transition-all ${filterType === 'groups' ? 'bg-indigo-500 text-white' : 'text-foreground/50 hover:text-foreground'}`}
648
+ >
649
+ Groups
650
+ </button>
651
+ <button
652
+ onClick={() => setFilterType('channels')}
653
+ className={`px-2.5 py-1 rounded-lg text-xs font-medium cursor-pointer transition-all ${filterType === 'channels' ? 'bg-indigo-500 text-white' : 'text-foreground/50 hover:text-foreground'}`}
654
+ >
655
+ Channels
656
+ </button>
657
+ </div>
658
+ </div>
659
+
660
+ {/* Group / Channel Cards List */}
661
+ {filteredItems.length === 0 ? (
662
+ <div className="bg-card border border-border/80 rounded-2xl p-12 text-center flex flex-col items-center justify-center">
663
+ <div className="w-12 h-12 rounded-2xl bg-indigo-500/10 flex items-center justify-center text-indigo-500 mb-3 border border-indigo-500/20">
664
+ <CheckCircle2 size={24} />
665
+ </div>
666
+ <h4 className="text-base font-bold text-foreground">No Items in this Category</h4>
667
+ <p className="text-xs text-foreground/40 max-w-sm mt-1">
668
+ {searchTerm ? "No groups or channels match your current search criteria." : "All groups and channels between the accounts are fully synchronized for this view."}
669
+ </p>
670
+ </div>
671
+ ) : (
672
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3.5">
673
+ {filteredItems.map(item => {
674
+ const isMissingInB = item.missing_in.includes(phoneB);
675
+ const isMissingInA = item.missing_in.includes(phoneA);
676
+ const isShared = item.present_in.includes(phoneA) && item.present_in.includes(phoneB);
677
+ const targetPhone = item.can_join_with;
678
+ const isThisJoining = joiningId === item.id;
679
+ const targetString = item.join_target || (item.username ? `@${item.username}` : item.id);
680
+
681
+ return (
682
+ <div
683
+ key={`${item.id}-${item.title}`}
684
+ className="bg-card border border-border/80 hover:border-indigo-500/40 rounded-2xl p-4 transition-all flex flex-col justify-between group shadow-xs"
685
+ >
686
+ <div>
687
+ {/* Type Badge & Quick ID */}
688
+ <div className="flex items-center justify-between gap-2 mb-2">
689
+ <div className="flex items-center gap-1.5">
690
+ <span className={`px-2 py-0.5 rounded-md text-[9px] font-black uppercase tracking-wider border flex items-center gap-1 ${
691
+ item.is_channel
692
+ ? 'bg-blue-500/10 text-blue-400 border-blue-500/20'
693
+ : 'bg-indigo-500/10 text-indigo-400 border-indigo-500/20'
694
+ }`}>
695
+ {item.is_channel ? <Tv size={10} /> : <MessageSquare size={10} />}
696
+ {item.is_channel ? 'Channel' : 'Group'}
697
+ </span>
698
+
699
+ {item.participants_count ? (
700
+ <span className="text-[10px] font-semibold text-foreground/40 flex items-center gap-1">
701
+ <Users size={11} />
702
+ {item.participants_count.toLocaleString()}
703
+ </span>
704
+ ) : null}
705
+ </div>
706
+
707
+ <button
708
+ onClick={() => copyToClipboard(targetString, item.id)}
709
+ className="text-foreground/30 hover:text-foreground text-[10px] font-mono flex items-center gap-1 hover:bg-foreground/5 px-1.5 py-0.5 rounded transition-all cursor-pointer"
710
+ title="Copy identifier"
711
+ >
712
+ {copiedTarget === item.id ? (
713
+ <>
714
+ <Check size={11} className="text-emerald-400" />
715
+ <span className="text-emerald-400">Copied</span>
716
+ </>
717
+ ) : (
718
+ <>
719
+ <Copy size={11} />
720
+ <span>Copy</span>
721
+ </>
722
+ )}
723
+ </button>
724
+ </div>
725
+
726
+ {/* Title & Username */}
727
+ <h4 className="text-sm font-bold text-foreground leading-snug line-clamp-1 group-hover:text-indigo-400 transition-colors">
728
+ {item.title}
729
+ </h4>
730
+
731
+ <div className="flex items-center gap-2 mt-1">
732
+ {item.username ? (
733
+ <span className="text-xs font-mono font-medium text-indigo-400/90 flex items-center gap-1">
734
+ @{item.username}
735
+ </span>
736
+ ) : (
737
+ <span className="text-[11px] font-mono text-foreground/40">
738
+ ID: {item.id}
739
+ </span>
740
+ )}
741
+ </div>
742
+
743
+ {/* Presence Matrix Indicator */}
744
+ <div className="mt-3 pt-3 border-t border-border/50 space-y-1.5">
745
+ <div className="flex items-center justify-between text-[11px]">
746
+ <span className="text-foreground/50 font-medium">Account A ({phoneA.slice(-4)}):</span>
747
+ {item.present_in.includes(phoneA) ? (
748
+ <span className="text-emerald-400 font-bold flex items-center gap-1">
749
+ <Check size={12} /> Joined
750
+ </span>
751
+ ) : (
752
+ <span className="text-amber-400/80 font-bold flex items-center gap-1">
753
+ <AlertCircle size={12} /> Missing
754
+ </span>
755
+ )}
756
+ </div>
757
+
758
+ <div className="flex items-center justify-between text-[11px]">
759
+ <span className="text-foreground/50 font-medium">Account B ({phoneB.slice(-4)}):</span>
760
+ {item.present_in.includes(phoneB) ? (
761
+ <span className="text-emerald-400 font-bold flex items-center gap-1">
762
+ <Check size={12} /> Joined
763
+ </span>
764
+ ) : (
765
+ <span className="text-amber-400/80 font-bold flex items-center gap-1">
766
+ <AlertCircle size={12} /> Missing
767
+ </span>
768
+ )}
769
+ </div>
770
+ </div>
771
+ </div>
772
+
773
+ {/* Action Button */}
774
+ <div className="mt-4 pt-2">
775
+ {isShared ? (
776
+ <div className="w-full py-2 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs font-bold flex items-center justify-center gap-1.5">
777
+ <Check size={14} />
778
+ <span>Present in Both</span>
779
+ </div>
780
+ ) : targetPhone ? (
781
+ <button
782
+ onClick={() => handleJoinSingle(targetPhone, item)}
783
+ disabled={isThisJoining || batchJoining}
784
+ className={`w-full py-2.5 rounded-xl text-xs font-bold text-white shadow-md transition-all active:scale-95 flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50 ${
785
+ isMissingInB
786
+ ? 'bg-amber-500 hover:bg-amber-600 shadow-amber-500/20'
787
+ : 'bg-rose-500 hover:bg-rose-600 shadow-rose-500/20'
788
+ }`}
789
+ >
790
+ {isThisJoining ? (
791
+ <>
792
+ <Loader2 size={14} className="animate-spin" />
793
+ <span>Joining with {targetPhone.slice(-4)}...</span>
794
+ </>
795
+ ) : (
796
+ <>
797
+ <Plus size={14} />
798
+ <span>Join with {targetPhone.slice(-4)}</span>
799
+ </>
800
+ )}
801
+ </button>
802
+ ) : null}
803
+ </div>
804
+ </div>
805
+ );
806
+ })}
807
+ </div>
808
+ )}
809
+ </div>
810
+ ) : (
811
+ /* Initial Instructions Card */
812
+ <div className="bg-card border border-border/80 rounded-2xl p-12 text-center flex flex-col items-center justify-center">
813
+ <div className="w-14 h-14 rounded-2xl bg-indigo-500/10 flex items-center justify-center text-indigo-500 mb-4 border border-indigo-500/20">
814
+ <ArrowLeftRight size={26} />
815
+ </div>
816
+ <h3 className="text-lg font-bold text-foreground">Select Two Accounts to Compare</h3>
817
+ <p className="text-xs text-foreground/40 max-w-md mt-1 mb-6 leading-relaxed">
818
+ Choose any two active accounts from your fleet above and click <strong>Compare Accounts</strong>. The engine will inspect all dialogs, identify missing memberships, and let you synchronize them with 1-click.
819
+ </p>
820
+ <button
821
+ onClick={() => runComparison()}
822
+ disabled={loadingAccounts || !phoneA || !phoneB}
823
+ className="bg-indigo-500 hover:bg-indigo-600 text-white font-semibold px-5 py-2.5 rounded-xl text-xs shadow-md shadow-indigo-500/20 transition-all active:scale-95 cursor-pointer disabled:opacity-40"
824
+ >
825
+ Start Comparison
826
+ </button>
827
+ </div>
828
+ )}
829
+ </div>
830
+ );
831
+ }
frontend/src/components/Sidebar.tsx CHANGED
@@ -14,6 +14,10 @@ import {
14
  Sun,
15
  Moon,
16
  ChevronLeft,
 
 
 
 
17
  LogOut,
18
  Shield,
19
  Bookmark,
@@ -25,6 +29,9 @@ import { BroadcastBanner } from "./BroadcastBanner";
25
  export function Sidebar({ children }: { children: React.ReactNode }) {
26
  const [isMobileOpen, setIsMobileOpen] = useState(false);
27
  const [isCollapsed, setIsCollapsed] = useState(false);
 
 
 
28
  const pathname = usePathname();
29
  const router = useRouter();
30
  const { theme, setTheme } = useTheme();
@@ -103,6 +110,67 @@ export function Sidebar({ children }: { children: React.ReactNode }) {
103
  };
104
  }, [pathname, router]);
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  const handleLogout = () => {
107
  removeToken();
108
  const isAdminRoute = pathname.startsWith('/admin');
@@ -115,6 +183,7 @@ export function Sidebar({ children }: { children: React.ReactNode }) {
115
  const navItems = [
116
  { name: "Dashboard", href: "/", icon: LayoutDashboard },
117
  { name: "Accounts", href: "/accounts", icon: Users },
 
118
  { name: "Campaigns", href: "/campaigns", icon: Megaphone },
119
  { name: "Scraper", href: "/scraper", icon: Search },
120
  { name: "Leads", href: "/leads", icon: Bookmark },
@@ -218,24 +287,53 @@ export function Sidebar({ children }: { children: React.ReactNode }) {
218
  })}
219
  </div>
220
 
221
- {/* Theme Toggle & Logout */}
222
- <div className="p-4 border-t border-border space-y-1">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  <button
224
  onClick={handleLogout}
225
  className={`
226
- flex items-center gap-3 py-3 w-full rounded-xl text-sm font-medium transition-all text-red-500/60 hover:text-red-500 hover:bg-red-500/10
227
- ${isCollapsed ? "justify-center px-0" : "px-4"}
228
- `}
229
  title={isCollapsed ? "Logout" : ""}
230
  >
231
- <LogOut size={20} />
232
  {!isCollapsed && <span className="animate-in fade-in duration-300">Logout</span>}
233
  </button>
234
 
 
235
  {!isCollapsed && user && (
236
- <div className="px-4 py-2 mt-4 space-y-4">
237
- <div className="flex items-center justify-between">
238
- <div className="text-[10px] text-foreground/30 uppercase tracking-[0.2em] font-bold">System Status</div>
239
  <span className={`text-[9px] font-black px-2 py-0.5 rounded-full border border-current uppercase ${status?.plan === 'unlimited' ? 'text-rose-400 bg-rose-500/10' :
240
  status?.plan === 'premium' ? 'text-indigo-400 bg-indigo-500/10' :
241
  status?.plan === 'standard' ? 'text-amber-400 bg-amber-500/10' :
@@ -252,7 +350,7 @@ export function Sidebar({ children }: { children: React.ReactNode }) {
252
  </Link>
253
  )}
254
 
255
- <div className="space-y-3 pt-2">
256
  {/* Templates usage - Global visibility */}
257
  <div className="space-y-1">
258
  <div className="flex justify-between text-[9px] font-bold text-foreground/30 uppercase">
 
14
  Sun,
15
  Moon,
16
  ChevronLeft,
17
+ ChevronDown,
18
+ ChevronUp,
19
+ GripHorizontal,
20
+ ArrowLeftRight,
21
  LogOut,
22
  Shield,
23
  Bookmark,
 
29
  export function Sidebar({ children }: { children: React.ReactNode }) {
30
  const [isMobileOpen, setIsMobileOpen] = useState(false);
31
  const [isCollapsed, setIsCollapsed] = useState(false);
32
+ const [isFooterCollapsed, setIsFooterCollapsed] = useState(false);
33
+ const [footerHeight, setFooterHeight] = useState<number>(300);
34
+ const [isDragging, setIsDragging] = useState(false);
35
  const pathname = usePathname();
36
  const router = useRouter();
37
  const { theme, setTheme } = useTheme();
 
110
  };
111
  }, [pathname, router]);
112
 
113
+ // Load and persist sidebar footer preference
114
+ useEffect(() => {
115
+ try {
116
+ const savedCollapsed = localStorage.getItem('arkitel_sidebar_footer_collapsed');
117
+ if (savedCollapsed !== null) {
118
+ setIsFooterCollapsed(savedCollapsed === 'true');
119
+ }
120
+ const savedHeight = localStorage.getItem('arkitel_sidebar_footer_height');
121
+ if (savedHeight !== null) {
122
+ const h = parseInt(savedHeight, 10);
123
+ if (!isNaN(h) && h >= 100 && h <= 500) {
124
+ setFooterHeight(h);
125
+ }
126
+ }
127
+ } catch (e) { }
128
+ }, []);
129
+
130
+ const toggleFooterCollapse = () => {
131
+ setIsFooterCollapsed(prev => {
132
+ const next = !prev;
133
+ try {
134
+ localStorage.setItem('arkitel_sidebar_footer_collapsed', String(next));
135
+ } catch (e) { }
136
+ return next;
137
+ });
138
+ };
139
+
140
+ const handleDragStart = (e: React.MouseEvent) => {
141
+ e.preventDefault();
142
+ setIsDragging(true);
143
+ const startY = e.clientY;
144
+ const startHeight = isFooterCollapsed ? 0 : footerHeight;
145
+
146
+ const onMouseMove = (moveEvent: MouseEvent) => {
147
+ const deltaY = startY - moveEvent.clientY;
148
+ const newHeight = startHeight + deltaY;
149
+
150
+ if (newHeight < 60) {
151
+ setIsFooterCollapsed(true);
152
+ try { localStorage.setItem('arkitel_sidebar_footer_collapsed', 'true'); } catch (e) { }
153
+ } else {
154
+ setIsFooterCollapsed(false);
155
+ const clamped = Math.min(Math.max(newHeight, 120), 480);
156
+ setFooterHeight(clamped);
157
+ try {
158
+ localStorage.setItem('arkitel_sidebar_footer_collapsed', 'false');
159
+ localStorage.setItem('arkitel_sidebar_footer_height', String(clamped));
160
+ } catch (e) { }
161
+ }
162
+ };
163
+
164
+ const onMouseUp = () => {
165
+ setIsDragging(false);
166
+ window.removeEventListener('mousemove', onMouseMove);
167
+ window.removeEventListener('mouseup', onMouseUp);
168
+ };
169
+
170
+ window.addEventListener('mousemove', onMouseMove);
171
+ window.addEventListener('mouseup', onMouseUp);
172
+ };
173
+
174
  const handleLogout = () => {
175
  removeToken();
176
  const isAdminRoute = pathname.startsWith('/admin');
 
183
  const navItems = [
184
  { name: "Dashboard", href: "/", icon: LayoutDashboard },
185
  { name: "Accounts", href: "/accounts", icon: Users },
186
+ { name: "Fleet Compare", href: "/compare", icon: ArrowLeftRight },
187
  { name: "Campaigns", href: "/campaigns", icon: Megaphone },
188
  { name: "Scraper", href: "/scraper", icon: Search },
189
  { name: "Leads", href: "/leads", icon: Bookmark },
 
287
  })}
288
  </div>
289
 
290
+ {/* Draggable & Collapsible Divider Bar */}
291
+ <div
292
+ onMouseDown={handleDragStart}
293
+ className={`w-full py-1.5 flex items-center justify-center cursor-row-resize hover:bg-foreground/5 transition-colors group select-none border-t border-border shrink-0 ${isDragging ? 'bg-indigo-500/10' : ''}`}
294
+ title="Drag up/down to resize or click arrows to collapse/expand system status"
295
+ >
296
+ <div className="flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-border/60 group-hover:bg-indigo-500/20 group-hover:border-indigo-500/40 border border-transparent transition-all">
297
+ <GripHorizontal size={13} className="text-foreground/40 group-hover:text-indigo-400 transition-colors" />
298
+ <button
299
+ type="button"
300
+ onClick={(e) => {
301
+ e.stopPropagation();
302
+ toggleFooterCollapse();
303
+ }}
304
+ className="text-foreground/40 hover:text-indigo-400 p-0.5 transition-colors cursor-pointer"
305
+ title={isFooterCollapsed ? "Expand system status" : "Collapse system status"}
306
+ >
307
+ {isFooterCollapsed ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
308
+ </button>
309
+ </div>
310
+ </div>
311
+
312
+ {/* Footer Status & Logout Section */}
313
+ <div
314
+ style={!isCollapsed && !isFooterCollapsed ? { height: `${footerHeight}px` } : undefined}
315
+ className={`
316
+ border-border transition-all duration-300 flex flex-col justify-between shrink-0 overflow-hidden
317
+ ${isFooterCollapsed ? 'h-auto p-2 pb-3' : 'p-4 overflow-y-auto custom-scrollbar'}
318
+ `}
319
+ >
320
  <button
321
  onClick={handleLogout}
322
  className={`
323
+ flex items-center gap-3 py-2.5 w-full rounded-xl text-xs font-semibold transition-all text-red-500/70 hover:text-red-500 hover:bg-red-500/10 shrink-0
324
+ ${isCollapsed ? "justify-center px-0" : "px-3.5"}
325
+ `}
326
  title={isCollapsed ? "Logout" : ""}
327
  >
328
+ <LogOut size={16} />
329
  {!isCollapsed && <span className="animate-in fade-in duration-300">Logout</span>}
330
  </button>
331
 
332
+ {/* Collapsible System Status & Telemetry */}
333
  {!isCollapsed && user && (
334
+ <div className={`transition-all duration-300 space-y-3.5 ${isFooterCollapsed ? 'opacity-0 max-h-0 pointer-events-none mt-0' : 'opacity-100 mt-2'}`}>
335
+ <div className="flex items-center justify-between pt-2 border-t border-border/50">
336
+ <div className="text-[10px] text-foreground/40 uppercase tracking-[0.2em] font-bold">System Status</div>
337
  <span className={`text-[9px] font-black px-2 py-0.5 rounded-full border border-current uppercase ${status?.plan === 'unlimited' ? 'text-rose-400 bg-rose-500/10' :
338
  status?.plan === 'premium' ? 'text-indigo-400 bg-indigo-500/10' :
339
  status?.plan === 'standard' ? 'text-amber-400 bg-amber-500/10' :
 
350
  </Link>
351
  )}
352
 
353
+ <div className="space-y-3 pt-1">
354
  {/* Templates usage - Global visibility */}
355
  <div className="space-y-1">
356
  <div className="flex justify-between text-[9px] font-bold text-foreground/30 uppercase">