'use client'; import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react'; import type { Category, Course, DataSource, InboxItem, Locale, Settings, Student, Viewer } from '@lms/data'; import { LOCALES, newId } from '@lms/data'; import { messages } from '@lms/i18n'; export const DEFAULT_SETTINGS: Settings = { brandName: 'Sirkul Makeup', supportPhone: '+251 911 000 000', telegramLink: 'https://t.me/', supportEmail: 'support@example.com', sessionLimit: 2, maintenanceBanner: '' }; const store = { get(k: string) { try { return localStorage.getItem('lms.' + k); } catch { return null; } }, set(k: string, v: string | null) { try { v == null ? localStorage.removeItem('lms.' + k) : localStorage.setItem('lms.' + k, v); } catch { /* per-viewer convenience only */ } }, }; // ---------------------------------------------------------------- hash router export function parseRoute(hash: string): string[] { return hash.replace(/^#\/?/, '').split('/').filter(Boolean).map(decodeURIComponent); } interface Ctx { ds: DataSource; viewer: Viewer | null; ready: boolean; categories: Category[]; courses: Course[]; settings: Settings; catalogLoaded: boolean; /** The signed-in student; null when signed out, so no screen shows a signed-out visitor's courses. */ me: Student | null; meLoaded: boolean; signedIn: boolean; /** The stored student record even when signed out (sign-in uses it for "Continue as"). */ account: Student | null; inbox: InboxItem[]; locale: Locale; setLocale(l: Locale): void; route: string[]; nav(path: string): void; toast(msg: string): void; /** Serialized writes: the db wants one write at a time per document. */ write(fn: () => Promise, okMsg?: string): Promise; signIn(): void; signOut(): void; /** Re-reads who is signed in, after a real (API) sign-in. */ reloadViewer(): Promise; notify(studentId: string, item: Omit): Promise; msg(loc: Locale, key: string, vars?: Record): string; } const AppCtx = createContext(null); export const useApp = () => { const c = useContext(AppCtx); if (!c) throw new Error('AppProvider missing'); return c; }; /** Message lookup outside React components (system notifications are written in the student's language). */ export function lookup(loc: Locale, key: string, vars: Record = {}): string { const get = (l: Locale) => key.split('.').reduce((o, k) => o?.[k], messages[l]); const raw: string = get(loc) ?? get('en') ?? key; return raw.replace(/\{(\w+)(?:, plural,[^{}]*(?:\{[^{}]*\}[^{}]*)*)?\}/g, (_m, k) => String(vars[k] ?? '')); } export function AppProvider({ ds, children }: { ds: DataSource; children: ReactNode }) { const [viewer, setViewer] = useState(null); const [ready, setReady] = useState(false); const [categories, setCategories] = useState([]); const [courses, setCourses] = useState([]); const [settings, setSettings] = useState(null); const [catalogLoaded, setCatalogLoaded] = useState(false); const [me, setMe] = useState(null); const [meLoaded, setMeLoaded] = useState(false); const [inbox, setInbox] = useState([]); const [route, setRoute] = useState([]); const [locale, setLocaleState] = useState('en'); const [toastMsg, setToastMsg] = useState(null); const [signedOut, setSignedOut] = useState(false); const chain = useRef>(Promise.resolve()); const toastTimer = useRef | null>(null); // initial route + locale (client only) useEffect(() => { const r = parseRoute(location.hash); const saved = store.get('locale') as Locale | null; const loc = (LOCALES as string[]).includes(r[0]) ? (r[0] as Locale) : saved && LOCALES.includes(saved) ? saved : 'en'; setLocaleState(loc); setRoute(r.length ? r : [loc]); setSignedOut(store.get('signedOut') === '1'); const onHash = () => setRoute(parseRoute(location.hash)); addEventListener('hashchange', onHash); addEventListener('popstate', onHash); return () => { removeEventListener('hashchange', onHash); removeEventListener('popstate', onHash); }; }, []); useEffect(() => { let alive = true; ds.viewer().then((v) => { if (alive) { setViewer(v); setReady(true); } }); let gotCourses = false, gotCats = false; const done = () => { if (gotCourses && gotCats) setCatalogLoaded(true); }; const u1 = ds.watchCourses((c) => { setCourses(c); gotCourses = true; done(); }); const u2 = ds.watchCategories((c) => { setCategories([...c].sort((a, b) => a.sortOrder - b.sortOrder)); gotCats = true; done(); }); const u3 = ds.watchSettings(setSettings); return () => { alive = false; u1(); u2(); u3(); }; }, [ds]); const uid = viewer?.id ?? null; useEffect(() => { if (!ready) return; if (!uid) { setMeLoaded(true); return; } const u1 = ds.watchStudent(uid, (s) => { setMe(s); setMeLoaded(true); }); const u2 = ds.watchInbox(uid, setInbox); return () => { u1(); u2(); }; }, [ds, uid, ready]); const nav = useCallback((path: string) => { const r = parseRoute(path); setRoute(r); try { if (location.hash !== '#' + path) history.pushState(null, '', '#' + path); } catch { /* sandboxed history: state already updated */ } try { scrollTo({ top: 0 }); } catch { /* jsdom */ } }, []); const toast = useCallback((m: string) => { setToastMsg(m); if (toastTimer.current) clearTimeout(toastTimer.current); toastTimer.current = setTimeout(() => setToastMsg(null), 3200); }, []); const msg = useCallback((loc: Locale, key: string, vars?: Record) => lookup(loc, key, vars), []); const write = useCallback((fn: () => Promise, okMsg?: string) => { const p = chain.current.then(fn).then(() => { if (okMsg) toast(okMsg); return true; }, (e) => { console.warn(e); toast(e?.code === 'not_granted' || e?.code === 'invalid_argument' ? lookup(locale, 'common.readOnly') : lookup(locale, 'common.saveFailed')); return false; }); chain.current = p; return p; }, [toast, locale]); const setLocale = useCallback((l: Locale) => { setLocaleState(l); store.set('locale', l); setRoute((r) => { const next = (LOCALES as string[]).includes(r[0]) ? [l, ...r.slice(1)] : r; try { history.replaceState(null, '', '#/' + next.join('/')); } catch { /* ignore */ } return next; }); if (me && me.locale !== l && !me.deletedAt) write(() => ds.patchStudent(me.id, { locale: l })); }, [me, ds, write]); const notify = useCallback(async (studentId: string, item: Omit) => { await ds.addInbox(studentId, { ...item, id: newId('n_'), createdAt: new Date().toISOString(), readAt: null }); }, [ds]); const value: Ctx = { ds, viewer, ready, categories, courses, settings: settings ?? DEFAULT_SETTINGS, catalogLoaded, me: me && !me.deletedAt && !signedOut ? me : null, account: me, meLoaded, signedIn: !!me && !me.deletedAt && !signedOut, inbox, locale, setLocale, route, nav, toast, write, signIn: () => { store.set('signedOut', null); setSignedOut(false); }, // With a real account system, signing out also ends the server session and forgets the user. signOut: () => { store.set('signedOut', '1'); setSignedOut(true); if (ds.auth) ds.auth.signOut().then(() => ds.viewer()).then(setViewer, () => {}); }, reloadViewer: async () => { setViewer(await ds.viewer()); }, notify, msg, }; return ( {children} {toastMsg &&
{toastMsg}
}
); }