'use client'; import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { useTranslations } from 'next-intl'; import type { Assessment, AssessmentResult, Course, Issue, IssueType, Lesson, Locale, Order, Student } from '@lms/data'; import { LOCALES, newId } from '@lms/data'; import { LOCALE_NAMES, DRAFT_LOCALES } from '@lms/i18n'; import { lookup, useApp } from './store'; import { applyHeartbeat, applyPaymentEvent, clock, COUNTRIES, courseDuration, courseProgress, createOrder, DomainError, effectiveStatus, ET_CITIES, formatDuration, formatMoney, gradeAssessment, isCompleted, isStudentVisible, lessonAccess, owns, publishedLessons, resumePoint, tr, validateLocation, validPassword, } from './domain'; import { CAT_PHOTOS, CopyText, Cover, coursePhoto, Empty, FeedbackButton, fmtDate, Icon, KitIcon, Logo, Modal, VIMEO_ORIGIN, VIMEO_PLACEHOLDER, Ring, Skeleton, StatusPill } from './ui'; import { PAY_LOGOS } from './payLogos'; const ISSUE_TYPES: IssueType[] = ['BUG', 'PAYMENT', 'VIDEO', 'ACCOUNT', 'CONTENT', 'OTHER']; // Demo checkout lists every method we plan to accept; all of them run through the same simulated ETB order. const METHODS = [ { id: 'TELEBIRR', name: 'Telebirr', via: 'ArifPay' }, { id: 'CBE_BIRR', name: 'CBE Birr', via: 'ArifPay' }, { id: 'VISA', name: 'Visa', via: 'ArifPay' }, { id: 'MASTERCARD', name: 'Mastercard', via: 'ArifPay' }, { id: 'PAYPAL', name: 'PayPal', via: 'International' }, { id: 'ZELLE', name: 'Zelle', via: 'International' }, ]; const PayLogo = ({ id }: { id: string }) => ; const methodName = (id: string) => METHODS.find((m) => m.id === id)?.name ?? id; // ---------------------------------------------------------------- helpers function useCatalog() { const { courses, categories, me, locale } = useApp(); const visible = useMemo(() => courses.filter((c) => isStudentVisible(c, me)).sort((a, b) => (b.publishedAt ?? '').localeCompare(a.publishedAt ?? '')), [courses, me]); const catName = useCallback((id: string) => tr(categories.find((c) => c.id === id)?.translations, locale)?.name ?? '', [categories, locale]); return { visible, catName }; } const ct = (c: Course, l: Locale) => tr(c.translations, l) ?? { title: c.slug, description: '' }; const lessonTitle = (l: Lesson, loc: Locale) => tr(l.translations, loc)?.title ?? ''; const lessonNumber = (c: Course, id: string) => publishedLessons(c).findIndex((l) => l.id === id) + 1; function CourseCard({ c }: { c: Course }) { const { locale, nav, me, signedIn } = useApp(); const t = useTranslations(); const { catName } = useCatalog(); const p = courseProgress(c, me); const mine = signedIn && owns(me, c.id); return ( ); } function SignInGate({ children }: { children: ReactNode }) { const { signedIn, meLoaded, ready } = useApp(); if (!ready || !meLoaded) return ; return signedIn ? <>{children} : ; } // ---------------------------------------------------------------- shell export function StudentApp() { const t = useTranslations(); const { route, locale, nav, signedIn, inbox, settings } = useApp(); const section = route[1] ?? ''; const unread = signedIn ? inbox.filter((n) => !n.readAt).length : 0; const mainRef = useRef(null); const sheet = useRef(null); const closeSheet = () => sheet.current?.close(); const [touring, setTouring] = useState(false); // The tour runs once, after sign-in and after the first-visit language choice. const maybeTour = useCallback(() => { try { if (signedIn && localStorage.getItem('lms.langChosen') && !localStorage.getItem('lms.tourDone')) setTouring(true); } catch { /* storage blocked: skip the tour */ } }, [signedIn]); useEffect(() => { maybeTour(); }, [maybeTour]); const endTour = () => { try { localStorage.setItem('lms.tourDone', '1'); } catch {} setTouring(false); }; const [scrolled, setScrolled] = useState(false); useEffect(() => { const on = () => setScrolled(scrollY > 24); on(); addEventListener('scroll', on, { passive: true }); return () => removeEventListener('scroll', on); }, []); const go = (p: string) => nav(`/${locale}${p}`); // Tab title per section (the course page sets its own, with the course name). useEffect(() => { if (section !== 'course') document.title = section ? `${t.has(`nav.${section}`) ? t(`nav.${section}`) : settings.brandName} · ${settings.brandName}` : `${settings.brandName} — ${t('landing.title')}`; }, [section, locale, settings.brandName, t]); const tabs: [string, string, string][] = [['', 'home', t('nav.home')], ['courses', 'grid', t('nav.courses')], ['my', 'book', t('nav.myCourses')], ['help', 'help', t('nav.help')], ['profile', 'user', t('nav.profile')]]; const links = tabs.filter(([p]) => p !== 'profile' && (p !== 'my' || signedIn)); const current = (s: string) => (s === section || (s === 'courses' && (section === 'course')) || (s === 'profile' && (section === 'progress' || section === 'history')) ? 'page' : undefined); return (
{signedIn ? <> : <> }
{/* Menu sheet: the main links set large, then the preferences that used to crowd the header. */} { if (e.target === sheet.current) closeSheet(); }}>
{signedIn &&
{t('tour.again')}
}
{t('common.theme')}
{t('common.language')}
{t('common.feedback')} mainRef.current} />

