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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
const API_BASE = import.meta.env.VITE_API_URL || "/api/v1";
const IS_PRODUCTION = import.meta.env.MODE === "production" || API_BASE.includes("hf.space");

// Abort long-running requests so a stalled backend never hangs the UI.
const DEFAULT_TIMEOUT_MS = 15_000;
const STREAM_TIMEOUT_MS = 120_000;

async function fetchWithTimeout(url: string, options?: RequestInit, timeoutMs = DEFAULT_TIMEOUT_MS): Promise<Response> {
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeoutMs);
  try {
    return await fetch(url, { ...options, signal: controller.signal });
  } finally {
    clearTimeout(id);
  }
}

export function getApiBase(): string {
  return API_BASE;
}

export type UserType = "user" | "admin";

export interface User {
  id: string;
  email: string;
  full_name: string;
  phone: string;
  avatar_url?: string;
  role: string;
  is_active: boolean;
  created_at?: string;
}

export interface AuthResponse {
  access_token: string;
  token_type: string;
  user: User;
}

function isClient(): boolean {
  return typeof window !== "undefined";
}

// ── Auth state (in-memory + localStorage persistence for production) ──
let currentUser: User | null = null;
let currentAdmin: User | null = null;

type AuthListener = (user: User | null) => void;
const userListeners = new Set<AuthListener>();
const adminListeners = new Set<AuthListener>();

function onUserAuthChange(listener: AuthListener): () => void {
  userListeners.add(listener);
  return () => userListeners.delete(listener);
}

function onAdminAuthChange(listener: AuthListener): () => void {
  adminListeners.add(listener);
  return () => adminListeners.delete(listener);
}

export function onAuthChange(userType: UserType, listener: AuthListener): () => void {
  return userType === "admin"
    ? onAdminAuthChange(listener)
    : onUserAuthChange(listener);
}

function emitUserAuthChange(user: User | null) {
  userListeners.forEach((fn) => fn(user));
}

function emitAdminAuthChange(user: User | null) {
  adminListeners.forEach((fn) => fn(user));
}

function emitAuthChange(userType: UserType, user: User | null) {
  if (userType === "admin") {
    emitAdminAuthChange(user);
  } else {
    emitUserAuthChange(user);
  }
}

// ── localStorage auth persistence (for production mode) ──
function getStorageKey(userType: UserType): string {
  return `auth_${userType}`;
}

export function saveAuthToStorage(token: string, user: User, userType: UserType) {
  if (!isClient()) return;
  localStorage.setItem(getStorageKey(userType), JSON.stringify({ token, user }));
}

function clearAuthFromStorage(userType: UserType) {
  if (!isClient()) return;
  localStorage.removeItem(getStorageKey(userType));
}

function loadAuthFromStorage(userType: UserType): { token: string; user: User } | null {
  if (!isClient()) return null;
  try {
    const raw = localStorage.getItem(getStorageKey(userType));
    return raw ? JSON.parse(raw) : null;
  } catch {
    return null;
  }
}

// Restore auth state from localStorage on init
if (isClient()) {
  const saved = loadAuthFromStorage("admin");
  if (saved) currentAdmin = saved.user;
  const savedUser = loadAuthFromStorage("user");
  if (savedUser) currentUser = savedUser.user;
}

// ── Token refresh (auto-renew on 401) ──
let _refreshPromise: Promise<string | null> | null = null;

async function _doRefresh(userType: UserType): Promise<string | null> {
  if (_refreshPromise) return _refreshPromise;
  _refreshPromise = (async () => {
    try {
      const saved = loadAuthFromStorage(userType);
      if (!saved?.token) return null;
      const res = await fetchWithTimeout(`${API_BASE}/auth/refresh`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Authorization": `Bearer ${saved.token}` },
      });
      if (!res.ok) { clearAuthFromStorage(userType); return null; }
      const data = await res.json();
      if (data.access_token) {
        saveAuthToStorage(data.access_token, saved.user, userType);
        return data.access_token;
      }
      return null;
    } catch { return null; }
    finally { _refreshPromise = null; }
  })();
  return _refreshPromise;
}

