File size: 11,667 Bytes
94c9882
c92b696
 
 
 
 
 
 
bea55e2
c92b696
 
 
 
94c9882
bea55e2
 
 
 
 
 
 
 
 
 
94c9882
 
 
 
 
 
 
 
 
 
 
bea55e2
 
 
 
94c9882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c92b696
94c9882
 
 
bea55e2
94c9882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c92b696
94c9882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bea55e2
94c9882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bea55e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94c9882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bea55e2
94c9882
1
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
// Cellex API Client
// For web: uses relative paths (/api/) — handled by Next.js route handlers
// For Capacitor (APK/IPA): uses absolute URL to the live HF Space
// Detection: checks if running on localhost with Capacitor's native bridge

import { Capacitor } from '@capacitor/core';

const API_BASE = Capacitor.isNativePlatform()
  ? 'https://eesha-learn.onrender.com'
  : '';

export { Capacitor };
export { API_BASE };

// Owncast streaming server — handles live video for seller go-live sessions.
// Sellers stream to this RTMP endpoint via OBS or their phone's streaming app.
// Viewers watch via the embed URL (embedded in /live-watch).
// Admin panel is at /admin (admin / Cellex2026!).
export const OWNCAST_URL = 'https://ai-module-tester.onrender.com';
export const OWNCAST_RTMP_SERVER = 'rtmp://ai-module-tester.onrender.com/live';
export const OWNCAST_STREAM_KEY = 'cellex-live-2026';
export const OWNCAST_EMBED_URL = `${OWNCAST_URL}/embed/stream`;
export const OWNCAST_HLS_URL = `${OWNCAST_URL}/hls/stream.m3u8`;

export interface Product {
  id: number;
  name: string;
  price: number;
  description?: string;
  image_url?: string;
  category?: string;
  seller_id?: string;
  units_sold?: number;
  created_at?: string;
  additional_images?: string[];
  video_url?: string;
  group_buy_enabled?: boolean;
  group_buy_target_count?: number;
  group_buy_discount_pct?: number;
}

export interface Seller {
  id: string;
  business_name?: string;
  farm_name?: string;
  business_category?: string;
  business_location?: string;
  profile_image?: string;
  seller_type?: string;
  created_at?: string;
}

export interface CartItem {
  id: string;
  product_id: number;
  quantity: number;
  products?: Product;
}

export interface Review {
  id: string;
  user_id: string;
  product_id: number;
  rating: number;
  title?: string;
  comment?: string;
  images?: string[];
  verified_purchase?: boolean;
  helpful_count?: number;
  created_at?: string;
  reviewer_name?: string;
}