{t('help.telegram')}{settings.supportPhone}

{touring && }
{settings.maintenanceBanner &&
{settings.maintenanceBanner}
}
{signedIn && section !== 'learn' && section !== 'course' && }
); } function LangPick() { const t = useTranslations(); const { locale, setLocale } = useApp(); return ( ); } // Guided tour: each step rings a real element (the first visible match, so phones point at the bottom tabs // and desktops at the header) and explains it. A step whose element isn't on screen shows as a centered card. const TOUR: [string, string | null][] = [['welcome', null], ['continue', '.continue'], ['courses', '[data-tour="courses"]'], ['my', '[data-tour="my"]'], ['profile', '[data-tour="profile"]'], ['menu', '.menu-btn'], ['help', '[data-tour="help"]']]; function Tour({ onDone }: { onDone(): void }) { const t = useTranslations(); const { me } = useApp(); const [i, setI] = useState(0); const [rect, setRect] = useState(null); const [key, sel] = TOUR[i]; const last = i === TOUR.length - 1; useEffect(() => { const el = sel ? [...document.querySelectorAll(sel)].find((e) => e.offsetParent && e.getBoundingClientRect().width > 0) : undefined; if (!el) { setRect(null); return; } el.scrollIntoView({ block: 'center', behavior: 'smooth' }); const measure = () => setRect(el.getBoundingClientRect()); const id = setTimeout(measure, 380); addEventListener('resize', measure); addEventListener('scroll', measure, { passive: true }); return () => { clearTimeout(id); removeEventListener('resize', measure); removeEventListener('scroll', measure); }; }, [sel]); // Esc or any navigation (e.g. the back button) ends the tour. useEffect(() => { const esc = (e: KeyboardEvent) => { if (e.key === 'Escape') onDone(); }; addEventListener('keydown', esc); addEventListener('hashchange', onDone); return () => { removeEventListener('keydown', esc); removeEventListener('hashchange', onDone); }; }, [onDone]); const below = !rect || rect.top + rect.height / 2 < innerHeight / 2; const pad = 8; return (
{rect ?
:
}
{TOUR.map((_, k) => )}
{i + 1} / {TOUR.length}

{t(`tour.${key}T`, { name: me?.name.split(' ')[0] ?? '' })}

{t(`tour.${key}`)}

{!last && } {i > 0 && }
); } // First visit: ask for a language before anything else. Shown in every language, since we don't know theirs yet. const LANG_PROMPT: Record = { en: 'Choose your language', am: 'ቋንቋ ይምረጡ', om: 'Afaan filadhu', ti: 'ቋንቋ ምረጽ' }; function LangWelcome({ onDone }: { onDone(): void }) { const { locale, setLocale } = useApp(); const ref = useRef(null); useEffect(() => { let seen = true; try { seen = !!localStorage.getItem('lms.langChosen'); } catch { /* storage blocked: don't nag */ } if (!seen) ref.current?.showModal(); }, []); const pick = (l: Locale) => { try { localStorage.setItem('lms.langChosen', '1'); } catch {} if (l !== locale) setLocale(l); ref.current?.close(); onDone(); }; return ( pick(locale)}>

{LANG_PROMPT.en}

{LOCALES.filter((l) => l !== 'en').map((l) => {LANG_PROMPT[l]})}

