import { APIKey, AuthStatus, DashboardStats, Document, DocumentBlock, DocShare, DocLockInfo, ListItem, Organization, PriorityLevel, SharedList, Space, SystemSettings, Team, TaskList, Thought, SubTask, User, UserInvite, WSMessage, } from './types'; const TOKEN_STORAGE_KEY = 'mindsift_jwt_token'; const OFFLINE_QUEUE_KEY = 'mindsift_offline_capture_queue'; export function getToken(): string | null { return localStorage.getItem(TOKEN_STORAGE_KEY); } export function setToken(token: string): void { localStorage.setItem(TOKEN_STORAGE_KEY, token); } export function clearToken(): void { localStorage.removeItem(TOKEN_STORAGE_KEY); } export function triggerHaptic(pattern: number | number[] = 15): void { try { if (typeof navigator !== 'undefined' && 'vibrate' in navigator) { navigator.vibrate(pattern); } } catch { // Ignore on desktop browsers } } function ensureArray(val: T[] | null | undefined): T[] { return Array.isArray(val) ? val : []; } async function request(path: string, options: RequestInit = {}): Promise { const token = getToken(); const headers: Record = { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', ...(options.headers as Record), }; if (token) { headers['Authorization'] = `Bearer ${token}`; } const controller = new AbortController(); const timeoutId = window.setTimeout(() => controller.abort(), 12000); let res: Response; try { res = await fetch(path, { ...options, headers, cache: 'no-store', signal: controller.signal, }); } finally { window.clearTimeout(timeoutId); } if ( res.status === 401 && !path.includes('/auth/login') && !path.includes('/auth/register') && !path.includes('/auth/setup') && !path.includes('/auth/status') ) { clearToken(); window.dispatchEvent(new CustomEvent('mindsift:unauthorized')); } if (!res.ok) { let errMsg = `HTTP ${res.status}`; try { const errData = await res.json(); if (errData.error) errMsg = errData.error; } catch { // ignore } throw new Error(errMsg); } return res.json(); } export const api = { // --- AUTH, FIRST-BOOT SETUP & SETTINGS --- async getAuthStatus(): Promise { return request('/api/v1/auth/status'); }, async completeSetup(payload: { email: string; password: string; displayName: string; instanceName?: string; sharingMode?: 'open' | 'teams_only' | 'strict_private'; allowRegistration?: boolean; createSampleData?: boolean; }): Promise<{ token: string; user: User }> { const res = await request<{ token: string; user: User }>('/api/v1/auth/setup', { method: 'POST', body: JSON.stringify(payload), }); setToken(res.token); return res; }, async login(email: string, password: string): Promise<{ token: string; user: User }> { const res = await request<{ token: string; user: User }>('/api/v1/auth/login', { method: 'POST', body: JSON.stringify({ email, password }), }); setToken(res.token); return res; }, async register( email: string, password: string, displayName: string, inviteCode?: string ): Promise<{ token: string; user: User }> { const res = await request<{ token: string; user: User }>('/api/v1/auth/register', { method: 'POST', body: JSON.stringify({ email, password, displayName, inviteCode: inviteCode || '' }), }); setToken(res.token); return res; }, async getMe(): Promise<{ user: User; stats: DashboardStats }> { return request<{ user: User; stats: DashboardStats }>('/api/v1/auth/me'); }, async updateSettings(patch: { displayName?: string; email?: string; password?: string; alarmChannels?: string[]; alarmEmail?: string; discordWebhookUrl?: string; customWebhookUrl?: string; notifyBeforeMinutes?: number; }): Promise { return request('/api/v1/auth/settings', { method: 'PATCH', body: JSON.stringify(patch), }); }, async testAlarmChannel( channel: 'email' | 'discord' | 'webhook', target?: string ): Promise<{ status: string }> { return request<{ status: string }>('/api/v1/auth/alarms/test', { method: 'POST', body: JSON.stringify({ channel, target: target || '' }), }); }, async getStats(): Promise { return request('/api/v1/stats'); }, async getUsersDirectory(): Promise { const res = await request('/api/v1/users/directory'); return ensureArray(res); }, // --- INSTANT CAPTURE & OFFLINE SYNC --- async captureThought( content: string, priority: PriorityLevel = 'normal', source: 'manual' | 'voice' = 'manual', dueDate = '', options?: { target?: 'inbox' | 'task' | 'list_item' | 'document'; targetListId?: string; taskListId?: string; } ): Promise { try { const thought = await request('/api/v1/inbox', { method: 'POST', body: JSON.stringify({ content, priority, source, dueDate, target: options?.target || 'inbox', targetListId: options?.targetListId || '', taskListId: options?.taskListId || '', }), }); return thought; } catch { // Queue locally if offline const queue = getOfflineQueue(); const offlineThought: Thought = { id: `th_offline_${Date.now()}`, userId: 'offline', content, tags: (content.match(/#([a-zA-Z0-9äöüÄÖÜß_-]+)/g) || []).map((t) => t.slice(1).toLowerCase()), priority, source, status: 'inbox', isCompleted: false, dueDate, taskListId: options?.taskListId || '', createdAt: new Date().toISOString(), }; queue.push(offlineThought); localStorage.setItem(OFFLINE_QUEUE_KEY, JSON.stringify(queue)); return offlineThought; } }, async flushOfflineQueue(): Promise { const queue = getOfflineQueue(); if (queue.length === 0) return 0; let synced = 0; const remaining: Thought[] = []; for (const item of queue) { try { await request('/api/v1/inbox', { method: 'POST', body: JSON.stringify({ content: item.content, priority: item.priority, source: item.source, dueDate: item.dueDate || '', taskListId: item.taskListId || '', }), }); synced++; } catch { remaining.push(item); } } localStorage.setItem(OFFLINE_QUEUE_KEY, JSON.stringify(remaining)); return synced; }, // --- THOUGHTS, TRIAGE & TASKS --- async getTriageDeck(): Promise { const res = await request('/api/v1/triage/deck'); return ensureArray(res); }, async getThoughts(status = 'all'): Promise { const res = await request(`/api/v1/thoughts?status=${encodeURIComponent(status)}`); return ensureArray(res); }, async triageAction( thoughtId: string, action: 'keep' | 'discard' | 'restore', options?: { convertTo?: 'task' | 'document' | 'list_item'; targetListId?: string; taskListId?: string; dueDate?: string; } ): Promise { return request(`/api/v1/triage/${thoughtId}`, { method: 'PATCH', body: JSON.stringify({ action, convertTo: options?.convertTo || '', targetListId: options?.targetListId || '', taskListId: options?.taskListId || '', dueDate: options?.dueDate || '', }), }); }, async getTasks(taskListId?: string): Promise { const query = taskListId ? `?taskListId=${encodeURIComponent(taskListId)}` : ''; const res = await request(`/api/v1/tasks${query}`); return ensureArray(res); }, async updateThought( thoughtId: string, patch: { content?: string; isCompleted?: boolean; dueDate?: string; priority?: PriorityLevel; taskListId?: string; kanbanStatus?: 'todo' | 'in_progress' | 'done'; notes?: string; subtasks?: SubTask[]; } ): Promise { return request(`/api/v1/thoughts/${thoughtId}`, { method: 'PATCH', body: JSON.stringify(patch), }); }, async deleteThought(thoughtId: string): Promise { await request(`/api/v1/thoughts/${thoughtId}`, { method: 'DELETE' }); }, async purgeDiscarded(): Promise<{ purged: number }> { return request<{ purged: number }>('/api/v1/thoughts/discarded/purge', { method: 'DELETE' }); }, // --- TASK LISTS --- async getTaskLists(): Promise { const res = await request('/api/v1/task-lists'); return ensureArray(res); }, async createTaskList(payload: { title: string; icon?: string; color?: string; spaceId?: string; }): Promise { return request('/api/v1/task-lists', { method: 'POST', body: JSON.stringify(payload), }); }, async updateTaskList( id: string, patch: { title?: string; icon?: string; color?: string; spaceId?: string; } ): Promise { return request(`/api/v1/task-lists/${id}`, { method: 'PUT', body: JSON.stringify(patch), }); }, async deleteTaskList(id: string): Promise { await request(`/api/v1/task-lists/${id}`, { method: 'DELETE' }); }, // --- WORKSPACE DOCUMENTS --- async getDocuments(): Promise { const res = await request('/api/v1/documents'); return ensureArray(res).map((d) => ({ ...d, blocks: ensureArray(d.blocks), tags: ensureArray(d.tags), })); }, async getDocument(id: string): Promise { const d = await request(`/api/v1/documents/${id}`); return { ...d, blocks: ensureArray(d.blocks), tags: ensureArray(d.tags), }; }, async createDocument(payload: { title: string; icon?: string; folderPath?: string; blocks?: DocumentBlock[]; tags?: string[]; isPinned?: boolean; }): Promise { const d = await request('/api/v1/documents', { method: 'POST', body: JSON.stringify(payload), }); return { ...d, blocks: ensureArray(d.blocks), tags: ensureArray(d.tags), }; }, async updateDocument( id: string, patch: { title?: string; icon?: string; folderPath?: string; blocks?: DocumentBlock[]; tags?: string[]; isPinned?: boolean; } ): Promise { const d = await request(`/api/v1/documents/${id}`, { method: 'PUT', body: JSON.stringify(patch), }); return { ...d, blocks: ensureArray(d.blocks), tags: ensureArray(d.tags), }; }, async deleteDocument(id: string): Promise { await request(`/api/v1/documents/${id}`, { method: 'DELETE' }); }, // --- DOCUMENT SHARING --- async getDocShares(docId: string): Promise { const res = await request(`/api/v1/documents/${docId}/shares`); return ensureArray(res); }, async createDocShare( docId: string, payload: { userId?: string; email?: string; permission: 'read' | 'write' } ): Promise { return request(`/api/v1/documents/${docId}/shares`, { method: 'POST', body: JSON.stringify(payload), }); }, async deleteDocShare(docId: string, userId: string): Promise { await request(`/api/v1/documents/${docId}/shares/${userId}`, { method: 'DELETE' }); }, async getCollaborators(): Promise { const res = await request('/api/v1/collaborators'); return ensureArray(res); }, // --- DOCUMENT LOCKING --- async getDocLock(docId: string): Promise<{ locked: boolean; lock?: DocLockInfo }> { return request<{ locked: boolean; lock?: DocLockInfo }>(`/api/v1/documents/${docId}/lock`); }, async lockDocument( docId: string ): Promise<{ locked: boolean; acquired: boolean; lock?: DocLockInfo; message?: string }> { try { return await request<{ locked: boolean; acquired: boolean; lock?: DocLockInfo; message?: string }>( `/api/v1/documents/${docId}/lock`, { method: 'POST' } ); } catch (e: any) { return { locked: true, acquired: false, message: e.message }; } }, async heartbeatDocLock(docId: string): Promise<{ extended: boolean }> { try { return await request<{ extended: boolean }>(`/api/v1/documents/${docId}/lock/heartbeat`, { method: 'POST', }); } catch { return { extended: false }; } }, async unlockDocument(docId: string): Promise<{ unlocked: boolean }> { try { return await request<{ unlocked: boolean }>(`/api/v1/documents/${docId}/lock`, { method: 'DELETE', }); } catch { return { unlocked: false }; } }, // --- SPACES & REALTIME LISTS --- async getSpaces(): Promise { const res = await request('/api/v1/spaces'); return ensureArray(res).map((s) => ({ ...s, members: ensureArray(s.members), })); }, async createSpace(name: string, icon: string, description: string): Promise { return request('/api/v1/spaces', { method: 'POST', body: JSON.stringify({ name, icon, description }), }); }, async joinSpace(inviteCode: string): Promise { return request('/api/v1/spaces/join', { method: 'POST', body: JSON.stringify({ inviteCode }), }); }, async getSpaceLists(spaceId: string): Promise { const res = await request(`/api/v1/spaces/${spaceId}/lists`); return ensureArray(res).map((l) => ({ ...l, items: ensureArray(l.items), })); }, async getAllLists(): Promise { const res = await request('/api/v1/lists'); return ensureArray(res).map((l) => ({ ...l, items: ensureArray(l.items), })); }, async createList(spaceId: string, title: string, icon: string, listType: 'shopping' | 'checklist' | 'vacation'): Promise { const l = await request(`/api/v1/spaces/${spaceId}/lists`, { method: 'POST', body: JSON.stringify({ title, icon, listType }), }); return { ...l, items: ensureArray(l.items), }; }, async deleteList(listId: string): Promise { await request(`/api/v1/lists/${listId}`, { method: 'DELETE' }); }, async createListItem(listId: string, content: string, category = '', quantity = ''): Promise { return request(`/api/v1/lists/${listId}/items`, { method: 'POST', body: JSON.stringify({ content, category, quantity }), }); }, async toggleListItem(listId: string, itemId: string, isCompleted?: boolean): Promise { return request(`/api/v1/lists/${listId}/items/${itemId}`, { method: 'PATCH', body: JSON.stringify({ isCompleted }), }); }, async deleteListItem(listId: string, itemId: string): Promise { await request(`/api/v1/lists/${listId}/items/${itemId}`, { method: 'DELETE' }); }, async clearCompletedItems(listId: string): Promise<{ removed: number }> { return request<{ removed: number }>(`/api/v1/lists/${listId}/clear-completed`, { method: 'POST', }); }, // --- ORGANIZATIONS & TEAMS --- async getOrganizations(): Promise { const res = await request('/api/v1/organizations'); return ensureArray(res).map((o) => ({ ...o, teams: ensureArray(o.teams).map((t) => ({ ...t, members: ensureArray(t.members), })), })); }, async createOrganization(name: string): Promise { return request('/api/v1/organizations', { method: 'POST', body: JSON.stringify({ name }), }); }, async deleteOrganization(id: string): Promise { await request(`/api/v1/organizations/${id}`, { method: 'DELETE' }); }, async getOrgTeams(orgId: string): Promise { const res = await request(`/api/v1/organizations/${orgId}/teams`); return ensureArray(res).map((t) => ({ ...t, members: ensureArray(t.members) })); }, async createOrgTeam(orgId: string, name: string, description: string): Promise { return request(`/api/v1/organizations/${orgId}/teams`, { method: 'POST', body: JSON.stringify({ name, description }), }); }, async deleteTeam(teamId: string): Promise { await request(`/api/v1/teams/${teamId}`, { method: 'DELETE' }); }, async getUserTeams(): Promise { const res = await request('/api/v1/teams'); return ensureArray(res).map((t) => ({ ...t, members: ensureArray(t.members) })); }, async addTeamMember( teamId: string, payload: { userId?: string; email?: string; role: string } ): Promise { await request(`/api/v1/teams/${teamId}/members`, { method: 'POST', body: JSON.stringify(payload), }); }, async removeTeamMember(teamId: string, userId: string): Promise { await request(`/api/v1/teams/${teamId}/members/${userId}`, { method: 'DELETE' }); }, // --- ADMIN & STAFF PANEL --- async adminGetUsers(): Promise { const res = await request('/api/v1/admin/users'); return ensureArray(res); }, async adminCreateUser(payload: { email: string; password: string; displayName: string; role: string; }): Promise { return request('/api/v1/admin/users', { method: 'POST', body: JSON.stringify(payload), }); }, async adminUpdateUser( id: string, patch: { displayName?: string; email?: string; role?: string; isActive?: boolean; discordWebhookUrl?: string; } ): Promise { return request(`/api/v1/admin/users/${id}`, { method: 'PATCH', body: JSON.stringify(patch), }); }, async adminResetPassword(id: string, password: string): Promise { await request(`/api/v1/admin/users/${id}/password`, { method: 'PUT', body: JSON.stringify({ password }), }); }, async adminDeleteUser(id: string): Promise { await request(`/api/v1/admin/users/${id}`, { method: 'DELETE' }); }, async adminGetInvites(): Promise { const res = await request('/api/v1/admin/invites'); return ensureArray(res); }, async adminCreateInvite(payload: { email?: string; role: string; teamId?: string; }): Promise { return request('/api/v1/admin/invites', { method: 'POST', body: JSON.stringify(payload), }); }, async adminDeleteInvite(id: string): Promise { await request(`/api/v1/admin/invites/${id}`, { method: 'DELETE' }); }, async adminGetSettings(): Promise { return request('/api/v1/admin/settings'); }, async adminUpdateSettings(settings: SystemSettings): Promise { return request('/api/v1/admin/settings', { method: 'PUT', body: JSON.stringify(settings), }); }, async adminTestSMTP(toEmail: string): Promise<{ status: string }> { return request<{ status: string }>('/api/v1/admin/smtp/test', { method: 'POST', body: JSON.stringify({ toEmail }), }); }, // --- API KEYS, WEBHOOKS & EXPORT --- async getAPIKeys(): Promise { const res = await request('/api/v1/keys'); return ensureArray(res); }, async createAPIKey(name: string): Promise { return request('/api/v1/keys', { method: 'POST', body: JSON.stringify({ name }), }); }, async deleteAPIKey(id: string): Promise { await request(`/api/v1/keys/${id}`, { method: 'DELETE' }); }, async testWebhookIngest( token: string, title: string, priority: PriorityLevel, tags: string[] ): Promise<{ status: string; thought: Thought }> { return request<{ status: string; thought: Thought }>( `/api/v1/webhooks/ingest?token=${encodeURIComponent(token)}`, { method: 'POST', body: JSON.stringify({ title, priority, tags }), } ); }, async searchAll(q: string): Promise<{ thoughts: Thought[]; documents: Document[] }> { return request<{ thoughts: Thought[]; documents: Document[] }>( `/api/v1/search?q=${encodeURIComponent(q)}` ); }, async exportAll(): Promise { return request('/api/v1/export'); }, }; export function getOfflineQueue(): Thought[] { try { const raw = localStorage.getItem(OFFLINE_QUEUE_KEY); if (!raw) return []; return JSON.parse(raw); } catch { return []; } } let activeGlobalWS: WebSocket | null = null; let wsReconnectTimer: any = null; let wsListeners: ((msg: WSMessage) => void)[] = []; let manualDisconnect = false; export function buildWebSocketURL(spaceId?: string): string { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const token = getToken() || ''; if (spaceId) { return `${protocol}//${window.location.host}/api/v1/ws/spaces/${encodeURIComponent(spaceId)}?token=${encodeURIComponent(token)}`; } return `${protocol}//${window.location.host}/api/v1/ws?token=${encodeURIComponent(token)}`; } export function connectWebSocket(): void { const token = getToken(); if (!token) return; manualDisconnect = false; if (activeGlobalWS && (activeGlobalWS.readyState === WebSocket.OPEN || activeGlobalWS.readyState === WebSocket.CONNECTING)) { return; } try { const url = buildWebSocketURL(); const ws = new WebSocket(url); activeGlobalWS = ws; ws.onmessage = (event) => { try { const msg = JSON.parse(event.data) as WSMessage; wsListeners.forEach((fn) => { try { fn(msg); } catch (e) { console.error('WS listener error', e); } }); window.dispatchEvent(new CustomEvent('mindsift:ws', { detail: msg })); } catch (err) { console.error('Failed to parse WS message', err); } }; ws.onclose = () => { activeGlobalWS = null; if (!manualDisconnect && getToken()) { clearTimeout(wsReconnectTimer); wsReconnectTimer = setTimeout(() => { connectWebSocket(); }, 3000); } }; ws.onerror = () => { try { ws.close(); } catch {} }; } catch (e) { console.error('Failed to connect WebSocket', e); } } export function disconnectWebSocket(): void { manualDisconnect = true; clearTimeout(wsReconnectTimer); if (activeGlobalWS) { try { activeGlobalWS.close(); } catch {} activeGlobalWS = null; } } export function sendWebSocketMessage(msg: any): void { if (activeGlobalWS && activeGlobalWS.readyState === WebSocket.OPEN) { activeGlobalWS.send(typeof msg === 'string' ? msg : JSON.stringify(msg)); } } export function onWebSocketMessage(callback: (msg: WSMessage) => void): () => void { wsListeners.push(callback); return () => { wsListeners = wsListeners.filter((fn) => fn !== callback); }; }