// ── Gradio 5.x API caller (for HF Spaces production) ──
async function gradioPredict<T>(apiName: string, data: unknown[] = []): Promise<T> {
  const res = await fetchWithTimeout(`${API_BASE}/_call/${apiName}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ data }),
  });

  if (!res.ok) {
    const text = await res.text().catch(() => "");
    throw new Error(`Gradio call failed: ${res.status}${text ? ` - ${text}` : ""}`);
  }

  const { event_id } = await res.json();

  // Poll for result via SSE (streaming, allow a longer timeout)
  const dataRes = await fetchWithTimeout(`${API_BASE}/_call/${apiName}/${event_id}`, undefined, STREAM_TIMEOUT_MS);
  if (!dataRes.ok) {
    throw new Error(`Gradio data fetch failed: ${dataRes.status}`);
  }

  const reader = dataRes.body?.getReader();
  if (!reader) throw new Error("No response body");

  const decoder = new TextDecoder();
  let buffer = "";

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });

    for (const line of buffer.split("\n")) {
      if (line.startsWith("data: ")) {
        try {
          const event = JSON.parse(line.slice(6));
          if (Array.isArray(event) && typeof event[0] === "string") {
            return JSON.parse(event[0]) as T;
          }
        } catch {
          // continue waiting for complete event
        }
      }
    }
  }

  // Try parsing remaining buffer
  for (const line of buffer.split("\n")) {
    if (line.startsWith("data: ")) {
      const event = JSON.parse(line.slice(6));
      if (Array.isArray(event) && typeof event[0] === "string") {
        return JSON.parse(event[0]) as T;
      }
      return event as T;
    }
  }

  throw new Error("No result from Gradio API");
}

// ── Main API caller ──
export async function api<T>(path: string, options?: RequestInit, _userType: UserType = "user", timeoutMs?: number): Promise<T> {
  if (IS_PRODUCTION) {
    return gradioApiCaller<T>(path, options, _userType, timeoutMs);
  }

  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    "X-Auth-Type": _userType,
    ...((options?.headers as Record<string, string>) || {}),
  };

  const saved = isClient() ? loadAuthFromStorage(_userType) : null;
  if (saved?.token) headers["Authorization"] = `Bearer ${saved.token}`;

  const res = await fetchWithTimeout(`${API_BASE}${path}`, { ...options, headers }, timeoutMs);

  if (!res.ok) {
    const text = await res.text().catch(() => "");
    let msg = `API error: ${res.status}`;
    if (text && !text.startsWith("<!")) {
      try {
        const err = JSON.parse(text);
        msg = err.detail || err.error || err.message || msg;
      } catch {}
    }
    if (res.status === 401 && path !== "/auth/refresh") {
      const newToken = await _doRefresh(_userType);
      if (newToken) {
        headers["Authorization"] = `Bearer ${newToken}`;
        const retryRes = await fetchWithTimeout(`${API_BASE}${path}`, { ...options, headers }, timeoutMs);
        if (retryRes.ok) {
          const retryText = await retryRes.text();
          if (!retryText.startsWith("<!")) return JSON.parse(retryText) as T;
        }
      }
      clearAuthFromStorage(_userType);
      if (_userType === "admin") { currentAdmin = null; emitAdminAuthChange(null); }
      else { currentUser = null; emitUserAuthChange(null); }
    }
    throw new Error(msg);
  }

  const text = await res.text();
  if (text.startsWith("<!")) {
    throw new Error("API unavailable");
  }
  return JSON.parse(text) as T;
}

// ── Direct REST API proxy for HF Spaces (no Gradio protocol) ──
async function gradioApiCaller<T>(path: string, options?: RequestInit, _userType: UserType = "user", timeoutMs?: number): Promise<T> {
  const method = options?.method || "GET";

  // Logout: clear auth state only for the calling user type
  if ((path === "/auth/logout" || path === "/admin/logout") && method === "POST") {
    clearAuthFromStorage(_userType);
    if (_userType === "admin") { currentAdmin = null; emitAdminAuthChange(null); }
    else { currentUser = null; emitUserAuthChange(null); }
    return { message: "Logged out" } as T;
  }

  // /auth/me GET: return from localStorage
  if (path === "/auth/me" && method === "GET") {
    const saved = loadAuthFromStorage(_userType);
    return (saved?.user || null) as T;
  }

  // For all endpoints: call the REST API directly
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    ...((options?.headers as Record<string, string>) || {}),
  };
  const saved = isClient() ? loadAuthFromStorage(_userType) : null;
  if (saved?.token) headers["Authorization"] = `Bearer ${saved.token}`;

  const res = await fetchWithTimeout(`${API_BASE}${path}`, { ...options, headers }, timeoutMs);

  // Handle login response: save token + user to localStorage
  if ((path === "/auth/login" || path === "/admin/login") && method === "POST" && res.ok) {
    const authRes = await res.json() as AuthResponse;
    if (authRes.access_token && authRes.user) {
      saveAuthToStorage(authRes.access_token, authRes.user, _userType);
      if (_userType === "admin") { currentAdmin = authRes.user; emitAdminAuthChange(authRes.user); }
      else { currentUser = authRes.user; emitUserAuthChange(authRes.user); }
    }
    return authRes as T;
  }

  // Handle register response: save token + user to localStorage
  if (path === "/auth/register" && method === "POST" && res.ok) {
    const authRes = await res.json() as AuthResponse;
    if (authRes.access_token && authRes.user) {
      saveAuthToStorage(authRes.access_token, authRes.user, "user");
      currentUser = authRes.user;
      emitUserAuthChange(authRes.user);
    }
    return authRes as T;
  }

  // Handle /auth/me PUT response: update localStorage with fresh API data
  if (path === "/auth/me" && method === "PUT" && res.ok) {
    const updated = await res.json() as User;
    const saved = loadAuthFromStorage(_userType);
    if (saved) {
      saveAuthToStorage(saved.token, updated, _userType);
      if (_userType === "admin") { currentAdmin = updated; emitAdminAuthChange(updated); }
      else { currentUser = updated; emitUserAuthChange(updated); }
    }
    return updated as T;
  }

  if (!res.ok) {
    const text = await res.text().catch(() => "");
    let msg = `API error: ${res.status}`;
    if (text && !text.startsWith("<!")) {
      try {
        const err = JSON.parse(text);
        msg = err.detail || err.error || err.message || msg;
      } catch {}
    }
    if (res.status === 401 && path !== "/auth/refresh") {
      const newToken = await _doRefresh(_userType);
      if (newToken) {
        headers["Authorization"] = `Bearer ${newToken}`;
        const retryRes = await fetchWithTimeout(`${API_BASE}${path}`, { ...options, headers }, timeoutMs);
        if (retryRes.ok) return retryRes.json() as Promise<T>;
      }
      clearAuthFromStorage(_userType);
      if (_userType === "admin") { currentAdmin = null; emitAdminAuthChange(null); }
      else { currentUser = null; emitUserAuthChange(null); }
    }
    throw new Error(msg);
  }

  return res.json() as Promise<T>;
}

// ── Auth API functions ──
function captureAndSaveLocation() {
  if (!navigator.geolocation) return;
  navigator.geolocation.getCurrentPosition(
    (pos) => {
      updateLocation(pos.coords.latitude, pos.coords.longitude).catch(() => {});
    },
    () => {},
    { enableHighAccuracy: false, timeout: 10000, maximumAge: 300000 }
  );
}

export async function login(email: string, password: string): Promise<AuthResponse> {
  const data = await api<AuthResponse>("/auth/login", {
    method: "POST",
    body: JSON.stringify({ email, password }),
  }, "user");
  if (isClient() && data.access_token) {
    saveAuthToStorage(data.access_token, data.user, "user");
    currentUser = data.user;
    emitUserAuthChange(data.user);
    captureAndSaveLocation();
  }
  return data;
}

export async function adminLogin(email: string, password: string): Promise<AuthResponse> {
  const data = await api<AuthResponse>("/admin/login", {
    method: "POST",
    body: JSON.stringify({ email, password }),
  }, "admin");
  if (isClient() && data.access_token) {
    saveAuthToStorage(data.access_token, data.user, "admin");
    currentAdmin = data.user;
    emitAdminAuthChange(data.user);
  }
  return data;
}

export async function register(email: string | undefined, password: string, fullName: string, phone?: string): Promise<AuthResponse> {
  const data = await api<AuthResponse>("/auth/register", {
    method: "POST",
    body: JSON.stringify({ email: email || undefined, password, full_name: fullName, phone }),
  }, "user");
  if (isClient() && data.access_token) {
    saveAuthToStorage(data.access_token, data.user, "user");
    currentUser = data.user;
    emitUserAuthChange(data.user);
    captureAndSaveLocation();
  }
  return data;
}

export async function getMe(userType: UserType = "user"): Promise<User | null> {
  if (isClient() && !loadAuthFromStorage(userType)?.token) {
    return null;
  }
  return api<User>("/auth/me", undefined, userType);
}

export async function logout(userType: UserType = "user") {
  try {
    await api(`/${userType === "admin" ? "admin" : "auth"}/logout`, { method: "POST" }, userType);
  } catch {}
  if (isClient()) {
    clearAuthFromStorage(userType);
    if (userType === "admin") {
      currentAdmin = null;
      emitAdminAuthChange(null);
    } else {
      currentUser = null;
      emitUserAuthChange(null);
    }
  }
}

export function adminLogout() {
  return logout("admin");
}

export function getUser(userType: UserType = "user"): User | null {
  if (!isClient()) return null;
  if (IS_PRODUCTION) {
    const saved = loadAuthFromStorage(userType);
    return saved?.user || null;
  }
  return userType === "admin" ? currentAdmin : currentUser;
}

export function setUser(user: User | null, userType: UserType = "user") {
  if (userType === "admin") {
    currentAdmin = user;
  } else {
    currentUser = user;
  }
}

export function isAuthenticated(_userType: UserType = "user"): boolean {
  if (!isClient()) return false;
  if (IS_PRODUCTION) {
    return !!loadAuthFromStorage(_userType);
  }
  return _userType === "admin" ? currentAdmin !== null : currentUser !== null;
}

export function adminIsAuthenticated(): boolean {
  return isAuthenticated("admin");
}

export async function updateProfile(data: { full_name?: string; phone?: string; avatar_url?: string }): Promise<User> {
  const updated = await api<User>("/auth/me", {
    method: "PUT",
    body: JSON.stringify(data),
  }, "user");
  if (isClient()) {
    const saved = loadAuthFromStorage("user");
    if (saved) saveAuthToStorage(saved.token, updated, "user");
    currentUser = updated;
    emitUserAuthChange(updated);
  }
  return updated;
}

export async function updateLocation(latitude: number, longitude: number): Promise<void> {
  const user = getUser("user");
  if (user) {
    await api("/auth/location", {
      method: "POST",
      body: JSON.stringify({ latitude, longitude }),
    }, "user");
  } else {
    const sessionId = getGuestDeviceId();
    await api("/guest/location", {
      method: "POST",
      body: JSON.stringify({ latitude, longitude }),
      headers: { "X-Session-Id": sessionId },
    });
  }
}

/** Returns (and creates if needed) this device's stable anonymous guest id used to
 *  associate guest chats + location in the admin panel. */
export function getGuestDeviceId(): string {
  if (typeof window === "undefined") return "";
  try {
    let id = localStorage.getItem("guest-session") || "";
    if (!id) {
      id = crypto.randomUUID();
      localStorage.setItem("guest-session", id);
    }
    return id;
  } catch {
    return "";
  }
}