{LOCALES.map((l) => )}
); } // The choice lives in localStorage; apps/demo/app/layout.tsx applies it before first paint. function ThemeToggle({ label }: { label: string }) { const [dark, setDark] = useState(false); useEffect(() => setDark(document.documentElement.dataset.theme === 'dark'), []); const flip = () => { const next = dark ? 'light' : 'dark'; document.documentElement.dataset.theme = next; try { localStorage.setItem('theme', next); } catch {} setDark(!dark); }; return ; } const initials = (name: string) => name.split(/\s+/).filter(Boolean).slice(0, 2).map((w) => w[0]).join('').toUpperCase() || '?'; function UserMenu() { const t = useTranslations(); const { me, viewer, locale, nav, signOut } = useApp(); const ref = useRef(null); useEffect(() => { const close = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) ref.current.open = false; }; addEventListener('click', close); return () => removeEventListener('click', close); }, []); const name = me?.name || viewer?.name || ''; const go = (p: string) => { if (ref.current) ref.current.open = false; nav(p); }; return (
{viewer?.avatarUrl ? : initials(name)}
{name}{(me?.phone || me?.email) && {me?.phone || me?.email}}
); } function Footer() { const t = useTranslations(); const { settings, locale, nav, categories, courses, signedIn, me, route } = useApp(); // Big marketing footer on the landing page and catalog only; app screens get one quiet line (audit 2026-10-16, Q1). const langs = ; const go = (p: string) => nav(`/${locale}${p}`); const kit: [string, string][] = [['foundation', 'kit1'], ['brush', 'kit2'], ['brow', 'kit3'], ['lipstick', 'kit4']]; return (

{settings.brandName}

{t('footer.tagline')}

{t.rich('footer.founder', { name: () => Rezina Brhane })}

{t('footer.contact')} {t('help.telegram')} {settings.supportPhone} {settings.supportEmail && {settings.supportEmail}} {t('footer.tiktok')}

{t('footer.workTitle')}{t('footer.workSub')}

{/* ponytail: placeholder shots until real student work exists; swap WORK_PHOTOS for their uploads. */}
{[...WORK_PHOTOS, ...WORK_PHOTOS].map((f, k) => )}
© {new Date().getFullYear()} {settings.brandName} · {t('footer.rights')}
{t('footer.credits')}

{PHOTO_CREDITS.map(([who, lic, url], k) => {k > 0 && ' · '}{who} ({lic}))} · Wikimedia Commons, Pexels. Icons: IconPark (Apache-2.0).

{t.rich('footer.poweredBy', { name: () => Yaltopia Tech })}

); } function StudentRoutes() { const { route, signedIn } = useApp(); const [, s, a, b] = route; switch (s) { case undefined: return signedIn ? : ; case 'courses': return ; case 'course': return ; case 'learn': return ; case 'assess': return ; case 'checkout': return ; case 'pay': return ; case 'orders': return ; case 'my': return ; case 'progress': return ; // progress lives on the profile case 'history': return ; case 'notifications': return ; case 'help': return ; case 'profile': return ; case 'signin': return !signedIn ? : ; default: return ; } } // ---------------------------------------------------------------- landing + home // Hero collage and category photos (apps/demo/public/photos; credits in PHOTO_CREDITS). Decorative, so they don't wait on the catalog. const HERO_PHOTOS = ['habesha-bride.jpg', 'habesha-harari.jpg', 'habesha-trad.jpg', 'habesha-eritrean.jpg', 'hero.jpg', 'habesha-tigray.jpg']; // The live pill: faces take turns lighting up and it points people to the waitlist (apps/demo/public/waitlist). const FACES = ['habesha-tigray.jpg', 'habesha-harari.jpg', 'habesha-bride.jpg', 'hero.jpg']; const PHOTO_CREDITS: [string, string, string][] = [ ['Rod Waddington', 'CC BY-SA 2.0', 'https://commons.wikimedia.org/wiki/File:Tigray_Bride_(48108302903).jpg'], ['Imagesdumonde', 'CC BY-SA 4.0', 'https://commons.wikimedia.org/wiki/File:Femme_harari_v%C3%AAtue_de_la_tenue_traditionnelle,_orn%C3%A9e_de_bijoux_en_or..jpg'], ['T.Voekler', 'CC BY-SA 3.0', 'https://commons.wikimedia.org/wiki/File:Eritrean_woman.jpg'], ]; const WORK_PHOTOS = ['glam.jpg', 'habesha-harari.jpg', 'bridal.jpg', 'hero.jpg', 'skin.jpg', 'habesha-trad.jpg', 'foundations.jpg', 'habesha-eritrean.jpg', 'clients.jpg', 'habesha-bride.jpg']; const PAY_GROUPS: [string, string[]][] = [['payLocal', ['TELEBIRR', 'CBE_BIRR']], ['payCards', ['VISA', 'MASTERCARD']], ['payAbroad', ['PAYPAL', 'ZELLE']]]; function WaitPill({ label }: { label: string }) { const [i, setI] = useState(0); useEffect(() => { if (matchMedia('(prefers-reduced-motion: reduce)').matches) return; const id = setInterval(() => setI((n) => (n + 1) % FACES.length), 2000); return () => clearInterval(id); }, []); return ( {FACES.map((f, k) => )} {label} ); } function Landing() { const t = useTranslations(); const { locale, nav, catalogLoaded, categories } = useApp(); const { visible } = useCatalog(); const featured = [...visible.filter((c) => c.isFeatured), ...visible.filter((c) => !c.isFeatured)].slice(0, 3); const lead = featured[0]; const preview = lead && publishedLessons(lead).find((l) => l.isPreview); const minPrice = Math.min(...visible.map((c) => c.prices.ETB ?? Infinity)); const cats = categories.filter((c) => c.isActive); const watch = () => { if (lead) nav(preview ? `/${locale}/learn/${lead.slug}/${preview.id}` : `/${locale}/course/${lead.slug}`); }; return (
{[...HERO_PHOTOS, ...HERO_PHOTOS].map((p, i) => )}

{t('landing.title')}

{t('landing.lead')}

{lead && }
    {['fact2', 'fact3'].map((k) =>
  • {t(`landing.${k}`)}
  • )}
{cats.length > 0 &&

{t('landing.catTitle')}

{t('landing.catLead')}

{cats.map((c, i) => ( ))}
}

{t('landing.featured')}

{t('landing.featuredLead')}{Number.isFinite(minPrice) && <> · {t('landing.from', { price: formatMoney(minPrice, 'ETB') })}}

{!catalogLoaded ? : featured.length ?
{featured.map((c) => )}
: {t('catalog.emptyCategory')}}

{t('landing.howTitle')}

{t('landing.payLead')}{Number.isFinite(minPrice) && <> {t('landing.from', { price: formatMoney(minPrice, 'ETB') })}}

    {/* Abstract art per step (CSS only): preview rings, a stack of cards, an unlocking arc. */} {(['play', 'cart', 'lock'] as const).map((icon, k) =>
  1. {t(`landing.how${k + 1}`)}
  2. )}

{t('landing.payTitle')}

    {PAY_GROUPS.flatMap(([k, ids]) => ids.map((id) =>
  • {methodName(id)} ({t(`landing.${k}`)})
  • ))}
{/* Logos drift past in greyscale; hover brings back their colour and pauses the strip. */}
{[0, 1, 2, 3].flatMap((r) => PAY_GROUPS.flatMap(([k, ids]) => ids.map((id) => {methodName(id)}{t(`landing.${k}`)})))}

{t('landing.payNote')}

{t('landing.ctaTitle')}

{t('landing.ctaBody')}

); } function Home() { const t = useTranslations(); const { me, locale, nav, categories, catalogLoaded } = useApp(); const { visible } = useCatalog(); if (!catalogLoaded) return ; const mine = visible.filter((c) => owns(me, c.id)); const last = Object.values(me?.progress ?? {}).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0]; const unfinished = mine.filter((c) => courseProgress(c, me).pct < 100); const cont = (last && unfinished.find((c) => c.id === last.courseId)) || unfinished[0] || (last && mine.find((c) => c.id === last.courseId)) || mine[0]; const others = visible.filter((c) => !owns(me, c.id)); return ( <>

{t('home.hello', { name: me?.name.split(' ')[0] ?? '' })}

{cont ? : nav(`/${locale}/courses`)}>{t('landing.browse')}}>{t('home.emptyMine')}} {mine.length > 1 &&

{t('nav.myCourses')}

{mine.map((c) => )}
}

