CBV01 commited on
Commit
d4ac480
·
1 Parent(s): 33d9a63

Refine Telegram login, Accounts & Leads UI, and Fix Dashboard Trends Accuracy

Browse files
backend/database.py CHANGED
@@ -11,7 +11,7 @@ import json
11
  import urllib.request
12
  import urllib.parse
13
  import urllib.error
14
- from typing import Any, List, Optional, Dict
15
  from dotenv import load_dotenv # type: ignore
16
  load_dotenv()
17
 
@@ -161,7 +161,7 @@ class TursoConnection:
161
  # Public helpers
162
  # ---------------------------------------------------------------------------
163
 
164
- def get_db_connection():
165
  db_url = os.getenv("TURSO_DATABASE_URL", "")
166
  auth_token = os.getenv("TURSO_AUTH_TOKEN", "")
167
 
@@ -195,7 +195,13 @@ def init_db():
195
  session_string TEXT NOT NULL,
196
  api_id TEXT,
197
  api_hash TEXT,
198
- status TEXT DEFAULT 'active'
 
 
 
 
 
 
199
  )""",
200
  """CREATE TABLE IF NOT EXISTS tasks (
201
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -243,15 +249,25 @@ def init_db():
243
  )""",
244
  ]
245
 
246
- conn = get_db_connection()
247
  for q in table_queries:
248
  conn.execute(q)
249
 
250
- # Migration: Ensure accounts table has user_id
251
- try:
252
- conn.execute("ALTER TABLE accounts ADD COLUMN user_id TEXT")
253
- except:
254
- pass # Column likely exists
 
 
 
 
 
 
 
 
 
 
255
 
256
  # Seed default settings
257
  conn.execute("INSERT OR IGNORE INTO system_settings (key, value) VALUES ('admin_password', 'admin123')")
 
11
  import urllib.request
12
  import urllib.parse
13
  import urllib.error
14
+ from typing import Any, List, Optional, Dict, Union, cast
15
  from dotenv import load_dotenv # type: ignore
16
  load_dotenv()
17
 
 
161
  # Public helpers
162
  # ---------------------------------------------------------------------------
163
 
164
+ def get_db_connection() -> Any:
165
  db_url = os.getenv("TURSO_DATABASE_URL", "")
166
  auth_token = os.getenv("TURSO_AUTH_TOKEN", "")
167
 
 
195
  session_string TEXT NOT NULL,
196
  api_id TEXT,
197
  api_hash TEXT,
198
+ first_name TEXT,
199
+ last_name TEXT,
200
+ username TEXT,
201
+ profile_photo TEXT,
202
+ country TEXT,
203
+ status TEXT DEFAULT 'active',
204
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
205
  )""",
206
  """CREATE TABLE IF NOT EXISTS tasks (
207
  id INTEGER PRIMARY KEY AUTOINCREMENT,
 
249
  )""",
250
  ]
251
 
252
+ conn = cast(Any, get_db_connection())
253
  for q in table_queries:
254
  conn.execute(q)
255
 
256
+ # Migration: Ensure accounts table has all needed fields
257
+ needed_cols = [
258
+ ("user_id", "TEXT"),
259
+ ("first_name", "TEXT"),
260
+ ("last_name", "TEXT"),
261
+ ("username", "TEXT"),
262
+ ("profile_photo", "TEXT"),
263
+ ("country", "TEXT"),
264
+ ("created_at", "DATETIME DEFAULT CURRENT_TIMESTAMP")
265
+ ]
266
+ for col_name, col_type in needed_cols:
267
+ try:
268
+ conn.execute(f"ALTER TABLE accounts ADD COLUMN {col_name} {col_type}")
269
+ except:
270
+ pass # Column likely exists
271
 
272
  # Seed default settings
273
  conn.execute("INSERT OR IGNORE INTO system_settings (key, value) VALUES ('admin_password', 'admin123')")
backend/main.py CHANGED
@@ -15,7 +15,8 @@ import collections
15
  import asyncio
16
  import random
17
  import json
18
- from typing import Optional, List, Dict, Any, Union
 
19
  import re
20
  import ast
21
  import traceback
@@ -35,6 +36,8 @@ from telethon.tl.functions.channels import JoinChannelRequest, GetParticipantsRe
35
  from telethon.tl.functions.messages import SearchGlobalRequest, CheckChatInviteRequest, ImportChatInviteRequest # type: ignore
36
  from telethon.tl.functions.contacts import SearchRequest # type: ignore
37
  from telethon.tl.types import ChannelParticipantsSearch, InputMessagesFilterEmpty, InputPeerEmpty, InputPeerChannel, InputPeerChat # type: ignore
 
 
38
 
39
  from config import TELEGRAM_API_ID, TELEGRAM_API_HASH # type: ignore
40
  from auth import get_password_hash, verify_password, create_access_token, get_current_user_id # type: ignore
@@ -84,6 +87,50 @@ app.add_middleware(
84
  allow_headers=["*"],
85
  )
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  @app.get("/api/debug/db")
88
  async def debug_db():
89
  url = os.getenv("TURSO_DATABASE_URL", "NOT_SET")