async function apiCall(path: string, body: Record<string, unknown> = {}) {
  const resp = await fetch(`${API_BASE}/api/${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
    credentials: 'include',
  });
  const data = await resp.json();
  if (!resp.ok) {
    return { success: false, error: data.error || 'Request failed', status: resp.status };
  }
  return data;
}

export const api = {
  // ===== Auth =====
  auth: {
    login: (email: string, password: string) =>
      apiCall('auth', { op: 'login', email, password }),
    signup: (email: string, password: string) =>
      apiCall('auth', { op: 'signup', email, password }),
    logout: () => apiCall('auth', { op: 'logout' }),
    session: () => apiCall('auth', { op: 'session' }),
  },

  // ===== Products =====
  products: {
    home: () => apiCall('products', { op: 'home' }),
    search: (query: string, maxPrice?: number | null) =>
      apiCall('products', { op: 'search', query, maxPrice }),
    category: (category: string, sort = 'newest', page = 1) =>
      apiCall('products', { op: 'category', category, sort, page }),
    byId: (id: number) => apiCall('products', { op: 'by_id', id }),
    all: (limit = 100) => apiCall('products', { op: 'all', limit }),
  },

  // ===== Cart =====
  cart: {
    get: () => apiCall('cart', { op: 'get' }),
    count: () => apiCall('cart', { op: 'count' }),
    add: (productId: number, quantity = 1) => apiCall('cart', { op: 'add', productId, quantity }),
    remove: (cartItemId: string) => apiCall('cart', { op: 'remove', cartItemId }),
    update: (cartItemId: string, quantity: number) => apiCall('cart', { op: 'update', cartItemId, quantity }),
    clear: () => apiCall('cart', { op: 'clear' }),
  },

  // ===== Wishlist =====
  wishlist: {
    get: () => apiCall('wishlist', { op: 'get' }),
    add: (productId: number) => apiCall('wishlist', { op: 'add', productId }),
    remove: (wishlistItemId: string) => apiCall('wishlist', { op: 'remove', wishlistItemId }),
  },

  // ===== Orders =====
  orders: {
    list: () => apiCall('orders', { op: 'list' }),
    details: (orderId: string) => apiCall('orders', { op: 'details', orderId }),
  },

  // ===== Checkout =====
  checkout: {
    prepare: () => apiCall('checkout', { op: 'prepare' }),
    placeOrder: (shippingAddress: Record<string, unknown>) =>
      apiCall('checkout', { op: 'place_order', shippingAddress }),
  },

  // ===== Reviews =====
  reviews: {
    byProduct: (productId: number) => apiCall('reviews', { op: 'by_product', productId }),
    bySeller: (sellerId: string) => apiCall('reviews', { op: 'by_seller', sellerId }),
    create: (data: { productId: number; rating: number; title?: string; comment?: string; images?: string[] }) =>
      apiCall('reviews', { op: 'create', ...data }),
    helpful: (reviewId: string) => apiCall('reviews', { op: 'helpful', reviewId }),
  },

  // ===== Social =====
  social: {
    publicProfile: (sellerId: string, viewerId?: string | null) =>
      apiCall('social', { op: 'public_profile', sellerId, viewerId }),
    sellerFeed: (sellerId: string, limit = 20) => apiCall('social', { op: 'seller_feed', sellerId, limit }),
    discover: (limit = 12) => apiCall('social', { op: 'discover', limit }),
    follow: (sellerId: string) => apiCall('social', { op: 'follow', sellerId }),
    unfollow: (sellerId: string) => apiCall('social', { op: 'unfollow', sellerId }),
    following: () => apiCall('social', { op: 'following' }),
    feed: (limit = 20, offset = 0) => apiCall('social', { op: 'feed', limit, offset }),
  },

  // ===== Group Buy =====
  groupBuy: {
    create: (productId: number, targetCount = 3, discountPct = 20) =>
      apiCall('group-buy', { op: 'create', productId, targetCount, discountPct }),
    join: (groupBuyId: string) => apiCall('group-buy', { op: 'join', groupBuyId }),
    status: (groupBuyId: string) => apiCall('group-buy', { op: 'status', groupBuyId }),
    active: (productId: number) => apiCall('group-buy', { op: 'active', productId }),
    mine: () => apiCall('group-buy', { op: 'mine' }),
    cancel: (groupBuyId: string) => apiCall('group-buy', { op: 'cancel', groupBuyId }),
  },

  // ===== Videos =====
  videos: {
    feed: (limit = 20) => apiCall('videos', { op: 'feed', limit }),
    byProduct: (productId: number) => apiCall('videos', { op: 'by_product', productId }),
    bySeller: (sellerId: string) => apiCall('videos', { op: 'by_seller', sellerId }),
    get: (videoId: number) => apiCall('videos', { op: 'get', videoId }),
    like: (videoId: number) => apiCall('videos', { op: 'like', videoId }),
    unlike: (videoId: number) => apiCall('videos', { op: 'unlike', videoId }),
  },

  // ===== Live Shopping =====
  live: {
    list: (status = 'live') => apiCall('live', { op: 'list', status }),
    get: (sessionId: string) => apiCall('live', { op: 'get', sessionId }),
    messages: (sessionId: string, afterId = 0) => apiCall('live', { op: 'messages', sessionId, afterId }),
    join: (sessionId: string, name?: string) => apiCall('live', { op: 'join', sessionId, name }),
    leave: (sessionId: string) => apiCall('live', { op: 'leave', sessionId }),
    message: (sessionId: string, message: string) => apiCall('live', { op: 'message', sessionId, message }),
  },

  // ===== Stories =====
  stories: {
    activeBar: () => apiCall('stories', { op: 'active_bar' }),
    bySeller: (sellerId: string) => apiCall('stories', { op: 'by_seller', sellerId }),
    get: (storyId: number) => apiCall('stories', { op: 'get', storyId }),
  },

  // ===== Trending =====
  trending: {
    list: (limit = 20, hours = 24) => apiCall('trending', { op: 'list', limit, hours }),
  },

  // ===== AI Discover =====
  discover: {
    recommend: (limit = 10) => apiCall('discover', { op: 'recommend', limit }),
  },

  // ===== Cross-platform =====
  crossPlatform: {
    generateLinkCode: (phone: string) => apiCall('cross-platform', { op: 'generate_link_code', phone }),
    myPhoneLinks: () => apiCall('cross-platform', { op: 'my_phone_links' }),
    unlinkPhone: (phone: string) => apiCall('cross-platform', { op: 'unlink_phone', phone }),
  },

  // ===== Telegram =====
  telegram: {
    channelInfo: () => apiCall('telegram', { op: 'channel_info' }),
    subscribe: (chatId: string) => apiCall('telegram', { op: 'subscribe', chatId }),
    unsubscribe: (chatId: string) => apiCall('telegram', { op: 'unsubscribe', chatId }),
    recent: (limit = 10) => apiCall('telegram', { op: 'recent', limit }),
  },

  // ===== Payment =====
  payment: {
    createOrder: (data: {
      buyerName: string;
      buyerEmail: string;
      buyerPhone?: string;
      buyerBankName?: string;
      itemsSummary: string;
      itemCount: number;
      total: number;
    }) => apiCall('payment', { op: 'create_order', ...data }),
    confirmSent: (orderId: string) => apiCall('payment', { op: 'confirm_sent', orderId }),
    checkStatus: (orderId: string) => apiCall('payment', { op: 'check_status', orderId }),
  },

  // ===== Profile =====
  profile: {
    get: () => apiCall('profile', { op: 'get' }),
    update: (data: { fullName?: string; phone?: string; address?: string; profileImage?: string }) =>
      apiCall('profile', { op: 'update', ...data }),
  },

  // ===== Seller =====
  sellerDashboard: {
    stats: () => apiCall('seller-dashboard', { op: 'stats' }),
    recent: () => apiCall('seller-dashboard', { op: 'recent' }),
  },
  sellerProducts: {
    list: () => apiCall('seller-products', { op: 'list' }),
    create: (data: { name: string; price: number; description?: string; category?: string; image_url?: string }) =>
      apiCall('seller-products', { op: 'create', ...data }),
    update: (id: number, data: Record<string, unknown>) => apiCall('seller-products', { op: 'update', id, ...data }),
    delete: (id: number) => apiCall('seller-products', { op: 'delete', id }),
  },
  sellerOrders: {
    list: () => apiCall('seller-orders', { op: 'list' }),
  },

  // ===== AI Recommendations (Gorse + NVIDIA + Chroma) =====
  recommend: {
    home: (limit?: number) =>
      apiCall('recommend', { op: 'home', limit }),
    category: (category: string, limit?: number) =>
      apiCall('recommend', { op: 'category', category, limit }),
    shorts: (limit?: number) =>
      apiCall('recommend', { op: 'shorts', limit }),
    neighbors: (itemId: string | number, limit?: number) =>
      apiCall('recommend', { op: 'neighbors', itemId: String(itemId), limit }),
  },

  // ===== Smart Search (NVIDIA + Chroma) =====
  smartSearch: (query: string, limit?: number) =>
    apiCall('smart-search', { query, limit }),

  // ===== Feedback Sync (non-blocking) =====
  feedback: (itemId: string | number, type: string, score?: number, metadata?: any) =>
    apiCall('feedback', { itemId: String(itemId), type, score, metadata }),
};

// ===== Utility functions =====
export function formatPrice(n: number): string {
  return `₦${Number(n || 0).toLocaleString('en-NG', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
}

export function timeAgo(iso?: string): string {
  if (!iso) return '';
  const d = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 60) return 'just now';
  if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
  if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
  if (diff < 604800) return Math.floor(diff / 86400) + 'd ago';
  return d.toLocaleDateString();
}

export function escapeHtml(s: unknown): string {
  return String(s ?? '').replace(/[&<>"']/g, c => ({
    '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
  }[c] as string));
}