{t('home.categories')}

{categories.filter((c) => c.isActive).map((c) => )}
{others.length > 0 &&

{others.some((c) => c.isFeatured) ? t('home.featured') : t('home.new')}

{[...others.filter((c) => c.isFeatured), ...others.filter((c) => !c.isFeatured)].slice(0, 4).map((c) => )}
} ); } function ContinueCard({ c }: { c: Course }) { const t = useTranslations(); const { me, locale, nav } = useApp(); const p = courseProgress(c, me); const r = resumePoint(c, me); return (
{t('home.continue')}

{ct(c, locale).title}

{r &&

{r.index + 1}. {lessonTitle(r.lesson, locale)}

}
{t('my.lessonsDone', { done: p.done, total: p.total })} {r &&
}
); } // ---------------------------------------------------------------- catalog + search function Catalog({ categorySlug }: { categorySlug?: string }) { const t = useTranslations(); const { categories, locale, nav, catalogLoaded } = useApp(); const { visible, catName } = useCatalog(); const [q, setQ] = useState(''); const [dq, setDq] = useState(''); useEffect(() => { const id = setTimeout(() => setDq(q.trim().toLowerCase()), 300); return () => clearTimeout(id); }, [q]); const cat = categories.find((c) => c.slug === categorySlug); const list = visible.filter((c) => (!cat || c.categoryId === cat.id) && (!dq || [ ...Object.values(c.translations).map((x) => x?.title ?? ''), c.instructorName, ...Object.values(categories.find((k) => k.id === c.categoryId)?.translations ?? {}).map((x) => x?.name ?? ''), ].some((s) => s.toLowerCase().includes(dq)))); return (