@@ -175,28 +222,36 @@ async def qr_login_worker(client: TelegramClient, qr, user_id, api_id, api_hash,
175
  user = await qr.wait()
176
  print(f"QR_WORKER[{token}]: Scan SUCCESS. Logged in as ID {user.id}")
177
 
178
- # Login success!
179
- session_string = client.session.save()
180
  me = await client.get_me()
181
- phone = getattr(me, 'phone', 'Unknown')
 
 
 
 
 
182
 
183
- # If phone is still unknown, we try to use a placeholder or ID
184
- if phone == 'Unknown' or not phone:
185
- phone = f"ID_{user.id}"
186
-
187
  # Save to DB
188
  conn = get_db_connection()
189
- # Check if already exists to avoid duplicates
190
  existing = conn.execute("SELECT 1 FROM accounts WHERE phone_number = ?", (phone,)).fetchone()
191
  if existing:
192
  conn.execute(
193
- "UPDATE accounts SET user_id = ?, session_string = ?, api_id = ?, api_hash = ?, status = 'active' WHERE phone_number = ?",
194
- (user_id, session_string, str(api_id), api_hash, phone)
 
 
 
 
195
  )
196
  else:
197
  conn.execute(
198
- "INSERT INTO accounts (user_id, phone_number, session_string, api_id, api_hash, status) VALUES (?, ?, ?, ?, ?, ?)",
199
- (user_id, phone, session_string, str(api_id), api_hash, "active")
 
 
 
 
200
  )
201
  if hasattr(conn, "commit"): conn.commit()
202
  if hasattr(conn, "close"): conn.close()
@@ -388,15 +443,36 @@ async def verify_code(req: VerifyCodeRequest, user_id: str = Depends(get_current
388
  code=req.code,
389
  phone_code_hash=req.phone_code_hash
390
  )
391
- session_string = client.session.save()
 
 
 
392
 
393
  # Save to DB with API credentials
394
  conn = get_db_connection()
395
  print(f"DB: Saving account {req.phone_number} for user {user_id}")
396
- conn.execute(
397
- "INSERT INTO accounts (user_id, phone_number, session_string, api_id, api_hash, status) VALUES (?, ?, ?, ?, ?, ?)",
398
- (user_id, req.phone_number, session_string, str(api_id), api_hash, "active")
399
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
  if hasattr(conn, "commit"): conn.commit()
401
  if hasattr(conn, "close"): conn.close()
402
  print(f"DB: Account {req.phone_number} saved successfully.")
@@ -516,8 +592,11 @@ async def qr_status(token: str):
516
  @app.get("/api/telegram/accounts")
517
  async def get_accounts(user_id: str = Depends(get_current_user_id)):
518
  conn = get_db_connection()
519
- # explicitly fetch api_id and api_hash to avoid 'empty' looking accounts in frontend
520
- rows = conn.execute("SELECT phone_number, status, api_id, api_hash FROM accounts WHERE user_id = ?", (user_id,)).fetchall()
 
 
 
521
  if hasattr(conn, "close"): conn.close()
522
 
523
  accounts = []
@@ -526,9 +605,14 @@ async def get_accounts(user_id: str = Depends(get_current_user_id)):
526
  "phone_number": row[0],
527
  "status": row[1],
528
  "api_id": row[2],
529
- "api_hash": row[3]
 
 
 
 
 
 
530
  })
531
- print(f"AUTH_ISOLATION: User {user_id} fetched {len(accounts)} accounts.")
532
  return {"accounts": accounts}
533
  @app.delete("/api/telegram/accounts/{phone_number}")
534
  async def delete_account(phone_number: str, user_id: str = Depends(get_current_user_id)):
@@ -1668,16 +1752,24 @@ async def get_dashboard_stats(user_id: str = Depends(get_current_user_id)):
1668
  (user_id,)
1669
  ).fetchall()
1670
 
1671
- # Construct engagement flow
1672
- base_flows = [30, 60, 40, 80, 50, 70, 90, 45, 85, 100] # Default
1673
- if total_leads > 0:
1674
- import random
1675
- base_flows = [random.randint(40, 100) for _ in range(10)]
 
 
 
 
 
 
 
 
1676
 
1677
  service_health = {
1678
- "database": "Stable",
1679
- "poller": "Active" if pending_tasks >= 0 else "Offline",
1680
- "api": "Idle" if pending_tasks == 0 else "Transmitting..."
1681
  }
1682
 
1683
  return {
@@ -1695,7 +1787,7 @@ async def get_dashboard_stats(user_id: str = Depends(get_current_user_id)):
1695
  "time": t[3]
1696
  } for t in tasks_rows
1697
  ],
1698
- "engagement_flow": base_flows,
1699
  "service_health": service_health
1700
  }
1701
  except Exception as e:
 
15
  import asyncio
16
  import random
17
  import json
18
+ import base64
19
+ from typing import Optional, List, Dict, Any, Union, cast
20
  import re
21
  import ast
22
  import traceback
 
36
  from telethon.tl.functions.messages import SearchGlobalRequest, CheckChatInviteRequest, ImportChatInviteRequest # type: ignore
37
  from telethon.tl.functions.contacts import SearchRequest # type: ignore
38
  from telethon.tl.types import ChannelParticipantsSearch, InputMessagesFilterEmpty, InputPeerEmpty, InputPeerChannel, InputPeerChat # type: ignore
39
+ from telethon.tl.functions.help import GetConfigRequest # type: ignore
40
+ from fastapi.staticfiles import StaticFiles # type: ignore
41
 
42
  from config import TELEGRAM_API_ID, TELEGRAM_API_HASH # type: ignore
43
  from auth import get_password_hash, verify_password, create_access_token, get_current_user_id # type: ignore
 
87
  allow_headers=["*"],
88
  )
89
 
90
+ # Static files for profile photos
91
+ if not os.path.exists("static/avatars"):
92
+ os.makedirs("static/avatars", exist_ok=True)
93
+ app.mount("/static", StaticFiles(directory="static"), name="static")
94
+
95
+ async def fetch_tg_profile_data(client: TelegramClient, phone_number: str):
96
+ """Fetches profile details and downloads photo for an authenticated client."""
97
+ me = await client.get_me()
98
+ first_name = getattr(me, 'first_name', '')
99
+ last_name = getattr(me, 'last_name', '')
100
+ username = getattr(me, 'username', '')
101
+
102
+ # Try to get country from phone number prefix
103
+ country = "Unknown"
104
+ if phone_number.startswith('+'):
105
+ # Very basic mapping, ideally use a library
106
+ prefixes = {"+1": "USA", "+44": "UK", "+234": "Nigeria", "+91": "India", "+62": "Indonesia"}
107
+ for p, c in prefixes.items():
108
+ if phone_number.startswith(p):
109
+ country = c
110
+ break
111
+
112
+ # Download profile photo
113
+ photo_path = None
114
+ try:
115
+ user_id = getattr(me, 'id', 0)
116
+ user_photo = getattr(me, 'photo', None)
117
+ if user_photo:
118
+ filename = f"avatar_{user_id}.jpg"
119
+ save_path = f"static/avatars/{filename}"
120
+ await client.download_profile_photo(me, file=save_path)
121
+ photo_path = f"/static/avatars/{filename}"
122
+ except Exception as e:
123
+ print(f"BKG: Photo download error: {e}")
124
+
125
+ return {
126
+ "first_name": first_name,
127
+ "last_name": last_name,
128
+ "username": username,
129
+ "profile_photo": photo_path,
130
+ "country": country
131
+ }
132
+
133
+
134
  @app.get("/api/debug/db")
135
  async def debug_db():
136
  url = os.getenv("TURSO_DATABASE_URL", "NOT_SET")
 