{cat ? catName(cat.id) : t('catalog.title')}

{categories.filter((c) => c.isActive).map((c) => )}
{!catalogLoaded ? : list.length ? <>

{t('catalog.count', { n: list.length })}

{list.map((c) => )}
: setQ('')}>{t('catalog.all')} : undefined}>{dq ? t('catalog.empty', { q }) : t('catalog.emptyCategory')}}
); } // ---------------------------------------------------------------- course page (Logosmental structure) function CoursePage({ slug }: { slug?: string }) { const t = useTranslations(); const { courses, categories, me, locale, nav, catalogLoaded, toast, ds } = useApp(); const { catName } = useCatalog(); const [tab, setTab] = useState(null); // null: the viewer's default (curriculum once they own it) // The sticky bar repeats the buy card's button, so it only shows while that button is off screen (P1). const [ctaEl, setCtaEl] = useState(null); const [ctaInView, setCtaInView] = useState(true); // start hidden: the bar slides in once the button is known to be off screen, never flashes out on load const c = courses.find((x) => x.slug === slug); useEffect(() => { if (c) document.title = `${ct(c, locale).title} · Sirkul Makeup`; }, [c, locale]); // before the early returns: hooks must run every render useEffect(() => { if (!ctaEl || typeof IntersectionObserver === 'undefined') { setCtaInView(false); return; } // The bottom margin is the bar's own height: a button still underneath the bar doesn't count as visible. const io = new IntersectionObserver(([e]) => setCtaInView(e.isIntersecting), { rootMargin: '0px 0px -88px 0px' }); io.observe(ctaEl); return () => io.disconnect(); }, [ctaEl]); if (!catalogLoaded) return ; if (!c || !isStudentVisible(c, me)) return nav(`/${locale}/courses`)}>{t('catalog.title')}}>{t('course.notFound')}; const text = ct(c, locale); const mine = owns(me, c.id); const lessons = publishedLessons(c); const r = resumePoint(c, me); const p = courseProgress(c, me); const done = p.pct === 100; const pre = c.prerequisiteCourseId ? courses.find((x) => x.id === c.prerequisiteCourseId) : undefined; const preDone = !pre || courseProgress(pre, me).pct === 100; const preview = lessons.find((l) => l.isPreview); const previews = lessons.filter((l) => l.isPreview).length; const cat = categories.find((k) => k.id === c.categoryId); const chapters = [...c.chapters].sort((a, b) => a.sortOrder - b.sortOrder); // The hero only offers the free preview; once owned, the progress card below carries the one "continue" button (P2). const play = !mine && preview ? `/${locale}/learn/${c.slug}/${preview.id}` : null; const playLabel = mine && r ? (done ? t('course.watchAgain') : t('course.continue', { n: r.index + 1 })) : t('course.watchPreview'); const share = () => { navigator.clipboard?.writeText(location.href).then(() => toast(t('course.linkCopied')), () => { /* clipboard blocked */ }); }; const teaches = courses.filter((x) => x.instructorName === c.instructorName && isStudentVisible(x, me)).length; // No uploaded cover in the demo → a category photo stands in on the preview card. const photo = c.coverAssetId ? ds.assetUrl(c.coverAssetId) : coursePhoto(c, categories.map((k) => k.id)); // Owners come back for the curriculum, buyers for the pitch (P4). Desktop shows one tab at a time; // phones drop the tabs and stack every section in one scroll (P3). const active = tab ?? (mine ? 'content' : 'overview'); const tabs: [string, string][] = [['overview', t('course.tabOverview')], ['content', t('course.content')]]; const nextChapter = mine && r ? chapters.find((ch) => ch.lessons.some((l) => l.id === r.lesson.id))?.id : undefined; const includes: [string, ReactNode][] = [ ['globe', LOCALE_NAMES[c.instructionLocale]], ['video', t('course.lessons', { n: lessons.length })], ['clock', formatDuration(courseDuration(c))], ...(previews ? [['play', t('course.previewLessons', { n: previews })] as [string, ReactNode]] : []), ...(c.assessments?.length ? [['quiz', t('assess.title')] as [string, ReactNode]] : []), ]; const showBar = !!(mine ? r : c.prices.ETB != null && c.status === 'PUBLISHED'); const barHidden = showBar && ctaInView; return (
{c.status === 'ARCHIVED' && } {mine && {done ? t('course.completed') : t('course.owned')}}

{text.title}

{lessons.length}{t('course.lessonsLabel')} {formatDuration(courseDuration(c))}
{(text.subtitle || text.description) &&

{text.subtitle || text.description}

} {play && }
{initials(c.instructorName)} {t('course.createdBy')}{c.instructorName}{t('course.teaches', { n: teaches })} {t('course.lastUpdated')} {fmtDate(c.updatedAt)}
{showBar &&
{mine && r ? <> {p.pct}%{t('my.lessonsDone', { done: p.done, total: p.total })} : <> {formatMoney(c.prices.ETB ?? 0, 'ETB')}{t('course.lifetime')} }
}
{pre && !preDone &&
{t('course.prereq', { title: ct(pre, locale).title })}
}
{tabs.map(([k, label]) => )}
{!!text.outcomes?.length &&

{t('course.outcomes')}

    {text.outcomes.map((o, k) =>
  • {o}
  • )}
}

{t('course.content')}

{t('course.lessons', { n: lessons.length })} · {formatDuration(courseDuration(c))}

{chapters.map((ch, i) => { const ls = [...ch.lessons].sort((a, b) => a.sortOrder - b.sortOrder).filter((l) => l.isPublished); if (!ls.length) return null; const d = ls.filter((l) => isCompleted(me, l.id)).length; return (
{tr(ch.translations, locale)?.title}{d}/{ls.length} · {formatDuration(ls.reduce((s, l) => s + l.durationSec, 0))} {ls.map((l) => )}
); })} {!!c.assessments?.length &&
{t('assess.title')}{c.assessments.filter((a) => me?.assessments?.[a.id]?.passed).length}/{c.assessments.length} {c.assessments.map((a) => )}
}
{(text.description || text.audience) &&

{t('course.about')}

{text.description &&

{text.description}

} {text.audience &&

{t('course.audience')}: {text.audience}

}
}
); } function LessonRow({ c, l, current }: { c: Course; l: Lesson; current?: boolean }) { const t = useTranslations(); const { me, courses, locale, nav } = useApp(); const access = lessonAccess(c, l, me, courses); const done = isCompleted(me, l.id); const n = lessonNumber(c, l.id); const seen = !done && l.durationSec ? Math.min(100, ((me?.progress?.[l.id]?.maxPositionSec ?? 0) / l.durationSec) * 100) : 0; return ( ); } // ---------------------------------------------------------------- assessments function AssessmentRow({ c, a }: { c: Course; a: Assessment }) { const t = useTranslations(); const { me, locale, nav } = useApp(); const r = me?.assessments?.[a.id]; const ch = a.chapterId ? c.chapters.find((x) => x.id === a.chapterId) : undefined; const where = ch ? t('assess.chapter', { chapter: tr(ch.translations, locale)?.title ?? '' }) : t('assess.final'); return ( ); } function AssessmentPage({ slug, id }: { slug?: string; id?: string }) { const t = useTranslations(); const { courses, me, locale, nav, ds, write, catalogLoaded, toast } = useApp(); const c = courses.find((x) => x.slug === slug); const a = c?.assessments?.find((x) => x.id === id); const [answers, setAnswers] = useState([]); const [result, setResult] = useState(null); const [busy, setBusy] = useState(false); const top = useRef(null); if (!catalogLoaded) return ; if (!c || !a || !me) return nav(`/${locale}/courses`)}>{t('catalog.title')}}>{t('assess.notFound')}; const text = tr(a.translations, locale); const back = () => nav(`/${locale}/course/${c.slug}`); if (!owns(me, c.id)) return {ct(c, locale).title}}>{t('assess.locked')}; const prev = me.assessments?.[a.id]; const done = a.questions.filter((_, i) => answers[i] != null).length; const submit = async () => { setBusy(true); try { const r = gradeAssessment(c, a, a.questions.map((_, i) => answers[i] ?? -1), prev, new Date()); if (await write(() => ds.patchStudent(me.id, { assessments: { [a.id]: r } }))) { setResult(r); toast(t('assess.saved')); top.current?.scrollIntoView({ behavior: 'smooth' }); } } catch { /* INCOMPLETE: the button is disabled until every question is answered */ } setBusy(false); }; const retake = () => { setAnswers([]); setResult(null); top.current?.scrollIntoView({ behavior: 'smooth' }); }; const pct = result ? Math.round((result.score / result.total) * 100) : 0; return (