222
  user = await qr.wait()
223
  print(f"QR_WORKER[{token}]: Scan SUCCESS. Logged in as ID {user.id}")
224
 
225
+ # Login success! Get full profile
 
226
  me = await client.get_me()
227
+ user_id_val = getattr(me, 'id', 0)
228
+ phone = getattr(me, 'phone', f"ID_{user_id_val}")
229
+ # Fetch profile data and ensure it's fully resolved
230
+ profile_data = await fetch_tg_profile_data(client, phone)
231
+ profile: Dict[str, Any] = cast(Dict[str, Any], profile_data)
232
+ session_string = str(client.session.save()) # type: ignore
233
 
 
 
 
 
234
  # Save to DB
235
  conn = get_db_connection()
236
+ # Check if already exists
237
  existing = conn.execute("SELECT 1 FROM accounts WHERE phone_number = ?", (phone,)).fetchone()
238
  if existing:
239
  conn.execute(
240
+ """UPDATE accounts SET user_id = ?, session_string = ?, api_id = ?, api_hash = ?,
241
+ first_name = ?, last_name = ?, username = ?, profile_photo = ?, country = ?, status = 'active'
242
+ WHERE phone_number = ?""",
243
+ (user_id, session_string, str(api_id), api_hash,
244
+ profile['first_name'], profile['last_name'], profile['username'],
245
+ profile['profile_photo'], profile['country'], phone)
246
  )
247
  else:
248
  conn.execute(
249
+ """INSERT INTO accounts (user_id, phone_number, session_string, api_id, api_hash,
250
+ first_name, last_name, username, profile_photo, country, status)
251
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
252
+ (user_id, phone, session_string, str(api_id), api_hash,
253
+ profile['first_name'], profile['last_name'], profile['username'],
254
+ profile['profile_photo'], profile['country'], "active")
255
  )
256
  if hasattr(conn, "commit"): conn.commit()
257
  if hasattr(conn, "close"): conn.close()
 
443
  code=req.code,
444
  phone_code_hash=req.phone_code_hash
445
  )
446
+ # Success! Fetch profile
447
+ profile_data = await fetch_tg_profile_data(client, req.phone_number)
448
+ profile: Dict[str, Any] = cast(Dict[str, Any], profile_data)
449
+ session_string = str(client.session.save()) # type: ignore
450
 
451
  # Save to DB with API credentials
452
  conn = get_db_connection()
453
  print(f"DB: Saving account {req.phone_number} for user {user_id}")
454
+
455
+ # Check if already exists
456
+ existing = conn.execute("SELECT 1 FROM accounts WHERE phone_number = ?", (req.phone_number,)).fetchone()
457
+ if existing:
458
+ conn.execute(
459
+ """UPDATE accounts SET user_id = ?, session_string = ?, api_id = ?, api_hash = ?,
460
+ first_name = ?, last_name = ?, username = ?, profile_photo = ?, country = ?, status = 'active'
461
+ WHERE phone_number = ?""",
462
+ (user_id, session_string, str(api_id), api_hash,
463
+ profile['first_name'], profile['last_name'], profile['username'],
464
+ profile['profile_photo'], profile['country'], req.phone_number)
465
+ )
466
+ else:
467
+ conn.execute(
468
+ """INSERT INTO accounts (user_id, phone_number, session_string, api_id, api_hash,
469
+ first_name, last_name, username, profile_photo, country, status)
470
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
471
+ (user_id, req.phone_number, session_string, str(api_id), api_hash,
472
+ profile['first_name'], profile['last_name'], profile['username'],
473
+ profile['profile_photo'], profile['country'], "active")
474
+ )
475
+
476
  if hasattr(conn, "commit"): conn.commit()
477
  if hasattr(conn, "close"): conn.close()
478
  print(f"DB: Account {req.phone_number} saved successfully.")
 
592
  @app.get("/api/telegram/accounts")
593
  async def get_accounts(user_id: str = Depends(get_current_user_id)):
594
  conn = get_db_connection()
595
+ rows = conn.execute("""
596
+ SELECT phone_number, status, api_id, api_hash,
597
+ first_name, last_name, username, profile_photo, country, created_at
598
+ FROM accounts WHERE user_id = ?
599
+ """, (user_id,)).fetchall()
600
  if hasattr(conn, "close"): conn.close()
601
 
602
  accounts = []
 
605
  "phone_number": row[0],
606
  "status": row[1],
607
  "api_id": row[2],
608
+ "api_hash": row[3],
609
+ "first_name": row[4],
610
+ "last_name": row[5],
611
+ "username": row[6],
612
+ "profile_photo": row[7],
613
+ "country": row[8],
614
+ "created_at": row[9]
615
  })
 
616
  return {"accounts": accounts}
617
  @app.delete("/api/telegram/accounts/{phone_number}")
618
  async def delete_account(phone_number: str, user_id: str = Depends(get_current_user_id)):
 
1752
  (user_id,)
1753
  ).fetchall()
1754
 
1755
+ # Construct engagement flow (Real trends)
1756
+ # We fetch message counts for the last 7 days from tasks
1757
+ trends = []
1758
+ for i in range(6, -1, -1):
1759
+ day = (datetime.now() - timedelta(days=i)).strftime('%Y-%m-%d')
1760
+ count = conn.execute(
1761
+ "SELECT COUNT(*) FROM tasks WHERE user_id = ? AND status = 'completed' AND scheduled_time LIKE ?",
1762
+ (user_id, f"{day}%")
1763
+ ).fetchone()[0]
1764
+ # Since task counts might be zero, we normalize it to a 0-100 scale for the chart,
1765
+ # or just show raw counts if they are high enough.
1766
+ # Send raw counts, frontend will scale the chart
1767
+ trends.append(count)
1768
 
1769
  service_health = {
1770
+ "database": "Online",
1771
+ "poller": "Active" if pending_tasks >= 0 else "Degraded",
1772
+ "api": "Operational" if total_accounts > 0 else "Idle"
1773
  }
1774
 
1775
  return {
 
1787
  "time": t[3]
1788
  } for t in tasks_rows
1789
  ],
1790
+ "engagement_flow": trends,
1791
  "service_health": service_health
1792
  }
1793
  except Exception as e:
frontend/src/app/accounts/page.tsx CHANGED
@@ -196,7 +196,7 @@ export default function AccountsPage() {
196
  setIsConnecting(false);
197
  setStep('phone');
198
  setLoginMode('phone');
199
- }, 2000);
200
  } else if (data.status === 'pending') {
201
  setTimeout(poll, 2000);
202
  } else {
@@ -327,59 +327,99 @@ export default function AccountsPage() {
327
  </button>
328
  </div>
329
  ) : (
330
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 animate-in fade-in slide-in-from-bottom-8 duration-1000">
331
- {accounts.map((acc, idx) => (
332
- <div key={idx} className="bg-card/60 backdrop-blur-2xl border border-border rounded-[36px] p-8 group hover:border-indigo-500/30 transition-all relative overflow-hidden flex flex-col">
333
- <div className="absolute top-0 right-0 w-48 h-48 bg-indigo-500/10 rounded-full blur-[80px] -mr-16 -mt-16 transition-all group-hover:bg-indigo-500/20"></div>
334
-
335
- <div className="flex items-center gap-6 mb-8 relative z-10">
336
- <div className="w-16 h-16 rounded-3xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white text-2xl font-black transition-all group-hover:rotate-6 group-hover:scale-110 duration-500">
337
- {(acc.phone_number?.slice(-2) || 'N').toUpperCase()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  </div>
339
- <div className="flex-1 min-w-0">
340
- <h4 className="font-bold text-foreground text-xl tracking-tight truncate mb-1">
341
- {acc.phone_number}
342
- </h4>
343
- <div className="flex items-center gap-2">
344
- <div className="w-2 h-2 rounded-full bg-emerald-500 animate-[pulse_2s_infinite]"></div>
345
- <span className="text-[10px] font-black uppercase tracking-[0.2em] text-emerald-500/80">CORE ONLINE</span>
346
- </div>
 
 
 
 
 
 
 
 
347
  </div>
348
- <button
349
- onClick={() => handleDeleteAccount(acc.phone_number)}
350
- disabled={actionLoading === acc.phone_number}
351
- className="p-3 rounded-2xl bg-foreground/5 text-foreground/20 hover:text-red-400 hover:bg-red-400/10 transition-all border border-border disabled:opacity-50">
352
- {actionLoading === acc.phone_number ? <Loader2 size={20} className="animate-spin" /> : <X size={20} />}
353
- </button>
354
  </div>
355
 
356
- <div className="space-y-4 relative z-10 mb-8 flex-1">
357
- <div className="flex justify-between items-center py-4 border-b border-border/50">
358
- <span className="text-[11px] font-bold text-foreground/30 uppercase tracking-[0.1em]">Identity Lock</span>
359
- <span className="text-xs font-mono font-medium text-foreground/60 bg-foreground/5 px-2 py-1 rounded-md">API-{acc.api_id?.slice(0, 4) || '••••'}</span>
 
360
  </div>
361
- <div className="flex justify-between items-center py-2">
362
- <span className="text-[11px] font-bold text-foreground/30 uppercase tracking-[0.1em]">Traffic Capacity</span>
363
- <div className="flex items-center gap-2">
364
- <div className="w-12 h-1.5 bg-foreground/5 rounded-full overflow-hidden">
365
- <div className="w-3/4 h-full bg-indigo-500 rounded-full" />
 
 
 
 
 
366
  </div>
367
- <span className="text-[10px] font-bold text-foreground/80">OPTIMAL</span>
368
  </div>
369
  </div>
370
- </div>
371
 
372
- <div className="grid grid-cols-2 gap-3 relative z-10">
373
- <button
374
- onClick={() => handleSessionDump(acc.phone_number)}
375
- className="bg-foreground/5 hover:bg-foreground/10 text-foreground/40 hover:text-foreground transition-all py-4 rounded-2xl text-[10px] font-black uppercase tracking-[0.15em] border border-border">
376
- Export Key
377
- </button>
378
- <button
379
- onClick={() => handleValidateSession(acc.phone_number)}
380
- disabled={actionLoading === acc.phone_number + '_valid'}
381
- className="bg-indigo-500/10 hover:bg-indigo-500/20 text-indigo-500 transition-all py-4 rounded-2xl text-[10px] font-black uppercase tracking-[0.15em] border border-indigo-500/10 disabled:opacity-50">
382
- {actionLoading === acc.phone_number + '_valid' ? 'Verifying...' : 'Pulse Check'}
 
 
 
 
 
 
 
 
383
  </button>
384
  </div>
385
  </div>
@@ -602,44 +642,44 @@ export default function AccountsPage() {
602
  </div>
603
  </div>
604
 
605
- <h3 className="text-3xl font-bold text-foreground mb-3 tracking-tight">Security Code</h3>
606
- <p className="text-foreground/40 text-sm font-medium mb-12 max-w-[280px] mx-auto leading-relaxed">
607
  Enter the 5-digit verification code sent to your active Telegram session.
608
  </p>
609
 
610
  {error && (
611
- <div className="mb-8 p-4 rounded-2xl bg-red-500/10 border border-red-500/20 text-red-500 text-xs font-bold flex items-center gap-3 animate-in shake duration-500">
612
- <AlertCircle size={16} className="shrink-0" />
613
  <span>{error}</span>
614
  </div>
615
  )}
616
 
617
- <form onSubmit={handleVerifyCode} className="space-y-10">
618
- <div className="flex justify-center gap-4">
619
  <input
620
  type="text"
621
  value={otp}
622
  onChange={(e) => setOtp(e.target.value)}
623
  placeholder="•••••"
624
  maxLength={5}
625
- className="w-full h-20 bg-foreground/5 border border-border rounded-[24px] text-center text-4xl font-black tracking-[0.5em] text-foreground focus:outline-none focus:ring-4 focus:ring-indigo-500/20 focus:bg-foreground/10 transition-all"
626
  required
627
  autoFocus
628
  />
629
  </div>
630
 
631
- <div className="flex flex-col gap-4">
632
  <button
633
  type="submit"
634
  disabled={loading || otp.length < 5}
635
- className="w-full h-16 bg-foreground text-background hover:bg-foreground/90 disabled:opacity-30 text-base font-bold transition-all rounded-[20px] flex items-center justify-center gap-3 active:scale-[0.98]"
636
  >
637
- {loading ? <Loader2 size={24} className="animate-spin" /> : 'Complete Link'}
638
  </button>
639
  <button
640
  type="button"
641
  onClick={() => setStep('phone')}
642
- className="text-foreground/40 hover:text-foreground text-[11px] font-black uppercase tracking-widest transition-colors py-2"
643
  >
644
  ← Change Number
645
  </button>
 
196
  setIsConnecting(false);
197
  setStep('phone');
198
  setLoginMode('phone');
199
+ }, 800);
200
  } else if (data.status === 'pending') {
201
  setTimeout(poll, 2000);
202
  } else {
 
327
  </button>
328
  </div>
329
  ) : (
330
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 animate-in fade-in slide-in-from-bottom-8 duration-1000">
331
+ {accounts.map((acc) => (
332
+ <div key={acc.phone_number} className="bg-card border border-border p-6 rounded-[32px] group relative hover:shadow-2xl hover:shadow-indigo-500/5 transition-all duration-500 flex flex-col">
333
+ {/* Status and Action Header */}
334
+ <div className="flex justify-between items-start mb-6">
335
+ <span className="px-3 py-1 bg-emerald-500/10 text-emerald-500 text-[10px] font-bold rounded-full flex items-center gap-1.5 uppercase transition-all group-hover:bg-emerald-500/20">
336
+ <div className="w-1.5 h-1.5 bg-emerald-500 rounded-full animate-pulse" />
337
+ {acc.status}
338
+ </span>
339
+ <div className="flex gap-2">
340
+ <button
341
+ onClick={() => handleValidateSession(acc.phone_number)}
342
+ className="p-1.5 bg-foreground/5 hover:bg-emerald-500/10 hover:text-emerald-500 rounded-lg text-foreground/30 transition-all"
343
+ title="Pulse Check"
344
+ >
345
+ {actionLoading === acc.phone_number + '_valid' ? <Loader2 size={14} className="animate-spin" /> : <Rocket size={14} />}
346
+ </button>
347
+ <button
348
+ onClick={() => handleSessionDump(acc.phone_number)}
349
+ className="p-1.5 bg-foreground/5 hover:bg-indigo-500/10 hover:text-indigo-500 rounded-lg text-foreground/30 transition-all"
350
+ title="Export Key"
351
+ >
352
+ {actionLoading === acc.phone_number + '_dump' ? <Loader2 size={14} className="animate-spin" /> : <KeyRound size={14} />}
353
+ </button>
354
+ <button
355
+ onClick={() => handleDeleteAccount(acc.phone_number)}
356
+ className="p-1.5 bg-foreground/5 hover:bg-red-500/10 hover:text-red-500 rounded-lg text-foreground/30 transition-all"
357
+ title="Delete"
358
+ >
359
+ {actionLoading === acc.phone_number ? <Loader2 size={14} className="animate-spin" /> : <X size={14} />}
360
+ </button>
361
  </div>
362
+ </div>
363
+
364
+ {/* Profile Image and Identity */}
365
+ <div className="flex flex-col items-center mb-6">
366
+ <div className="w-20 h-20 rounded-full border-4 border-foreground/5 p-1 mb-3 bg-foreground/[0.02] relative shadow-inner">
367
+ {acc.profile_photo ? (
368
+ <img
369
+ src={process.env.NEXT_PUBLIC_API_URL ? `${process.env.NEXT_PUBLIC_API_URL}${acc.profile_photo}` : `http://localhost:8000${acc.profile_photo}`}
370
+ className="w-full h-full rounded-full object-cover"
371
+ onError={(e) => { (e.target as any).src = 'https://abs.twimg.com/sticky/default_profile_images/default_profile_400x400.png' }}
372
+ />
373
+ ) : (
374
+ <div className="w-full h-full rounded-full bg-indigo-500/10 flex items-center justify-center text-indigo-500">
375
+ <Users size={32} />
376
+ </div>
377
+ )}
378
  </div>
379
+ <h4 className="text-lg font-bold text-foreground tracking-tight">{acc.first_name || 'Account'} {acc.last_name || ''}</h4>
380
+ <p className="text-[10px] font-black text-indigo-500 uppercase tracking-widest mt-1">@{acc.username || 'unknown_node'}</p>
 
 
 
 
381
  </div>
382
 
383
+ {/* Info Grid */}
384
+ <div className="bg-foreground/[0.03] border border-border/50 rounded-2xl p-5 mb-auto space-y-4">
385
+ <div className="flex items-center justify-between text-[10px] font-bold text-foreground/30 uppercase tracking-tighter">
386
+ <span className="flex items-center gap-1.5"><Rocket size={12} className="opacity-50" /> #NODE_{acc.phone_number.slice(-4)}</span>
387
+ <span className="flex items-center gap-1.5"><Globe size={12} className="opacity-50" /> {acc.country || 'Global'}</span>
388
  </div>
389
+
390
+ <div className="flex flex-col gap-2.5">
391
+ <div className="flex items-center gap-3 text-xs font-bold text-foreground/70">
392
+ <div className="w-7 h-7 rounded-lg bg-indigo-500/10 flex items-center justify-center text-indigo-500"><Phone size={14} /></div>
393
+ {acc.phone_number}
394
+ </div>
395
+ <div className="flex items-center gap-2 justify-between">
396
+ <div className="flex items-center gap-3 text-xs font-bold text-foreground/70">
397
+ <div className="w-7 h-7 rounded-lg bg-emerald-500/10 flex items-center justify-center text-emerald-500"><Rocket size={14} /></div>
398
+ Capacity
399
  </div>
400
+ <span className="text-[10px] font-bold text-foreground/40">98.4%</span>
401
  </div>
402
  </div>
 
403
 
404
+ <div className="h-px bg-border/20 my-1" />
405
+
406
+ <div className="flex items-center justify-between">
407
+ <div className="flex items-center gap-1.5 text-[9px] font-black text-foreground/30 uppercase">
408
+ <CheckCircle2 size={12} className="text-emerald-500" />
409
+ Identity Lock
410
+ </div>
411
+ <div className="flex items-center gap-1.5 text-[9px] font-black text-foreground/30 uppercase">
412
+ <Rocket size={12} className="text-indigo-500" />
413
+ Neural Pulse
414
+ </div>
415
+ </div>
416
+ </div>
417
+
418
+ {/* Joined Footer */}
419
+ <div className="flex items-center justify-between pt-5 mt-5 border-t border-border/10">
420
+ <span className="text-[10px] font-bold text-foreground/20 uppercase tracking-[0.1em]">Joined {acc.created_at ? new Date(acc.created_at).toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' }) : 'Recently'}</span>
421
+ <button className="text-[10px] font-black text-indigo-500 uppercase tracking-widest hover:text-indigo-400 flex items-center gap-1 transition-all group/btn">
422
+ View Details <ChevronRight size={10} className="group-hover/btn:translate-x-1 transition-transform" />
423
  </button>
424
  </div>
425
  </div>
 
642
  </div>
643
  </div>
644
 
645
+ <h3 className="text-2xl font-bold text-foreground mb-2 tracking-tight">Security Code</h3>
646
+ <p className="text-foreground/40 text-[11px] font-bold mb-8 max-w-[240px] mx-auto leading-relaxed uppercase tracking-tighter">
647
  Enter the 5-digit verification code sent to your active Telegram session.
648
  </p>
649
 
650
  {error && (
651
+ <div className="mb-6 p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-500 text-[10px] font-bold flex items-center gap-2 animate-in shake duration-500 text-left">
652
+ <AlertCircle size={14} className="shrink-0" />
653
  <span>{error}</span>
654
  </div>
655
  )}
656
 
657
+ <form onSubmit={handleVerifyCode} className="space-y-6">
658
+ <div className="flex justify-center">
659
  <input
660
  type="text"
661
  value={otp}
662
  onChange={(e) => setOtp(e.target.value)}
663
  placeholder="•••••"
664
  maxLength={5}
665
+ className="w-full h-14 bg-foreground/5 border border-border rounded-xl text-center text-2xl font-black tracking-[0.5em] text-foreground focus:outline-none focus:ring-4 focus:ring-indigo-500/20 focus:bg-foreground/10 transition-all"
666
  required
667
  autoFocus
668
  />
669
  </div>
670
 
671
+ <div className="flex flex-col gap-3">
672
  <button
673
  type="submit"
674
  disabled={loading || otp.length < 5}
675
+ className="w-full h-12 bg-foreground text-background hover:bg-foreground/90 disabled:opacity-30 text-sm font-bold transition-all rounded-xl flex items-center justify-center gap-2 active:scale-[0.98]"
676
  >
677
+ {loading ? <Loader2 size={18} className="animate-spin" /> : 'Link Account'}
678
  </button>
679
  <button
680
  type="button"
681
  onClick={() => setStep('phone')}
682
+ className="text-foreground/30 hover:text-foreground text-[10px] font-bold uppercase tracking-widest transition-colors py-1"
683
  >
684
  ← Change Number
685
  </button>
frontend/src/app/globals.css CHANGED
@@ -10,12 +10,12 @@
10
  }
11
 
12
  :root[class~="dark"] {
13
- --background: #0a0a0c;
14
  --foreground: #f8fafc;
15
- --card: #0b0c10;
16
  --card-foreground: #f8fafc;
17
- --border: rgba(255, 255, 255, 0.05);
18
- --input: #1c2231;
19
  }
20
 
21
  @theme inline {
 
10
  }
11
 
12
  :root[class~="dark"] {
13
+ --background: #09090b;
14
  --foreground: #f8fafc;
15
+ --card: #1c1c21;
16
  --card-foreground: #f8fafc;
17
+ --border: rgba(255, 255, 255, 0.1);
18
+ --input: #27272a;
19
  }
20
 
21
  @theme inline {
frontend/src/app/leads/page.tsx CHANGED
@@ -487,111 +487,73 @@ export default function LeadsPage() {
487
  <p className="text-foreground/20 text-xs">Try adjusting your filters or search query.</p>
488
  </div>
489
  ) : (
490
- <div className="bg-card border border-border rounded-[32px] overflow-hidden shadow-2xl overflow-x-auto custom-scrollbar">
491
- <table className="w-full text-left border-collapse min-w-[1000px]">
492
- <thead>
493
- <tr className="border-b border-border text-[10px] font-bold uppercase tracking-[0.2em] text-foreground/30 bg-foreground/[0.01]">
494
- <th className="p-6 w-12 text-center">
495
- <button
496
- onClick={() => toggleSelectAll(isAllVisibleSelected)}
497
- className={`w-5 h-5 rounded-md border flex items-center justify-center transition-all ${isAllVisibleSelected ? 'bg-indigo-500 border-indigo-500 text-white' : 'border-border bg-foreground/5 hover:border-foreground/30'}`}
498
- >
499
- {isAllVisibleSelected && <Check size={12} />}
500
- </button>
501
- </th>
502
- <th className="p-6">Lead / Entity</th>
503
- <th className="p-6">Identifiers</th>
504
- <th className="p-6 text-center">Type</th>
505
- <th className="p-6 text-right">Metrics / Info</th>
506
- <th className="p-6 text-right pr-10">Actions</th>
507
- </tr>
508
- </thead>
509
- <tbody className="divide-y divide-border">
510
- {visibleLeads.map((l) => {
511
- const isSelected = selectedIds.has(l.id);
512
- return (
513
- <tr
514
- key={l.id}
515
- className={`group hover:bg-foreground/[0.01] transition-all cursor-pointer ${isSelected ? 'bg-indigo-500/[0.03]' : ''}`}
516
- onClick={() => toggleSelection(l.id)}
517
- >
518
- <td className="p-6 text-center" onClick={(e) => e.stopPropagation()}>
519
  <button
520
- onClick={() => toggleSelection(l.id)}
521
- className={`w-5 h-5 rounded-md border flex items-center justify-center transition-all ${isSelected ? 'bg-indigo-500 border-indigo-500 text-white shadow-lg shadow-indigo-500/20' : 'border-border bg-foreground/[0.02] hover:border-foreground/20'}`}
 
522
  >
523
- {isSelected && <Check size={12} />}
524
  </button>
525
- </td>
526
- <td className="p-6">
527
- <div className="flex items-center gap-4">
528
- <div className={`w-10 h-10 rounded-2xl flex items-center justify-center border shadow-sm ${l.itemType === 'member' ? 'bg-indigo-500/10 border-indigo-500/20 text-indigo-500' : 'bg-emerald-500/10 border-emerald-500/20 text-emerald-500'}`}>
529
- {l.itemType === 'member' ? <UsersRound size={18} /> : (l.type === 'channel' ? <Megaphone size={18} /> : <Users size={18} />)}
530
- </div>
531
- <div className="max-w-[200px]">
532
- <div className="font-bold text-sm text-foreground truncate">{l.title}</div>
533
- <div className="text-[10px] text-foreground/30 font-bold uppercase tracking-widest">{l.itemType}</div>
534
- </div>
535
- </div>
536
- </td>
537
- <td className="p-6">
538
- {l.username ? (
539
- <div className="flex items-center gap-1.5 text-indigo-500 font-bold text-xs bg-indigo-500/5 px-2.5 py-1 rounded-full w-fit">
540
- @{l.username}
541
- </div>
542
- ) : (
543
- <div className="text-[10px] text-foreground/20 font-medium">ID: {l.id}</div>
544
- )}
545
- </td>
546
- <td className="p-6 text-center">
547
- <span className={`text-[10px] font-bold uppercase px-2.5 py-1 rounded-md tracking-tighter ${l.type === 'channel' ? 'bg-blue-500/10 text-blue-500' : (l.type === 'group' ? 'bg-indigo-500/10 text-indigo-500' : 'bg-slate-500/10 text-slate-500')}`}>
548
- {l.type}
549
- </span>
550
- </td>
551
- <td className="p-6 text-right">
552
- {l.itemType === 'community' ? (
553
- <>
554
- <div className="font-bold text-sm text-foreground">{(l.participants_count || 0).toLocaleString()}</div>
555
- <div className="text-[10px] text-foreground/20 font-bold uppercase">{l.country || "Global"}</div>
556
- </>
557
- ) : (
558
- <div className="text-[10px] text-foreground/20 font-bold uppercase italic">Direct Target</div>
559
- )}
560
- </td>
561
- <td className="p-6 text-right pr-8" onClick={(e) => e.stopPropagation()}>
562
- <div className="flex items-center justify-end gap-1 font-bold">
563
- {l.itemType === 'community' && (
564
- <>
565
- <button
566
- onClick={() => handleSingleJoin(l.id, l.username)}
567
- className="p-2 text-foreground/30 hover:text-emerald-500 hover:bg-emerald-500/10 rounded-xl transition-all"
568
- title="Join Community"
569
- >
570
- <UserPlus size={18} />
571
- </button>
572
- <button
573
- onClick={() => setExtractingGroup(l.username || l.id)}
574
- className="p-2 text-foreground/30 hover:text-indigo-500 hover:bg-indigo-500/10 rounded-xl transition-all"
575
- title="Extract Members"
576
- >
577
- <Shield size={18} />
578
- </button>
579
- </>
580
- )}
581
- <button
582
- onClick={() => handleDeleteSingle(l.id, l.itemType === 'member' ? 'member' : 'group')}
583
- className="p-2 text-foreground/30 hover:text-red-500 hover:bg-red-500/10 rounded-xl transition-all"
584
- title="Remove Lead"
585
- >
586
- <Trash2 size={18} />
587
- </button>
588
- </div>
589
- </td>
590
- </tr>
591
- );
592
- })}
593
- </tbody>
594
- </table>
595
  </div>
596
  )}
597
 
 
487
  <p className="text-foreground/20 text-xs">Try adjusting your filters or search query.</p>
488
  </div>
489
  ) : (
490
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4 gap-4 animate-in fade-in slide-in-from-bottom-8 duration-700">
491
+ {visibleLeads.map((l) => (
492
+ <div
493
+ key={l.id}
494
+ onClick={() => toggleSelection(l.id)}
495
+ className={`group bg-card/60 border border-border/50 rounded-3xl p-5 hover:border-indigo-500/30 transition-all cursor-pointer relative overflow-hidden flex flex-col ${selectedIds.has(l.id) ? 'ring-2 ring-indigo-500 bg-indigo-500/5 border-indigo-500/20' : ''}`}
496
+ >
497
+ <div className="flex justify-between items-start mb-4">
498
+ <div className={`w-10 h-10 rounded-2xl flex items-center justify-center border ${l.itemType === 'member' ? 'bg-indigo-500/10 border-indigo-500/20 text-indigo-500' : 'bg-emerald-500/10 border-emerald-500/20 text-emerald-500'}`}>
499
+ {l.itemType === 'member' ? <UsersRound size={18} /> : (l.type === 'channel' ? <Megaphone size={18} /> : <Users size={18} />)}
500
+ </div>
501
+ <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
502
+ {l.itemType === 'community' && (
503
+ <>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504
  <button
505
+ onClick={(e) => { e.stopPropagation(); handleSingleJoin(l.id, l.username); }}
506
+ className="p-1.5 bg-foreground/5 hover:bg-emerald-500/10 hover:text-emerald-500 rounded-lg text-foreground/30 transition-all"
507
+ title="Join"
508
  >
509
+ <UserPlus size={14} />
510
  </button>
511
+ <button
512
+ onClick={(e) => { e.stopPropagation(); setExtractingGroup(l.username || l.id); }}
513
+ className="p-1.5 bg-foreground/5 hover:bg-indigo-500/10 hover:text-indigo-500 rounded-lg text-foreground/30 transition-all"
514
+ title="Extract"
515
+ >
516
+ <Shield size={14} />
517
+ </button>
518
+ </>
519
+ )}
520
+ <button
521
+ onClick={(e) => { e.stopPropagation(); handleDeleteSingle(l.id, l.itemType === 'member' ? 'member' : 'group'); }}
522
+ className="p-1.5 bg-foreground/5 hover:bg-red-500/10 hover:text-red-500 rounded-lg text-foreground/30 transition-all"
523
+ title="Delete"
524
+ >
525
+ <Trash2 size={14} />
526
+ </button>
527
+ </div>
528
+ </div>
529
+
530
+ <div className="flex-1 min-w-0 mb-4">
531
+ <h4 className="font-bold text-sm text-foreground truncate mb-1">{l.title}</h4>
532
+ <div className="flex items-center gap-2">
533
+ <span className={`text-[9px] font-black uppercase px-2 py-0.5 rounded-md tracking-tighter ${l.type === 'channel' ? 'bg-blue-500/10 text-blue-500' : (l.type === 'group' ? 'bg-indigo-500/10 text-indigo-500' : 'bg-slate-500/10 text-slate-500')}`}>
534
+ {l.type}
535
+ </span>
536
+ {l.username && <span className="text-[10px] text-indigo-500/70 font-bold truncate">@{l.username}</span>}
537
+ </div>
538
+ </div>
539
+
540
+ <div className="flex items-center justify-between pt-4 border-t border-border/30">
541
+ <div className="text-[10px] font-bold text-foreground/30 uppercase tracking-widest">
542
+ {l.itemType === 'community' ? (l.participants_count || 0).toLocaleString() + ' Members' : 'Direct Target'}
543
+ </div>
544
+ <div className="text-[10px] font-bold text-foreground/20 uppercase">
545
+ {l.country || "Global"}
546
+ </div>
547
+ </div>
548
+
549
+ {/* Selection Checkmark */}
550
+ {selectedIds.has(l.id) && (
551
+ <div className="absolute top-2 right-2 p-1 bg-indigo-500 rounded-full text-white">
552
+ <Check size={10} />
553
+ </div>
554
+ )}
555
+ </div>
556
+ ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
  </div>
558
  )}
559
 
frontend/src/app/page.tsx CHANGED
@@ -22,34 +22,38 @@ export default function Dashboard() {
22
  };
23
 
24
  const dateLabels = getDateLabels();
25
- const chartData = stats?.engagement_flow || [85, 45, 60, 30, 70, 55, 40]; // Use 7 points for weekly
26
-
27
- // Smooth curve calculation (simple interpolation)
 
 
28
  const generateSmoothPath = (data: number[]) => {
29
  if (!data.length) return "";
30
  const width = 1000;
31
  const height = 200;
32
- const padding = 10;
33
  const chartHeight = height - padding * 2;
34
- const chartWidth = width - 20; // Allow slight right padding
35
  const step = chartWidth / (data.length - 1);
36
 
37
- let path = `M ${padding} ${height - padding - (data[0] / 100) * chartHeight}`;
 
 
38
 
39
  for (let i = 0; i < data.length - 1; i++) {
40
- const x1 = padding + i * step;
41
- const y1 = height - padding - (data[i] / 100) * chartHeight;
42
- const x2 = padding + (i + 1) * step;
43
- const y2 = height - padding - (data[i + 1] / 100) * chartHeight;
44
-
45
- const cx = (x1 + x2) / 2;
46
- path += ` C ${cx} ${y1}, ${cx} ${y2}, ${x2} ${y2}`;
47
  }
48
  return path;
49
  };
50
 
51
  const smoothPath = generateSmoothPath(chartData);
52
- const areaPath = smoothPath + ` L 990 190 L 10 190 Z`;
53
 
54
  useEffect(() => {
55
  const fetchStats = async () => {
@@ -151,7 +155,7 @@ export default function Dashboard() {
151
  <div className="flex-1 mt-4 flex">
152
  {/* Y-Axis Labels */}
153
  <div className="flex flex-col justify-between py-10 pr-3 text-[10px] font-mono text-foreground/50 font-bold h-full w-14 shrink-0 text-right border-r border-border/20">
154
- {[1400, 1050, 700, 350, 0].map(val => (
155
  <span key={val}>{val}</span>
156
  ))}
157
  </div>
@@ -159,7 +163,7 @@ export default function Dashboard() {
159
  <div className="flex-1 relative pl-3">
160
  {/* Grid Lines */}
161
  <div className="absolute inset-x-0 inset-y-0 flex flex-col justify-between pointer-events-none opacity-10 py-10 ml-3">
162
- {[1400, 1050, 700, 350, 0].map(val => (
163
  <div key={val} className="w-full border-t border-dashed border-foreground/50" />
164
  ))}
165
  </div>
@@ -202,9 +206,9 @@ export default function Dashboard() {
202
 
203
  {/* Data Points / Interaction Nodes */}
204
  {chartData.map((val: number, i: number) => {
205
- const step = 980 / (chartData.length - 1);
206
- const x = 10 + i * step;
207
- const y = 190 - (val / 100) * 180;
208
  return (
209
  <circle
210
  key={i}
 
22
  };
23
 
24
  const dateLabels = getDateLabels();
25
+ const chartData = stats?.engagement_flow || [0, 0, 0, 0, 0, 0, 0];
26
+ const maxVal = Math.max(...chartData, 10);
27
+ const chartMax = Math.ceil(maxVal / 10) * 10; // Round to nearest 10
28
+
29
+ // Smooth curve calculation (dynamic scaling)
30
  const generateSmoothPath = (data: number[]) => {
31
  if (!data.length) return "";
32
  const width = 1000;
33
  const height = 200;
34
+ const padding = 20;
35
  const chartHeight = height - padding * 2;
36
+ const chartWidth = width - padding * 2;
37
  const step = chartWidth / (data.length - 1);
38
 
39
+ const getY = (val: number) => height - padding - (val / chartMax) * chartHeight;
40
+
41
+ let path = `M ${padding} ${getY(data[0])}`;
42
 
43
  for (let i = 0; i < data.length - 1; i++) {
44
+ const x1 = padding + i * step;
45
+ const y1 = getY(data[i]);
46
+ const x2 = padding + (i + 1) * step;
47
+ const y2 = getY(data[i + 1]);
48
+
49
+ const cx = (x1 + x2) / 2;
50
+ path += ` C ${cx} ${y1}, ${cx} ${y2}, ${x2} ${y2}`;
51
  }
52
  return path;
53
  };
54
 
55
  const smoothPath = generateSmoothPath(chartData);
56
+ const areaPath = smoothPath + ` L 980 180 L 20 180 Z`;
57
 
58
  useEffect(() => {
59
  const fetchStats = async () => {
 
155
  <div className="flex-1 mt-4 flex">
156
  {/* Y-Axis Labels */}
157
  <div className="flex flex-col justify-between py-10 pr-3 text-[10px] font-mono text-foreground/50 font-bold h-full w-14 shrink-0 text-right border-r border-border/20">
158
+ {[chartMax, Math.round(chartMax * 0.75), Math.round(chartMax * 0.5), Math.round(chartMax * 0.25), 0].map(val => (
159
  <span key={val}>{val}</span>
160
  ))}
161
  </div>
 
163
  <div className="flex-1 relative pl-3">
164
  {/* Grid Lines */}
165
  <div className="absolute inset-x-0 inset-y-0 flex flex-col justify-between pointer-events-none opacity-10 py-10 ml-3">
166
+ {[chartMax, 0.75, 0.5, 0.25, 0].map(val => (
167
  <div key={val} className="w-full border-t border-dashed border-foreground/50" />
168
  ))}
169
  </div>
 
206
 
207
  {/* Data Points / Interaction Nodes */}
208
  {chartData.map((val: number, i: number) => {
209
+ const step = 960 / (chartData.length - 1);
210
+ const x = 20 + i * step;
211
+ const y = 180 - (val / chartMax) * 160;
212
  return (
213
  <circle
214
  key={i}