{text?.title}

{text?.intro &&

{text.intro}

}
{t('assess.questions', { n: a.questions.length })}·{t('assess.passMark', { pct: a.passPct })} {prev && <>·{t('assess.best', { pct: prev.bestPct })}·{t('assess.attempts', { n: prev.attempts })}}
{result && (
= a.passPct ? 'ok' : 'bad'}`} role="status">
{pct >= a.passPct ? t('assess.wellDone') : t('assess.tryAgain', { pct: a.passPct })}{t('assess.score', { score: result.score, total: result.total })} · {t('assess.best', { pct: result.bestPct })}
)}
    {a.questions.map((q, i) => { const qt = tr(q.translations, locale); if (!qt) return null; return (
  1. {i + 1}{qt.prompt}
    {qt.options.map((o, k) => { const state = !result ? '' : k === q.answer ? 'right' : answers[i] === k ? 'wrong' : ''; return ( ); })}
    {result && qt.explain &&

    {qt.explain}

    }
  2. ); })}
{!result &&
{done < a.questions.length ? t('assess.answerAll', { done, total: a.questions.length }) : ''}
}
); } // ---------------------------------------------------------------- player function Player({ slug, lessonId }: { slug?: string; lessonId?: string }) { const t = useTranslations(); const { courses, me, locale, nav, catalogLoaded, signedIn, viewer } = useApp(); const c = courses.find((x) => x.slug === slug); const lessons = c ? publishedLessons(c) : []; const lesson = lessons.find((l) => l.id === lessonId); if (!catalogLoaded) return ; if (!c || !lesson || !isStudentVisible(c, me)) return nav(`/${locale}/courses`)}>{t('catalog.title')}}>{t('course.notFound')}; const access = lessonAccess(c, lesson, signedIn ? me : null, courses); const p = courseProgress(c, me); const idx = lessons.indexOf(lesson); const next = lessons[idx + 1]; const notes = tr(lesson.translations, locale)?.description; const chapter = c.chapters.find((ch) => ch.lessons.some((l) => l.id === lesson.id)); return (
{ct(c, locale).title}
{tr(chapter?.translations, locale)?.title}

{idx + 1}. {lessonTitle(lesson, locale)}

{access.ok ? : (

{t(`player.${access.reason}`)}

{access.reason === 'COURSE_NOT_OWNED' && } {access.reason === 'LESSON_LOCKED' && idx > 0 && } {access.reason === 'PREREQUISITE_REQUIRED' && } {access.reason === 'ACCOUNT_DEACTIVATED' && }
)}

{t('player.notes')}

{notes || ct(c, locale).subtitle || ct(c, locale).description}

{viewer && !viewer.id &&

{t('auth.noIdentity')}

}
); } function VideoPanel({ c, lesson, next }: { c: Course; lesson: Lesson; next?: Lesson }) { const t = useTranslations(); const { me, locale, nav, ds, write, signedIn, viewer } = useApp(); const vimeo = !lesson.videoAssetId; // no upload yet: play the Vimeo placeholder instead const [vdur, setVdur] = useState(0); const dur = (vimeo && vdur) || lesson.durationSec || 1; const saved = me?.progress?.[lesson.id]; const [pos, setPos] = useState(() => (saved && !saved.completedAt ? Math.min(saved.positionSec, dur - 5) : 0)); const [playing, setPlaying] = useState(false); const [rate, setRate] = useState(1); const conn = typeof navigator !== 'undefined' ? (navigator as any).connection : undefined; const [saver, setSaver] = useState(() => !!conn && (conn.saveData || /2g|3g/.test(conn.effectiveType ?? ''))); const [quality, setQuality] = useState('auto'); const [justDone, setJustDone] = useState(false); const videoRef = useRef(null); const frameRef = useRef(null); const screenRef = useRef(null); const posRef = useRef(pos); posRef.current = pos; const sentAt = useRef(pos); // position at last heartbeat, for watch-time accounting const meRef = useRef(me); meRef.current = me; const canSave = signedIn && !!me; const heartbeat = useCallback(() => { const s = meRef.current; if (!canSave || !s) return; const now = new Date().toISOString(); const position = Math.floor(posRef.current); const prev = s.progress?.[lesson.id]; const hb = applyHeartbeat(prev, c.id, position, dur, now); const delta = Math.max(0, position - sentAt.current); sentAt.current = position; if (prev && prev.positionSec === hb.positionSec && prev.completedAt === hb.completedAt && !delta) return; // only write on change const ym = now.slice(0, 7); if (hb.completedAt && !prev?.completedAt) setJustDone(true); write(() => ds.patchStudent(s.id, { progress: { [lesson.id]: hb }, lastActiveAt: now, watchSec: { [ym]: (s.watchSec?.[ym] ?? 0) + Math.min(delta, 60) } })); }, [canSave, c.id, dur, lesson.id, ds, write]); // Vimeo placeholder, driven over the player's postMessage API so progress and heartbeats still work const vcall = (method: string, value?: unknown) => frameRef.current?.contentWindow?.postMessage(JSON.stringify(value === undefined ? { method } : { method, value }), VIMEO_ORIGIN); const vlisten = () => { ['timeupdate', 'play', 'pause', 'ended'].forEach((ev) => vcall('addEventListener', ev)); vcall('getDuration'); if (posRef.current) vcall('setCurrentTime', posRef.current); }; useEffect(() => { if (!vimeo) return; const on = (e: MessageEvent) => { if (e.origin !== VIMEO_ORIGIN || e.source !== frameRef.current?.contentWindow) return; let m: any; try { m = typeof e.data === 'string' ? JSON.parse(e.data) : e.data; } catch { return; } if (m.event === 'ready') vlisten(); else if (m.event === 'timeupdate') { setPos(m.data.seconds); if (m.data.duration) setVdur(m.data.duration); } else if (m.event === 'play') setPlaying(true); else if (m.event === 'pause' || m.event === 'ended') setPlaying(false); else if (m.method === 'getDuration' && m.value) setVdur(m.value); }; addEventListener('message', on); return () => removeEventListener('message', on); }, [vimeo]); // heartbeat every 15 s while playing, and on pause / leave (§5.8) useEffect(() => { if (!playing) { heartbeat(); return; } const id = setInterval(heartbeat, 15000); return () => clearInterval(id); }, [playing, heartbeat]); useEffect(() => { const vis = () => document.visibilityState === 'hidden' && heartbeat(); addEventListener('visibilitychange', vis); addEventListener('pagehide', heartbeat); return () => { removeEventListener('visibilitychange', vis); removeEventListener('pagehide', heartbeat); heartbeat(); }; }, [heartbeat]); useEffect(() => { const v = videoRef.current; if (v) v.playbackRate = rate; }, [rate]); useEffect(() => { if (vimeo && rate !== 1) vcall('setPlaybackRate', rate); }, [rate]); const toggle = () => { const v = videoRef.current; if (v) { v.paused ? v.play().catch(() => setPlaying(false)) : v.pause(); return; } vcall(playing ? 'pause' : 'play'); }; const seek = (to: number) => { const n = Math.max(0, Math.min(dur, to)); setPos(n); if (videoRef.current) videoRef.current.currentTime = n; else vcall('setCurrentTime', n); }; const full = () => { screenRef.current?.requestFullscreen?.().catch(() => { /* not allowed in this frame */ }); }; const onKey = (e: React.KeyboardEvent) => { if ((e.target as HTMLElement).tagName === 'SELECT' || (e.target as HTMLElement).tagName === 'INPUT') return; if (e.key === ' ') { e.preventDefault(); toggle(); } else if (e.key === 'ArrowLeft') seek(pos - 10); else if (e.key === 'ArrowRight') seek(pos + 10); else if (e.key === 'f') full(); else if (e.key === 'm' && videoRef.current) videoRef.current.muted = !videoRef.current.muted; }; const mark = (me?.phone || me?.email || viewer?.name || 'student').replace(/^(.{3}).*(.{2})$/, '$1•••$2'); const done = isCompleted(me, lesson.id) || justDone; const pct = courseProgress(c, me).pct; return (
{lesson.videoAssetId ? (