RezinaLMS-CustomerEnd/packages/features/src/student.tsx
n3p-tun3 d92180542b fix(api): time out and retry when the API server drops connections
About a third of new connections to api.rezina.yaltopia.com never complete (the TCP
connect hangs; requests that do connect answer in ~0.5s). With no timeout, sign-in sat
on a busy button forever.

- every API call gives up after 12s
- calls that are safe to repeat retry twice: reads, the account lookup, password login;
  sending or verifying a code never retries, so nobody gets two texts or burns a code
- the catalog keeps at most 3 requests in flight instead of firing one per course at once
- sign-in shows "Couldn't reach the server. Check your connection and try again."
  (auth.networkError, om/ti drafts) instead of hanging
2026-11-02 19:29:37 +03:00

1686 lines
118 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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 }) => <span className="pay-mark"><img src={PAY_LOGOS[id]} alt="" /></span>;
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 ?? '';
/** Length as text, or '' when unknown (the API carries no durations yet), so no screen shows "0 min". */
const dur = (sec: number) => (sec > 0 ? formatDuration(sec) : '');
const withDur = (sec: number, before = ' · ') => (sec > 0 ? `${before}${formatDuration(sec)}` : '');
const lessonNumber = (c: Course, id: string) => publishedLessons(c).findIndex((l) => l.id === id) + 1;
// C1: one quiet "lessons · length" line, with "new course" / student count as a tag on the photo.
// C2: the whole card is the target, so the footer is just the price. C3: owned cards say what's next.
// `tall` keeps the photo-on-top layout on phones too (the home Featured rail, C4).
function CourseCard({ c, tall }: { c: Course; tall?: boolean }) {
const { locale, nav, me, signedIn } = useApp();
const t = useTranslations();
const { catName } = useCatalog();
const p = courseProgress(c, me);
const mine = signedIn && owns(me, c.id);
const r = mine ? resumePoint(c, me) : null;
const tag = c.enrolledCount ? t('course.enrolled', { n: c.enrolledCount }) : t('course.newCourse');
return (
<button className={`ccard${tall ? ' ccard-tall' : ''}`} onClick={() => nav(`/${locale}/course/${c.slug}`)}>
<Cover course={c} locale={locale} badge={<>{catName(c.categoryId) && <span className="pill">{catName(c.categoryId)}</span>}{!mine && <span className="ccard-tag">{tag}</span>}</>} />
<div className="ccard-body">
<h3>{ct(c, locale).title}</h3>
<span className="meta num">{t('course.lessons', { n: p.total })}{withDur(courseDuration(c))}</span>
{c.instructorName && <span className="ccard-by">{t('course.by', { name: c.instructorName })}</span>}
{(mine || c.prices.ETB != null) && <div className="ccard-foot">
{mine ? <>
{r && <span className="ccard-next">{p.pct === 100 ? <b>{t('course.completed')}</b> : <><b>{t('player.upNext')}</b> {r.index + 1}. {lessonTitle(r.lesson, locale)}<span className="num">{withDur(r.lesson.durationSec)}</span></>}</span>}
<span className="ccard-prog"><span className="bar grow" aria-label={`${p.pct}%`}><i style={{ width: `${p.pct}%` }} /></span><span className="small num">{p.pct}%</span></span>
</> : <strong className="num">{formatMoney(c.prices.ETB!, 'ETB')}</strong>}
</div>}
</div>
</button>
);
}
function SignInGate({ children }: { children: ReactNode }) {
const { signedIn, meLoaded, ready } = useApp();
if (!ready || !meLoaded) return <Skeleton h={160} n={2} />;
return signedIn ? <>{children}</> : <SignIn />;
}
// ---------------------------------------------------------------- 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<HTMLElement>(null);
const sheet = useRef<HTMLDialogElement>(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);
const focus = section === 'learn'; // L1: watching a lesson drops the site links and the marketing footer
return (
<div lang={locale} className={focus ? 's-focus' : undefined}>
<header className={`s-top${scrolled ? ' scrolled' : ''}`}>
<div className="s-top-in">
<button className="brand" onClick={() => go('')} aria-label={settings.brandName}><Logo size={36} /><Logo size={36} mark /></button>
<nav className="s-nav" aria-label="Main">
{links.map(([p, , label]) => <button key={p} data-tour={p} aria-current={current(p)} onClick={() => go(p ? '/' + p : '')}>{label}</button>)}
</nav>
<div className="s-actions">
{signedIn ? <>
<button className="icon-btn" aria-label={`${t('nav.notifications')}${unread ? ` (${unread})` : ''}`} onClick={() => go('/notifications')}><Icon name="bell" />{unread > 0 && <span className="dot">{unread}</span>}</button>
<UserMenu />
</> : <>
<button className="btn btn-accent btn-sm" onClick={() => go('/signin')}>{t('nav.getStarted')}</button>
</>}
<button className="icon-btn menu-btn" aria-label={t('nav.menu')} aria-haspopup="dialog" onClick={() => sheet.current?.showModal()}><Icon name="menu" size={22} /></button>
</div>
</div>
</header>
{/* Menu sheet: the main links set large, then the preferences that used to crowd the header. */}
<dialog ref={sheet} className="sheet" aria-label={t('nav.menu')} onClick={(e) => { if (e.target === sheet.current) closeSheet(); }}>
<div className="sheet-in">
<div className="sheet-top"><Logo size={30} /><button className="icon-btn" aria-label={t('common.close')} onClick={closeSheet}><Icon name="x" size={22} /></button></div>
<nav className="sheet-nav" aria-label="Main">
{tabs.filter(([p]) => signedIn || (p !== 'my' && p !== 'profile')).map(([p, , label], k) => <button key={p} aria-current={current(p)} onClick={() => { closeSheet(); go(p ? '/' + p : ''); }}><span className="num">{String(k + 1).padStart(2, '0')}</span>{label}</button>)}
{signedIn && <button aria-current={section === 'history' ? 'page' : undefined} onClick={() => { closeSheet(); go('/history'); }}><span className="num">{String(tabs.length + 1).padStart(2, '0')}</span>{t('nav.history')}</button>}
</nav>
<div className="sheet-prefs">
{signedIn && <div className="sheet-row"><span>{t('tour.again')}</span><button className="icon-btn" aria-label={t('tour.again')} onClick={() => { closeSheet(); setTouring(true); }}><Icon name="sparkle" size={20} /></button></div>}
<div className="sheet-row"><span>{t('common.theme')}</span><ThemeToggle label={t('common.theme')} /></div>
<div className="sheet-row"><span>{t('common.language')}</span><LangPick /></div>
<div className="sheet-row" onClickCapture={closeSheet}><span>{t('common.feedback')}</span><FeedbackButton label={t('common.feedback')} target={() => mainRef.current} /></div>
</div>
<p className="sheet-foot"><a href={settings.telegramLink} target="_blank" rel="noreferrer">{t('help.telegram')}</a><span className="num">{settings.supportPhone}</span></p>
</div>
</dialog>
<LangWelcome onDone={maybeTour} />
{touring && <Tour onDone={endTour} />}
<main className="s-main" ref={mainRef}>
{settings.maintenanceBanner && <div className="banner small" role="status">{settings.maintenanceBanner}</div>}
<StudentRoutes />
</main>
{!focus && <Footer />}
{signedIn && section !== 'learn' && section !== 'course' && <nav className="s-tabs" aria-label="Main">
{tabs.map(([p, icon, label]) => <button key={p} data-tour={p} aria-current={current(p)} onClick={() => go(p ? '/' + p : '')}><Icon name={icon} size={22} />{label}</button>)}
</nav>}
</div>
);
}
function LangPick() {
const t = useTranslations();
const { locale, setLocale } = useApp();
return (
<label className="lang-pick" title={t('common.language')}><Icon name="globe" size={16} /><span className="sr-only">{t('common.language')}</span>
<select value={locale} onChange={(e) => setLocale(e.target.value as Locale)}>
{LOCALES.map((l) => <option key={l} value={l}>{LOCALE_NAMES[l]}{(DRAFT_LOCALES as readonly string[]).includes(l) ? ' (draft)' : ''}</option>)}
</select>
</label>
);
}
// 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<DOMRect | null>(null);
const [key, sel] = TOUR[i];
const last = i === TOUR.length - 1;
useEffect(() => {
const el = sel ? [...document.querySelectorAll<HTMLElement>(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 (
<div className="tour" role="dialog" aria-modal="true" aria-labelledby="tour-h">
{rect ? <div className="tour-ring" style={{ top: rect.top - pad, left: rect.left - pad, width: rect.width + pad * 2, height: rect.height + pad * 2 }} /> : <div className="tour-dim" />}
<div className={`tour-card ${rect ? (below ? 'at-bottom' : 'at-top') : 'at-center'}`} key={i}>
<div className="tour-dots" aria-hidden>{TOUR.map((_, k) => <i key={k} className={k === i ? 'on' : ''} />)}</div>
<span className="sr-only">{i + 1} / {TOUR.length}</span>
<h2 id="tour-h">{t(`tour.${key}T`, { name: me?.name.split(' ')[0] ?? '' })}</h2>
<p>{t(`tour.${key}`)}</p>
<div className="tour-actions">
{!last && <button className="link" onClick={onDone}>{t('tour.skip')}</button>}
<span className="grow" />
{i > 0 && <button className="btn btn-ghost btn-sm" onClick={() => setI(i - 1)}>{t('common.back')}</button>}
<button className="btn btn-accent btn-sm" autoFocus onClick={() => (last ? onDone() : setI(i + 1))}>{last ? t('tour.done') : t('tour.next')}</button>
</div>
</div>
</div>
);
}
// First visit: ask for a language before anything else. Shown in every language, since we don't know theirs yet.
const LANG_PROMPT: Record<string, string> = { en: 'Choose your language', am: 'ቋንቋ ይምረጡ', om: 'Afaan filadhu', ti: 'ቋንቋ ምረጽ' };
function LangWelcome({ onDone }: { onDone(): void }) {
const { locale, setLocale } = useApp();
const ref = useRef<HTMLDialogElement>(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 (
<dialog ref={ref} className="lang-welcome" aria-labelledby="lw-h" onCancel={() => pick(locale)}>
<img src="/photos/habesha-bride.jpg" alt="" />
<div className="lw-body">
<Logo size={30} />
<div><h2 id="lw-h" lang="en">{LANG_PROMPT.en}</h2><p>{LOCALES.filter((l) => l !== 'en').map((l) => <span key={l} lang={l}>{LANG_PROMPT[l]}</span>)}</p></div>
<div className="lw-list">{LOCALES.map((l) => <button key={l} lang={l} aria-current={l === locale} autoFocus={l === locale} onClick={() => pick(l)}><span>{LOCALE_NAMES[l]}</span><Icon name="chevron" size={18} /></button>)}</div>
</div>
</dialog>
);
}
// 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 <button className="icon-btn" aria-pressed={dark} aria-label={label} title={label} onClick={flip}><Icon name={dark ? 'sun' : 'moon'} size={20} /></button>;
}
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<HTMLDetailsElement>(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 (
<details className="menu" ref={ref}>
<summary data-tour="profile" className="avatar" aria-label={t('nav.account')}>{viewer?.avatarUrl ? <img src={viewer.avatarUrl} alt="" /> : initials(name)}</summary>
<div className="menu-pop">
<div className="menu-head"><strong>{name}</strong>{(me?.phone || me?.email) && <span className="small muted">{me?.phone || me?.email}</span>}</div>
<button onClick={() => go(`/${locale}/profile`)}><Icon name="user" size={16} />{t('nav.profile')}</button>
<button onClick={() => go(`/${locale}/history`)}><Icon name="clock" size={16} />{t('nav.history')}</button>
<button onClick={() => go(`/${locale}/help`)}><Icon name="help" size={16} />{t('nav.help')}</button>
<button onClick={() => { signOut(); go(`/${locale}/signin`); }}><Icon name="logout" size={16} />{t('nav.signOut')}</button>
</div>
</details>
);
}
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 = <LangPick />;
const go = (p: string) => nav(`/${locale}${p}`);
const kit: [string, string][] = [['foundation', 'kit1'], ['brush', 'kit2'], ['brow', 'kit3'], ['lipstick', 'kit4']];
return (
<footer className="foot foot-full">
<div className="foot-card">
<div className="foot-brand">
<h2 className="foot-word"><Logo size={64} /><span className="foot-icon"><KitIcon name="brush" size={56} /></span><span className="sr-only">{settings.brandName}</span></h2>
<p className="foot-tag">{t('footer.tagline')}</p>
<p className="foot-founder">{t.rich('footer.founder', { name: () => <a href="https://www.tiktok.com/@rezinabrhane" target="_blank" rel="noreferrer">Rezina Brhane</a> })}</p>
<div className="foot-contact">
<span className="foot-chip">{t('footer.contact')}</span>
<a href={settings.telegramLink} target="_blank" rel="noreferrer">{t('help.telegram')}</a>
<span className="num">{settings.supportPhone}</span>
{settings.supportEmail && <a href={`mailto:${settings.supportEmail}`}>{settings.supportEmail}</a>}
<a href="https://www.tiktok.com/@rezinabrhane" target="_blank" rel="noreferrer">{t('footer.tiktok')}</a>
</div>
</div>
<nav className="foot-cols" aria-label="Footer">
<div><h3>{t('nav.courses')}</h3>{categories.filter((c) => c.isActive).map((c) => <button key={c.id} onClick={() => go(`/courses/${c.slug}`)}>{tr(c.translations, locale)?.name}</button>)}</div>
<div><h3>{t('footer.learn')}</h3>
<button onClick={() => go('/courses')}>{t('catalog.title')}</button>
{signedIn && <button onClick={() => go('/history')}>{t('nav.history')}</button>}
<button onClick={() => go('/help')}>{t('nav.help')}</button>
<a href="/waitlist">{t('footer.waitlist')}</a>
</div>
<div><h3>{t('common.language')}</h3>{langs}</div>
</nav>
<aside className="kit-card" aria-label={t('footer.kitTitle')}>
<div className="kit-top">
<div className="kit-cover" aria-hidden>{['habesha-harari.jpg', 'glam.jpg', 'skin.jpg', 'habesha-bride.jpg'].map((f) => <img key={f} src={`/photos/${f}`} alt="" loading="lazy" />)}</div>
<div className="kit-head">
<span className="kit-badge"><KitIcon name="mirror" size={16} /></span>
<h3>{t('footer.kitTitle')}</h3>
<p>{t('footer.kitSub')}</p>
</div>
<span className="kit-tag">{t('footer.kitCount', { n: kit.length })}</span>
<button className="kit-go" onClick={() => go('/courses')} aria-label={t('landing.browse')}><Icon name="chevron" size={22} /></button>
</div>
<ol className="kit-list">{kit.map(([icon, k], n) => (
<li key={k}><span className="kit-n num">{n + 1}</span><span className="kit-item"><strong>{t(`footer.${k}`)}</strong><span>{t(`footer.${k}Note`)}</span></span><KitIcon name={icon} size={22} /></li>
))}</ol>
</aside>
</div>
<div className="foot-strip">
<p className="foot-bubble"><strong>{t('footer.workTitle')}</strong><span>{t('footer.workSub')}</span></p>
{/* ponytail: placeholder shots until real student work exists; swap WORK_PHOTOS for their uploads. */}
<div className="foot-reel" aria-hidden><div>{[...WORK_PHOTOS, ...WORK_PHOTOS].map((f, k) => <img key={k} src={`/photos/${f}`} alt="" loading="lazy" />)}</div></div>
</div>
<div className="foot-bar">
<span>© {new Date().getFullYear()} {settings.brandName} · {t('footer.rights')}</span>
<details className="foot-credits"><summary>{t('footer.credits')}</summary>
<p>{PHOTO_CREDITS.map(([who, lic, url], k) => <span key={url}>{k > 0 && ' · '}<a href={url} target="_blank" rel="noreferrer">{who}</a> ({lic})</span>)} · Wikimedia Commons, Pexels. Icons: IconPark (Apache-2.0).</p>
</details>
</div>
<p className="powered">{t.rich('footer.poweredBy', { name: () => <a className="shine" href="https://yaltopia.com" target="_blank" rel="noreferrer">Yaltopia Tech</a> })}</p>
</footer>
);
}
function StudentRoutes() {
const { route, signedIn } = useApp();
const [, s, a, b] = route;
switch (s) {
case undefined: return signedIn ? <Home /> : <Landing />;
case 'courses': return <Catalog categorySlug={a} />;
case 'course': return <CoursePage slug={a} />;
case 'learn': return <Player slug={a} lessonId={b} />;
case 'assess': return <SignInGate><AssessmentPage slug={a} id={b} /></SignInGate>;
case 'checkout': return <SignInGate><Checkout slug={a} /></SignInGate>;
case 'pay': return <SignInGate><ProviderSim orderId={a} /></SignInGate>;
case 'orders': return <SignInGate><OrderStatusPage orderId={a} /></SignInGate>;
case 'my': return <SignInGate><MyCourses /></SignInGate>;
case 'progress': return <SignInGate><Profile /></SignInGate>; // progress lives on the profile
case 'history': return <SignInGate><History /></SignInGate>;
case 'notifications': return <SignInGate><Inbox /></SignInGate>;
case 'help': return <Help />;
case 'profile': return <SignInGate><Profile /></SignInGate>;
case 'signin': return !signedIn ? <SignIn /> : <Home />;
default: return <Landing />;
}
}
// ---------------------------------------------------------------- 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 (
<a className="live-pill" href="/waitlist">
<span className="faces" aria-hidden>{FACES.map((f, k) => <img key={f} src={`/photos/${f}`} alt="" className={k === i ? 'on' : undefined} />)}</span>
<span className="live-dot" aria-hidden />
<span>{label}</span>
<Icon name="chevron" size={14} />
</a>
);
}
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 (
<div className="landing">
<section className="l-hero">
<div className="reel" aria-hidden><div className="reel-track">{[...HERO_PHOTOS, ...HERO_PHOTOS].map((p, i) => <img key={i} src={`/photos/${p}`} alt="" />)}</div></div>
<div className="hero-copy">
<WaitPill label={t('landing.waitPill')} />
<h1>{t('landing.title')}</h1>
<p className="lead">{t('landing.lead')}</p>
<div className="row hero-ctas">
<button className="btn btn-accent btn-lg" onClick={() => nav(`/${locale}/courses`)}>{t('landing.browse')}<Icon name="chevron" size={16} /></button>
{lead && <button className="btn btn-ghost btn-lg" onClick={watch}><span className="play-dot"><Icon name="play" size={12} /></span>{t('course.watchPreview')}</button>}
</div>
<ul className="facts">{['fact2', 'fact3'].map((k) => <li key={k}><Icon name="check" size={16} />{t(`landing.${k}`)}</li>)}</ul>
</div>
</section>
{cats.length > 0 && <section className="stack-lg">
<div className="section-h"><div className="stack-sm"><h2>{t('landing.catTitle')}</h2><p className="muted">{t('landing.catLead')}</p></div></div>
<div className="look-grid">{cats.map((c, i) => (
<button key={c.id} className="look" onClick={() => nav(`/${locale}/courses/${c.slug}`)}>
<img src={`/photos/${CAT_PHOTOS[i % CAT_PHOTOS.length]}`} alt="" loading="lazy" />
<span className="look-copy"><strong>{tr(c.translations, locale)?.name}</strong><span>{t('catalog.count', { n: visible.filter((x) => x.categoryId === c.id).length })}</span></span>
<span className="look-go" aria-hidden><Icon name="chevron" size={16} /></span>
</button>
))}</div>
</section>}
<section className="stack-lg">
<div className="section-h"><div className="stack-sm"><h2>{t('landing.featured')}</h2><p className="muted">{t('landing.featuredLead')}{Number.isFinite(minPrice) && <> · <span className="num">{t('landing.from', { price: formatMoney(minPrice, 'ETB') })}</span></>}</p></div>
<button className="btn btn-ghost btn-sm" onClick={() => nav(`/${locale}/courses`)}>{t('landing.viewAll')}</button></div>
{!catalogLoaded ? <Skeleton h={220} /> : featured.length ? <div className="grid-cards">{featured.map((c) => <CourseCard key={c.id} c={c} />)}</div> : <Empty>{t('catalog.emptyCategory')}</Empty>}
</section>
<section className="stack-lg">
<div className="section-h"><div className="stack-sm"><h2>{t('landing.howTitle')}</h2><p className="muted">{t('landing.payLead')}{Number.isFinite(minPrice) && <> <strong className="num">{t('landing.from', { price: formatMoney(minPrice, 'ETB') })}</strong></>}</p></div></div>
<ol className="steps3">
{/* Abstract art per step (CSS only): preview rings, a stack of cards, an unlocking arc. */}
{(['play', 'cart', 'lock'] as const).map((icon, k) => <li key={icon} className={`step step-${k + 1}`}><span className="step-art" aria-hidden><span className="step-glyph"><Icon name={icon} size={26} /></span></span><strong>{t(`landing.how${k + 1}`)}</strong></li>)}
</ol>
<div className="pay-strip">
<h3>{t('landing.payTitle')}</h3>
<ul className="sr-only">{PAY_GROUPS.flatMap(([k, ids]) => ids.map((id) => <li key={id}>{methodName(id)} ({t(`landing.${k}`)})</li>))}</ul>
{/* Logos drift past in greyscale; hover brings back their colour and pauses the strip. */}
<div className="pay-marquee" aria-hidden><div>{[0, 1, 2, 3].flatMap((r) => PAY_GROUPS.flatMap(([k, ids]) => ids.map((id) => <span key={`${r}-${id}`} className="pay-item"><PayLogo id={id} /><span><strong>{methodName(id)}</strong><small>{t(`landing.${k}`)}</small></span></span>)))}</div></div>
<p className="cd-note"><Icon name="lock" size={14} />{t('landing.payNote')}</p>
</div>
</section>
<section className="cta-photo">
<img src="/photos/habesha-tigray.jpg" alt="" loading="lazy" />
<div className="stack-sm"><h2>{t('landing.ctaTitle')}</h2><p>{t('landing.ctaBody')}</p></div>
<button className="btn btn-accent btn-lg" onClick={lead ? watch : () => nav(`/${locale}/courses`)}><Icon name="play" size={16} />{t('course.watchPreview')}</button>
</section>
</div>
);
}
function Home() {
const t = useTranslations();
const { me, locale, nav, categories, catalogLoaded } = useApp();
const { visible } = useCatalog();
if (!catalogLoaded) return <Skeleton h={200} n={2} />;
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 (
<>
<div className="home-top">
<h1 style={{ fontSize: 'var(--fs-2xl)' }}>{t('home.hello', { name: me?.name.split(' ')[0] ?? '' })}</h1>
{cont ? <ContinueCard c={cont} /> : <Empty action={<button className="btn" onClick={() => nav(`/${locale}/courses`)}>{t('landing.browse')}</button>}>{t('home.emptyMine')}</Empty>}
</div>
{mine.length > 1 && <section className="stack"><div className="section-h"><h2>{t('nav.myCourses')}</h2><button className="link" onClick={() => nav(`/${locale}/my`)}>{t('my.viewProgress')}</button></div><div className="grid-cards">{mine.map((c) => <CourseCard key={c.id} c={c} />)}</div></section>}
<section className="stack">
<div className="section-h"><h2>{t('home.categories')}</h2></div>
<div className="chips">{categories.filter((c) => c.isActive).map((c) => <button key={c.id} className="chip" onClick={() => nav(`/${locale}/courses/${c.slug}`)}>{tr(c.translations, locale)?.name}</button>)}</div>
</section>
{others.length > 0 && <section className="stack"><div className="section-h"><h2>{others.some((c) => c.isFeatured) ? t('home.featured') : t('home.new')}</h2><button className="link" onClick={() => nav(`/${locale}/courses`)}>{t('catalog.title')}</button></div><div className="rail">{[...others.filter((c) => c.isFeatured), ...others.filter((c) => !c.isFeatured)].slice(0, 4).map((c) => <CourseCard key={c.id} c={c} tall />)}</div></section>}
</>
);
}
// H1/H2: a short photo header carries the course and its progress; the body leads with the next lesson and how long
// it takes, with the button at the bottom where a thumb reaches it.
function ContinueCard({ c }: { c: Course }) {
const t = useTranslations();
const { me, locale, nav, ds, categories } = useApp();
const p = courseProgress(c, me);
const r = resumePoint(c, me);
const finished = p.pct === 100;
const photo = c.coverAssetId ? ds.assetUrl(c.coverAssetId) : coursePhoto(c, categories.map((k) => k.id));
return (
<section className="continue" aria-label={t('home.continue')}>
<div className="continue-media">
<img src={photo} alt="" />
<span className="continue-kicker">{t('home.continue')}</span>
<h2>{ct(c, locale).title}</h2>
<span className="continue-bar" role="progressbar" aria-valuenow={p.pct} aria-valuemin={0} aria-valuemax={100} aria-label={t('my.lessonsDone', { done: p.done, total: p.total })}><i style={{ width: `${p.pct}%` }} /></span>
</div>
<div className="continue-body">
{r && <p className="continue-next">
<span>{finished ? t('course.completed') : t('player.upNext')}</span>
<strong>{r.index + 1}. {lessonTitle(r.lesson, locale)}</strong>
<span className="num">{[dur(r.lesson.durationSec), t('my.lessonsDone', { done: p.done, total: p.total })].filter(Boolean).join(' · ')}</span>
</p>}
{r && <button className="btn btn-accent btn-lg" onClick={() => nav(`/${locale}/learn/${c.slug}/${r.lesson.id}`)}><Icon name="play" size={16} />{finished ? t('course.watchAgain') : t('course.continue', { n: r.index + 1 })}</button>}
</div>
</section>
);
}
// ---------------------------------------------------------------- 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 [lang, setLang] = useState(''); // '' = any language the course is taught in (CT3)
const searchRef = useRef<HTMLInputElement>(null);
const dq = q.trim().toLowerCase(); // the list is in memory: filter on every keystroke, no debounce (CT2)
const cat = categories.find((c) => c.slug === categorySlug);
const langs = [...new Set(visible.map((c) => c.instructionLocale))];
const list = visible.filter((c) => (!cat || c.categoryId === cat.id) && (!lang || c.instructionLocale === lang) && (!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))));
const clear = () => { setQ(''); searchRef.current?.focus(); };
return (
<section className="stack">
<h1 style={{ fontSize: 'var(--fs-2xl)' }}>{cat ? catName(cat.id) : t('catalog.title')}</h1>
<label className="search">
<span className="sr-only">{t('catalog.search')}</span>
<Icon name="search" size={18} />
<input ref={searchRef} id="search" className="input" type="search" placeholder={t('catalog.search')} value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => { if (e.key === 'Escape' && q) clear(); }} />
{q && <button type="button" className="search-clear" onClick={clear} aria-label={t('catalog.clearSearch')}><Icon name="x" size={16} /></button>}
</label>
<div className="chips" role="group">
<button className="chip" aria-pressed={!cat} onClick={() => nav(`/${locale}/courses`)}>{t('catalog.all')}</button>
{categories.filter((c) => c.isActive).map((c) => <button key={c.id} className="chip" aria-pressed={cat?.id === c.id} onClick={() => nav(`/${locale}/courses/${c.slug}`)}>{tr(c.translations, locale)?.name}</button>)}
</div>
{!catalogLoaded ? <Skeleton h={220} n={2} /> : <>
<div className="catalog-bar">
<p className="muted small" aria-live="polite">{t('catalog.count', { n: list.length })}</p>
{langs.length > 1 && <label className="catalog-lang">
<span>{t('catalog.taughtIn')}</span>
<select id="catalog-lang" value={lang} onChange={(e) => setLang(e.target.value)}>
<option value="">{t('catalog.anyLanguage')}</option>
{langs.map((l) => <option key={l} value={l}>{LOCALE_NAMES[l]}</option>)}
</select>
</label>}
</div>
{list.length ? <div className="grid-cards">{list.map((c) => <CourseCard key={c.id} c={c} />)}</div>
: <Empty action={dq || lang ? <button className="btn btn-ghost" onClick={() => { setQ(''); setLang(''); }}>{t('catalog.clearFilters')}</button> : undefined}>{dq ? t('catalog.empty', { q }) : lang ? t('catalog.emptyLanguage') : t('catalog.emptyCategory')}</Empty>}
</>}
</section>
);
}
// ---------------------------------------------------------------- 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<string | null>(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<HTMLDivElement | null>(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 <Skeleton h={260} n={2} />;
if (!c || !isStudentVisible(c, me)) return <Empty action={<button className="btn" onClick={() => nav(`/${locale}/courses`)}>{t('catalog.title')}</button>}>{t('course.notFound')}</Empty>;
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 && !(c.prices.ETB == null && lessons.every((l) => l.isPreview)) ? `/${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 quizzes = c.assessments ?? [];
const finalQuizzes = quizzes.filter((a) => !a.chapterId || !chapters.some((ch) => ch.id === a.chapterId && ch.lessons.some((l) => l.isPublished)));
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 })],
...(courseDuration(c) ? [['clock', formatDuration(courseDuration(c))] as [string, ReactNode]] : []),
...(previews ? [['play', t('course.previewLessons', { n: previews })] as [string, ReactNode]] : []),
...(c.assessments?.length ? [['quiz', t('assess.title')] as [string, ReactNode]] : []),
];
const free = !mine && c.prices.ETB == null && lessons.length > 0 && lessons.every((l) => l.isPreview);
const showBar = !!(mine ? r : c.prices.ETB != null && c.status === 'PUBLISHED');
const barHidden = showBar && ctaInView;
return (
<div className="cd">
<section className="cd-head">
<img className="cd-hero-img" src={photo} alt="" />
<div className="cd-top">
<nav className="crumbs" aria-label="Breadcrumb">
<button onClick={() => nav(`/${locale}/courses`)}>{t('nav.courses')}</button>
{cat && <><span aria-hidden>/</span><button onClick={() => nav(`/${locale}/courses/${cat.slug}`)}>{catName(cat.id)}</button></>}
<span aria-hidden>/</span><span aria-current="page">{text.title}</span>
</nav>
<span className="row" style={{ gap: 6 }}>
{c.status === 'ARCHIVED' && <StatusPill status="ARCHIVED" />}
<button className="cd-share" onClick={share} aria-label={t('course.share')}><Icon name="share" size={16} /></button>
</span>
</div>
<h1>{text.title}</h1>
<div className="cd-stats">
<span className="cd-pill"><Icon name="video" size={14} /><strong className="num">{lessons.length}</strong>{t('course.lessonsLabel')}</span>
{courseDuration(c) > 0 && <span className="cd-pill"><Icon name="clock" size={14} /><strong className="num">{formatDuration(courseDuration(c))}</strong></span>}
{mine && <span className="cd-pill cd-pill-own"><Icon name="check" size={14} /><strong>{done ? t('course.completed') : t('course.owned')}</strong></span>}
</div>
{(text.subtitle || text.description) && <p className="cd-lead">{text.subtitle || text.description}</p>}
{play && <button className="cd-hero-play" onClick={() => nav(play)}><span className="play-dot"><Icon name="play" size={12} /></span>{playLabel}</button>}
{c.instructorName && <div className="cd-by">
<span className="avatar" aria-hidden>{initials(c.instructorName)}</span>
<span className="cd-by-txt"><em>{t('course.createdBy')}</em><strong>{c.instructorName}</strong><span className="cd-by-n">{t('course.teaches', { n: teaches })}</span></span>
</div>}
</section>
<aside className="cd-side">
<div className="cd-buy">
{mine ? <>
<div className="row-between"><strong>{done ? t('course.completed') : t('course.owned')}</strong><span className="small num">{p.pct}%</span></div>
<div className="bar"><i style={{ width: `${p.pct}%` }} /></div>
<span className="small muted num">{t('my.lessonsDone', { done: p.done, total: p.total })}</span>
{pre && !preDone && <p className="cd-prereq"><Icon name="lock" size={14} /><span>{t('course.prereq', { title: ct(pre, locale).title })} <button className="link" onClick={() => nav(`/${locale}/course/${pre.slug}`)}>{t('course.prereqLink', { title: ct(pre, locale).title })}</button></span></p>}
{r && !done && <p className="cd-next"><span>{t('player.upNext')}</span><strong>{r.index + 1}. {lessonTitle(r.lesson, locale)}</strong>{r.lesson.durationSec > 0 && <span className="num">{clock(r.lesson.durationSec)}</span>}</p>}
{r && <div className="cd-cta" ref={setCtaEl}><button className={`btn btn-lg ${done ? 'btn-ghost' : 'btn-accent'}`} onClick={() => nav(`/${locale}/learn/${c.slug}/${r.lesson.id}`)}>{playLabel}</button></div>}
</> : <>
{c.prices.ETB != null && <div className="cd-price"><span className="num">{formatMoney(c.prices.ETB, 'ETB')}</span><span>{t('checkout.lifetime')}</span></div>}
{pre && !preDone && <p className="cd-prereq"><Icon name="lock" size={14} /><span>{t('course.prereq', { title: ct(pre, locale).title })} <button className="link" onClick={() => nav(`/${locale}/course/${pre.slug}`)}>{t('course.prereqLink', { title: ct(pre, locale).title })}</button></span></p>}
<div className="cd-cta" ref={setCtaEl}>
{/* a course whose every lesson is free (the API's FREE tier) has nothing to buy: it starts instead */}
{free ? <button className="btn btn-accent btn-lg" onClick={() => nav(`/${locale}/learn/${c.slug}/${lessons[0].id}`)}><Icon name="play" size={16} />{t('checkout.start')}</button>
: <button className="btn btn-accent btn-lg" disabled={c.status !== 'PUBLISHED' || c.prices.ETB == null} onClick={() => nav(`/${locale}/checkout/${c.slug}`)}>{t('course.buyShort')}</button>}
</div>
<div className="cd-includes">
<h2>{t('course.includes')}</h2>
<ul>{includes.map(([icon, label], k) => <li key={k}><Icon name={icon} size={18} />{label}</li>)}</ul>
{c.sequentialLessons && <p className="small muted">{t('course.sequential')}</p>}
</div>
</>}
</div>
</aside>
{showBar && <div className="cd-bar" data-hidden={barHidden} aria-hidden={barHidden || undefined} inert={barHidden || undefined}>
{mine && r ? <>
<span className="cd-bar-txt"><strong className="num">{p.pct}%</strong><span>{t('my.lessonsDone', { done: p.done, total: p.total })}</span></span>
<button className="btn btn-accent" onClick={() => nav(`/${locale}/learn/${c.slug}/${r.lesson.id}`)}>{playLabel}</button>
</> : <>
<span className="cd-bar-txt"><strong className="num">{formatMoney(c.prices.ETB ?? 0, 'ETB')}</strong><span>{t('course.lifetime')}</span></span>
<button className="btn btn-accent" onClick={() => nav(`/${locale}/checkout/${c.slug}`)}>{t('course.buyShort')}</button>
</>}
</div>}
<section className={`cd-body${mine ? ' is-owner' : ''}`}>
<div className="cd-tabs" role="tablist">{tabs.map(([k, label]) => <button key={k} role="tab" aria-selected={active === k} onClick={() => setTab(k)}>{label}</button>)}</div>
{!!text.outcomes?.length && <div className="cd-pane" data-tab="overview" data-active={active === 'overview'}>
<h2><KitIcon name="brush" size={22} />{t('course.outcomes')}</h2>
<ul className="cd-learn">{text.outcomes.map((o, k) => <li key={k}><Icon name="check" size={16} />{o}</li>)}</ul>
</div>}
<div className="cd-pane cd-content" data-tab="content" data-active={active === 'content'}>
<h2 className="cd-pane-h">{t('course.content')}</h2>
<p className="small muted num">{t('course.lessons', { n: lessons.length })}{withDur(courseDuration(c))}</p>
{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 (
<details key={ch.id} className="ch" open={nextChapter ? ch.id === nextChapter : i === 0}>
<summary><span className="grow"><strong>{tr(ch.translations, locale)?.title}</strong><span className="small muted num">{d}/{ls.length}{withDur(ls.reduce((s, l) => s + l.durationSec, 0))}</span></span><Icon name="down" size={18} /></summary>
{ls.map((l) => <LessonRow key={l.id} c={c} l={l} />)}
{quizzes.filter((a) => a.chapterId === ch.id).map((a) => <AssessmentRow key={a.id} c={c} a={a} inline />)}
</details>
);
})}
{!!finalQuizzes.length && <details className="ch" open>
<summary><span className="grow"><strong>{t('assess.title')}</strong><span className="small muted num">{finalQuizzes.filter((a) => me?.assessments?.[a.id]?.passed).length}/{finalQuizzes.length}</span></span><Icon name="down" size={18} /></summary>
{finalQuizzes.map((a) => <AssessmentRow key={a.id} c={c} a={a} />)}
</details>}
</div>
{(text.description || text.audience) && <div className="cd-pane" data-tab="overview" data-active={active === 'overview'}>
<h2>{t('course.about')}</h2>
{text.description && <p style={{ whiteSpace: 'pre-line' }}>{text.description}</p>}
{text.audience && <p className="small"><strong>{t('course.audience')}: </strong>{text.audience}</p>}
<p className="cd-updated"><Icon name="calendar" size={14} />{t('course.lastUpdated')} <span className="num">{fmtDate(c.updatedAt)}</span></p>
</div>}
</section>
</div>
);
}
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 (
<button className={`lesson-row${current ? ' is-current' : ''}${done ? ' is-done' : ''}${access.ok ? '' : ' is-locked'}`} aria-current={current ? 'step' : undefined} onClick={() => nav(`/${locale}/learn/${c.slug}/${l.id}`)}>
<span className="lr-ic" aria-hidden>{current && !done ? <span className="eq"><i /><i /><i /></span> : done ? <Icon name="check" size={14} /> : access.ok ? <Icon name="play" size={12} /> : <Icon name="lock" size={14} />}</span>
<span className="lr-txt">
<span className="lr-title">{n}. {lessonTitle(l, locale)}</span>
<span className="lr-meta num">{l.durationSec > 0 && clock(l.durationSec)}{l.isPreview && !owns(me, c.id) && <span className="lr-tag">{t('course.preview')}</span>}{!access.ok && access.reason === 'COMING_SOON' && <span className="lr-tag">{t('course.comingSoon')}</span>}</span>
{seen > 0 && <span className="lr-seen" aria-hidden><i style={{ width: `${seen}%` }} /></span>}
</span>
{current ? <span className="lr-now">{t('player.nowPlaying')}</span> : <Icon name="chevron" size={16} />}
</button>
);
}
// ---------------------------------------------------------------- assessments
function AssessmentRow({ c, a, inline }: { c: Course; a: Assessment; inline?: boolean }) {
const t = useTranslations();
const { me, locale, nav } = useApp();
const r = me?.assessments?.[a.id];
const mine = owns(me, c.id);
const ch = a.chapterId ? c.chapters.find((x) => x.id === a.chapterId) : undefined;
const where = inline ? '' : ch ? t('assess.chapter', { chapter: tr(ch.translations, locale)?.title ?? '' }) : t('assess.final');
return (
<button className={`lesson-row is-quiz${r?.passed ? ' is-done' : ''}${mine ? '' : ' is-locked'}`} onClick={() => nav(`/${locale}/assess/${c.slug}/${a.id}`)}>
<span className="lr-ic" aria-hidden>{r?.passed ? <Icon name="check" size={14} /> : mine ? <Icon name="quiz" size={14} /> : <Icon name="lock" size={14} />}</span>
<span className="lr-txt">
<span className="lr-title">{tr(a.translations, locale)?.title}</span>
<span className="lr-meta num">{where && <>{where} · </>}{t('assess.questions', { n: a.questions.length })}
{r && <span className={`lr-tag ${r.passed ? 'quiz-ok' : 'quiz-todo'}`}>{r.passed ? t('assess.passed') : t('assess.notPassed')} · {t('assess.best', { pct: r.bestPct })}</span>}</span>
</span>
<Icon name="chevron" size={16} />
</button>
);
}
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<number[]>([]);
const [result, setResult] = useState<AssessmentResult | null>(null);
const [busy, setBusy] = useState(false);
const top = useRef<HTMLDivElement>(null);
if (!catalogLoaded) return <Skeleton h={260} n={2} />;
if (!c || !a || !me) return <Empty action={<button className="btn" onClick={() => nav(`/${locale}/courses`)}>{t('catalog.title')}</button>}>{t('assess.notFound')}</Empty>;
const text = tr(a.translations, locale);
const back = () => nav(`/${locale}/course/${c.slug}`);
if (!owns(me, c.id)) return <Empty action={<button className="btn btn-accent" onClick={back}>{ct(c, locale).title}</button>}>{t('assess.locked')}</Empty>;
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 (
<section className="quiz" ref={top}>
<nav className="crumbs" aria-label="Breadcrumb">
<button onClick={() => nav(`/${locale}/courses`)}>{t('nav.courses')}</button><Icon name="chevron" size={14} />
<button onClick={back}>{ct(c, locale).title}</button><Icon name="chevron" size={14} />
<button aria-current="page">{text?.title}</button>
</nav>
<header className="quiz-head">
<span className="quiz-ic"><Icon name="quiz" size={22} /></span>
<div className="stack-sm grow">
<h1>{text?.title}</h1>
{text?.intro && <p className="muted">{text.intro}</p>}
<div className="row small muted num"><span>{t('assess.questions', { n: a.questions.length })}</span><span>·</span><span>{t('assess.passMark', { pct: a.passPct })}</span>
{prev && <><span>·</span><span>{t('assess.best', { pct: prev.bestPct })}</span><span>·</span><span>{t('assess.attempts', { n: prev.attempts })}</span></>}</div>
</div>
</header>
{result && (
<div className={`quiz-result ${pct >= a.passPct ? 'ok' : 'bad'}`} role="status">
<Ring pct={pct} />
<div className="grow stack-sm"><strong>{pct >= a.passPct ? t('assess.wellDone') : t('assess.tryAgain', { pct: a.passPct })}</strong><span className="small num">{t('assess.score', { score: result.score, total: result.total })} · {t('assess.best', { pct: result.bestPct })}</span></div>
<div className="row"><button className="btn btn-ghost btn-sm" onClick={retake}>{t('assess.retake')}</button><button className="btn btn-sm" onClick={back}>{t('assess.back')}</button></div>
</div>
)}
<ol className="quiz-list">
{a.questions.map((q, i) => {
const qt = tr(q.translations, locale);
if (!qt) return null;
return (
<li key={q.id} className="quiz-q">
<fieldset disabled={!!result}>
<legend><span className="quiz-n num">{i + 1}</span>{qt.prompt}</legend>
<div className="quiz-opts">
{qt.options.map((o, k) => {
const state = !result ? '' : k === q.answer ? 'right' : answers[i] === k ? 'wrong' : '';
return (
<label key={k} className={`quiz-opt ${state}`}>
<input type="radio" name={q.id} checked={answers[i] === k} onChange={() => setAnswers((x) => { const n = [...x]; n[i] = k; return n; })} />
<span className="grow">{o}</span>
{state === 'right' && <span className="pill pill-ok"><Icon name="check" size={12} />{t('assess.correct')}</span>}
{state === 'wrong' && <span className="pill pill-bad">{t('assess.wrong')}</span>}
</label>
);
})}
</div>
{result && qt.explain && <p className="quiz-explain small">{qt.explain}</p>}
</fieldset>
</li>
);
})}
</ol>
{!result && <div className="quiz-foot">
<span className="small muted num">{done < a.questions.length ? t('assess.answerAll', { done, total: a.questions.length }) : ''}</span>
<button className="btn btn-accent" disabled={busy || done < a.questions.length} onClick={submit}>{t('assess.submit')}</button>
</div>}
</section>
);
}
// ---------------------------------------------------------------- player
function Player({ slug, lessonId }: { slug?: string; lessonId?: string }) {
const t = useTranslations();
const { courses, me, locale, nav, catalogLoaded, signedIn, viewer } = useApp();
const sheet = useRef<HTMLDialogElement>(null);
useEffect(() => { sheet.current?.close(); }, [lessonId]); // picking a lesson in the sheet closes it
const c = courses.find((x) => x.slug === slug);
const lessons = c ? publishedLessons(c) : [];
const lesson = lessons.find((l) => l.id === lessonId);
if (!catalogLoaded) return <Skeleton h={320} />;
if (!c || !lesson || !isStudentVisible(c, me)) return <Empty action={<button className="btn" onClick={() => nav(`/${locale}/courses`)}>{t('catalog.title')}</button>}>{t('course.notFound')}</Empty>;
const access = lessonAccess(c, lesson, signedIn ? me : null, courses);
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));
// L2: the video comes first; where you are (course, chapter, lesson) sits right under it
const head = (
<div className="p-head">
<p className="p-crumb">
<button onClick={() => nav(`/${locale}/course/${c.slug}`)} aria-label={`${t('player.back')}: ${ct(c, locale).title}`}><Icon name="back" size={14} />{ct(c, locale).title}</button>
{chapter && <span>{tr(chapter.translations, locale)?.title}</span>}
</p>
<h1>{idx + 1}. {lessonTitle(lesson, locale)}</h1>
</div>
);
return (
<div className="stack">
<div className="p-wrap">
<div className="stack p-main">
{access.ok ? <VideoPanel key={lesson.id} c={c} lesson={lesson} next={next} head={head} /> : <>
<div className="screen"><div className="sim">
<Icon name="lock" size={36} />
<p>{t(`player.${access.reason}`)}</p>
{access.reason === 'COURSE_NOT_OWNED' && <button className="btn btn-accent" onClick={() => nav(signedIn ? `/${locale}/checkout/${c.slug}` : `/${locale}/signin`)}>{t('course.buy', { price: formatMoney(c.prices.ETB ?? 0, 'ETB') })}</button>}
{access.reason === 'LESSON_LOCKED' && idx > 0 && <button className="btn btn-accent" onClick={() => nav(`/${locale}/learn/${c.slug}/${lessons[idx - 1].id}`)}>{idx}. {lessonTitle(lessons[idx - 1], locale)}</button>}
{access.reason === 'PREREQUISITE_REQUIRED' && <button className="btn btn-accent" onClick={() => { const pre = courses.find((x) => x.id === c.prerequisiteCourseId); if (pre) nav(`/${locale}/course/${pre.slug}`); }}>{t('course.prereqLink', { title: ct(courses.find((x) => x.id === c.prerequisiteCourseId) ?? c, locale).title })}</button>}
{access.reason === 'ACCOUNT_DEACTIVATED' && <button className="btn btn-accent" onClick={() => nav(`/${locale}/help`)}>{t('nav.help')}</button>}
</div></div>
{head}
</>}
{/* L5: only real lesson notes; no card standing in with the course blurb */}
{notes && <div className="card stack-sm">
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('player.notes')}</h2>
<p style={{ whiteSpace: 'pre-line', color: 'var(--ink-2)' }}>{notes}</p>
</div>}
</div>
<aside className="card p-side p-side-order" aria-label={t('player.contents')}><CourseContents c={c} lesson={lesson} /></aside>
</div>
{viewer && !viewer.id && <p className="small muted">{t('auth.noIdentity')}</p>}
<nav className="l-bar" aria-label={t('player.contents')}>
<button disabled={idx === 0} onClick={() => nav(`/${locale}/learn/${c.slug}/${lessons[idx - 1].id}`)}><Icon name="back" size={18} />{t('player.prev')}</button>
<button aria-haspopup="dialog" onClick={() => sheet.current?.showModal()}><Icon name="list" size={18} /><span className="num">{idx + 1} / {lessons.length}</span></button>
<button className="l-next" disabled={!next} onClick={() => nav(`/${locale}/learn/${c.slug}/${next.id}`)}>{t('player.nextShort')}<Icon name="chevron" size={18} /></button>
</nav>
{/* L6: on phones and tablets the lesson list slides up over the video instead of scrolling the page away from it */}
<dialog ref={sheet} className="lsheet" aria-label={t('player.contents')} onClick={(e) => { if (e.target === sheet.current) sheet.current?.close(); }}>
<div className="lsheet-in">
<div className="lsheet-top"><span className="lsheet-grip" aria-hidden /><button className="icon-btn" aria-label={t('common.close')} onClick={() => sheet.current?.close()}><Icon name="x" size={20} /></button></div>
<CourseContents c={c} lesson={lesson} />
</div>
</dialog>
</div>
);
}
// The course's chapters and lessons with progress: the player's sidebar on desktop and its lesson sheet on phones.
function CourseContents({ c, lesson }: { c: Course; lesson: Lesson }) {
const t = useTranslations();
const { me, locale } = useApp();
const p = courseProgress(c, me);
return <>
<div className="ps-head">
{owns(me, c.id) && <Ring pct={p.pct} size={52} />}
<div className="ps-head-txt"><span className="ps-kicker">{t('course.content')}</span><strong>{ct(c, locale).title}</strong>
{owns(me, c.id) && <span className="small muted num">{t('player.progress', { done: p.done, total: p.total })}</span>}</div>
</div>
{[...c.chapters].sort((a, b) => a.sortOrder - b.sortOrder).map((ch, ci) => {
const ls = [...ch.lessons].sort((a, b) => a.sortOrder - b.sortOrder).filter((l) => l.isPublished);
if (!ls.length) return null;
const doneN = ls.filter((l) => isCompleted(me, l.id)).length;
return <details key={ch.id} className={`ps-ch${doneN === ls.length ? ' is-done' : ''}`} open={ls.some((l) => l.id === lesson.id) || undefined}>
<summary>
<span className="ps-ch-n num">{doneN === ls.length ? <Icon name="check" size={14} /> : String(ci + 1).padStart(2, '0')}</span>
<span className="ps-ch-txt"><strong>{tr(ch.translations, locale)?.title}</strong><span className="small muted num">{doneN}/{ls.length}{ls.some((l) => l.durationSec) ? ` · ${clock(ls.reduce((a, l) => a + l.durationSec, 0))}` : ''}</span></span>
<Icon name="down" size={16} />
</summary>
<div className="ps-ch-list">{ls.map((l) => <LessonRow key={l.id} c={c} l={l} current={l.id === lesson.id} />)}</div>
</details>;
})}
</>;
}
const AUTO_NEXT_SEC = 5;
/** vimeo.com/123, vimeo.com/123/abcdef (unlisted) or player.vimeo.com/video/123 → embeddable player URL; null otherwise. */
export function vimeoPlayerUrl(url: string): string | null {
const m = /vimeo\.com\/(?:video\/)?(\d+)(?:\/([0-9a-f]+))?/.exec(url);
if (!m) return null;
const hash = m[2] ?? new URL(url, 'https://x').searchParams.get('h');
return `${VIMEO_ORIGIN}/video/${m[1]}?${hash ? `h=${hash}&` : ''}dnt=1&title=0&byline=0&portrait=0`;
}
function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next?: Lesson; head?: ReactNode }) {
const t = useTranslations();
const { me, locale, nav, ds, write, signedIn, viewer } = useApp();
// A Vimeo link (what the API's lessons carry) plays in Vimeo's player; no video yet plays the sample clip.
const placeholder = !lesson.videoAssetId;
const vimeoSrc = placeholder ? VIMEO_PLACEHOLDER : vimeoPlayerUrl(lesson.videoAssetId!);
const vimeo = !!vimeoSrc;
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<boolean>(() => !!conn && (conn.saveData || /2g|3g/.test(conn.effectiveType ?? '')));
const [quality, setQuality] = useState('auto');
const [justDone, setJustDone] = useState(false);
// L4: when a lesson ends, "up next" appears over the video and plays it after a short count the student can cancel
const [ended, setEnded] = useState(false);
const [auto, setAuto] = useState<number | null>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const frameRef = useRef<HTMLIFrameElement>(null);
const screenRef = useRef<HTMLDivElement>(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); setEnded(false); setAuto(null); }
else if (m.event === 'pause') setPlaying(false);
else if (m.event === 'ended') { setPlaying(false); setEnded(true); }
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 goNext = () => { if (next) nav(`/${locale}/learn/${c.slug}/${next.id}`); };
useEffect(() => { if (ended && next) setAuto(AUTO_NEXT_SEC); }, [ended, next]);
useEffect(() => {
if (auto == null) return;
if (auto <= 0) { goNext(); return; }
const id = setTimeout(() => setAuto((a) => (a == null ? null : a - 1)), 1000);
return () => clearTimeout(id);
}, [auto]);
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 === 'Escape' && auto != null) { setAuto(null); 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 (
<div className="stack">
<div className="screen" ref={screenRef} tabIndex={0} onKeyDown={onKey} aria-label={lessonTitle(lesson, locale)}>
{lesson.videoAssetId ? (
<video ref={videoRef} src={ds.assetUrl(lesson.videoAssetId)} playsInline preload="metadata"
onLoadedMetadata={(e) => { if (pos) e.currentTarget.currentTime = pos; }}
onTimeUpdate={(e) => setPos(e.currentTarget.currentTime)} onPlay={() => { setPlaying(true); setEnded(false); setAuto(null); }} onPause={() => setPlaying(false)} onEnded={() => { setPlaying(false); setEnded(true); }} />
) : (
<iframe ref={frameRef} src={vimeoSrc!} onLoad={vlisten} title={lessonTitle(lesson, locale)} allow="autoplay; fullscreen; picture-in-picture" allowFullScreen />
)}
{canSave && <span className="wm" aria-hidden>{mark}</span>}
{auto != null && next && <div className="p-upnext" role="status">
<span className="p-upnext-k">{t('player.upNext')}</span>
<strong>{lessonNumber(c, next.id)}. {lessonTitle(next, locale)}</strong>
<span className="p-upnext-n num" aria-hidden><svg viewBox="0 0 24 24" width="18" height="18"><circle cx="12" cy="12" r="10" /></svg>{t('player.autoNext', { n: auto })}</span>
<div className="p-upnext-go">
<button className="btn btn-accent" onClick={goNext}><Icon name="play" size={14} />{t('player.playNow')}</button>
<button className="btn btn-quiet" onClick={() => setAuto(null)}>{t('common.cancel')}</button>
</div>
</div>}
{!vimeo && <div className="controls">
<input type="range" min={0} max={dur} step={1} value={Math.floor(pos)} onChange={(e) => seek(Number(e.target.value))} aria-label={`${clock(pos)} / ${clock(dur)}`} />
<div className="row">
<button onClick={toggle} aria-label={playing ? t('player.pause') : t('player.play')}><Icon name={playing ? 'pause' : 'play'} size={16} /></button>
<button onClick={() => seek(pos - 10)} aria-label={t('player.back10')}>−10</button>
<button onClick={() => seek(pos + 10)} aria-label={t('player.fwd10')}>+10</button>
<span className="small num" style={{ color: '#fff' }}>{clock(pos)} / {clock(dur)}</span>
<span className="grow" />
<label className="sr-only" htmlFor="speed">{t('player.speed')}</label>
<select id="speed" value={rate} onChange={(e) => setRate(Number(e.target.value))}>{[0.75, 1, 1.25, 1.5, 2].map((r) => <option key={r} value={r}>{r}×</option>)}</select>
<label className="sr-only" htmlFor="quality">{t('player.quality')}</label>
<select id="quality" value={quality} onChange={(e) => setQuality(e.target.value)}>
<option value="auto">Auto{saver ? ' (≤360p)' : ''}</option>{['240p', '360p', '480p', '720p'].map((q) => <option key={q} value={q} disabled={saver && (q === '480p' || q === '720p')}>{q}</option>)}
</select>
<button aria-pressed={saver} onClick={() => { setSaver((s) => !s); if (!saver && (quality === '480p' || quality === '720p')) setQuality('360p'); }}>{t('player.dataSaver')}: {saver ? 'on' : 'off'}</button>
<button onClick={full} aria-label={t('player.fullscreen')}><Icon name="expand" size={16} /></button>
</div>
</div>}
</div>
{head}
{placeholder && <p className="small muted">{t('player.demoVideo')}{canSave && !done && <> · <button className="link" onClick={() => { setPos(dur); posRef.current = dur; heartbeat(); setEnded(true); }}>{t('player.markWatched')}</button></>}</p>}
{done && pct === 100 && (
<div className="course-done" role="status">
<div className="confetti" aria-hidden>{Array.from({ length: 18 }, (_, k) => <i key={k} style={{ '--k': k } as React.CSSProperties} />)}</div>
<span className="ld-check big" aria-hidden><svg viewBox="0 0 24 24" width="34" height="34"><path d="M5 12.5l4.5 4.5L19 7" /></svg></span>
<h2>{t('player.courseDoneT')}</h2>
<p>{t('player.courseDone', { course: ct(c, locale).title })}</p>
<div className="row" style={{ justifyContent: 'center' }}>
<button className="btn btn-accent" onClick={() => nav(`/${locale}/profile`)}>{t('player.seeProgress')}</button>
<button className="btn btn-ghost" onClick={() => nav(`/${locale}/courses`)}>{t('landing.browse')}</button>
</div>
</div>
)}
{done && pct < 100 && auto == null && (
<div className="lesson-done" role="status">
<span className="ld-check" aria-hidden><svg viewBox="0 0 24 24" width="22" height="22"><path d="M5 12.5l4.5 4.5L19 7" /></svg></span>
<span className="ld-txt"><strong>{t('player.completed')}</strong><span className="small muted num">{t('player.courseProgress', { pct })}</span></span>
{next && <button className="ld-next" onClick={() => nav(`/${locale}/learn/${c.slug}/${next.id}`)}><span><small>{t('player.upNext')}</small>{lessonTitle(next, locale)}</span><Icon name="chevron" size={18} /></button>}
</div>
)}
</div>
);
}
// ---------------------------------------------------------------- checkout (simulated ArifPay, §8.3 state machine)
function Checkout({ slug }: { slug?: string }) {
const t = useTranslations();
const { courses, categories, me, locale, nav, ds, write } = useApp();
const c = courses.find((x) => x.slug === slug);
const [method, setMethod] = useState('TELEBIRR');
const key = useRef(newId('idem_')); // one key per checkout screen: double clicks reuse it (PAY-09)
const [busy, setBusy] = useState(false);
const [err, setErr] = useState('');
if (!c || !me) return <Empty>{t('course.notFound')}</Empty>;
if (owns(me, c.id)) return <Empty action={<button className="btn" onClick={() => nav(`/${locale}/course/${c.slug}`)}>{ct(c, locale).title}</button>}>{t('checkout.alreadyOwned')}</Empty>;
const start = async () => {
setBusy(true); setErr('');
try {
const o = createOrder(me, c, method, key.current, new Date(), newId('ord_'));
const ok = me.orders?.[o.id] ? true : await write(() => ds.patchStudent(me.id, { orders: { [o.id]: o } }));
if (ok) nav(`/${locale}/pay/${o.id}`);
} catch (e) { setErr(e instanceof DomainError && e.code === 'ALREADY_OWNED' ? t('checkout.alreadyOwned') : String((e as Error).message)); }
setBusy(false);
};
return (
<div className="co">
<section className="cd-head co-main">
<h1>{t('checkout.title')}</h1>
<fieldset className="pay-pick">
<legend className="sr-only">{t('landing.payTitle')}</legend>
{METHODS.map((m) => (
<label key={m.id} className="pay-opt">
<input type="radio" name="method" value={m.id} checked={method === m.id} onChange={() => setMethod(m.id)} />
<PayLogo id={m.id} />
<span className="pay-opt-copy"><strong>{m.name}</strong><span>{m.via}</span></span>
</label>
))}
</fieldset>
<p className="cd-note"><Icon name="lock" size={14} />{t('landing.payNote')}</p>
</section>
<aside className="cd-side">
<div className="cd-buy">
<div className="cd-preview" aria-hidden><img src={c.coverAssetId ? ds.assetUrl(c.coverAssetId) : coursePhoto(c, categories.map((k) => k.id))} alt="" /></div>
<div className="stack-sm"><strong className="co-title">{ct(c, locale).title}</strong>{c.instructorName && <span className="small muted">{t('course.by', { name: c.instructorName })}</span>}</div>
<div className="row-between co-total"><span>{t('checkout.total')}</span><strong className="num">{formatMoney(c.prices.ETB ?? 0, 'ETB')}</strong></div>
{err && <p className="err" role="alert">{err}</p>}
<div className="cd-cta"><button className="btn btn-accent btn-lg" disabled={busy} onClick={start}>{t('checkout.pay', { method: methodName(method) })}</button></div>
<p className="cd-note"><Icon name="shield" size={14} />{t('checkout.lifetime')}</p>
<p className="small muted">{t('checkout.simulated')}</p>
</div>
</aside>
</div>
);}
/** Stands in for ArifPay's hosted page. The unlock still goes through applyPaymentEvent — the same rule the webhook uses — never the return URL. */
function ProviderSim({ orderId }: { orderId?: string }) {
const t = useTranslations();
const { me, courses, locale, nav, ds, write, notify } = useApp();
const o = orderId ? me?.orders?.[orderId] : undefined;
if (!o || !me) return <Empty>{t('course.notFound')}</Empty>;
const c = courses.find((x) => x.id === o.courseId);
const settle = (status: 'PAID' | 'FAILED') => {
nav(`/${locale}/orders/${o.id}`);
// the "webhook" lands a moment later, like the real provider callback
setTimeout(async () => {
const fresh = me;
const patch = applyPaymentEvent(fresh, o.id, { status, amountMinor: o.amountMinor, currency: o.currency, reason: `Declined by ${methodName(o.method)} (simulated)` }, new Date());
if (!patch) return;
const ok = await write(() => ds.patchStudent(me.id, patch));
if (ok && status === 'PAID' && c) {
await write(() => notify(me.id, { type: 'PAYMENT', title: lookup(me.locale, 'system.paidTitle'), body: lookup(me.locale, 'system.paidBody', { title: ct(c, me.locale).title, price: formatMoney(o.amountMinor, o.currency) }), link: `/${me.locale}/course/${c.slug}` }));
}
}, 1800);
};
return (
<section className="stack" style={{ maxWidth: 480, margin: '0 auto', width: '100%' }}>
<div className="card stack">
<span className="pill pill-warn" style={{ alignSelf: 'flex-start' }}>{t('checkout.simulated')}</span>
<h1 style={{ fontSize: 'var(--fs-xl)' }}>{t('checkout.providerTitle', { method: methodName(o.method) })}</h1>
<p className="muted">{t('checkout.providerBody')}</p>
<dl className="kv"><dt>{t('checkout.total')}</dt><dd className="num">{formatMoney(o.amountMinor, o.currency)}</dd><dt>Order</dt><dd>{o.id}</dd></dl>
{effectiveStatus(o) === 'PENDING' ? <>
<button className="btn btn-accent btn-block" onClick={() => settle('PAID')}>{t('checkout.approve', { price: formatMoney(o.amountMinor, o.currency) })}</button>
<button className="btn btn-ghost btn-block" onClick={() => settle('FAILED')}>{t('checkout.decline')}</button>
<button className="btn btn-quiet btn-block" onClick={() => nav(`/${locale}/orders/${o.id}`)}>{t('checkout.leave')}</button>
</> : <button className="btn btn-block" onClick={() => nav(`/${locale}/orders/${o.id}`)}>{t('checkout.orderTitle', { id: '' })}</button>}
</div>
</section>
);
}
function OrderStatusPage({ orderId }: { orderId?: string }) {
const t = useTranslations();
const { me, courses, locale, nav, ds, write } = useApp();
const [now, setNow] = useState(Date.now());
useEffect(() => { const id = setInterval(() => setNow(Date.now()), 3000); return () => clearInterval(id); }, []); // re-check every 3 s (§5.5)
const o = orderId ? me?.orders?.[orderId] : undefined;
if (!o || !me) return <Empty>{t('course.notFound')}</Empty>;
const c = courses.find((x) => x.id === o.courseId);
const status = effectiveStatus(o, now);
const first = c && publishedLessons(c)[0];
return (
<section className="stack" style={{ maxWidth: 560 }}>
<span className="small muted">{t('checkout.orderTitle', { id: o.id })}</span>
<h1 style={{ fontSize: 'var(--fs-2xl)' }}>{c ? ct(c, locale).title : ''}</h1>
<div className="row"><StatusPill status={status} label={t(`status.${status}`)} /><span className="num">{formatMoney(o.amountMinor, o.currency)} · {methodName(o.method)}</span></div>
{status === 'PENDING' && <div className="card stack-sm" aria-live="polite">
<p>{now - Date.parse(o.createdAt) > 180_000 ? t('checkout.stillWaiting') : t('checkout.pending', { method: methodName(o.method) })}</p>
<div className="bar"><i style={{ width: '40%' }} /></div>
<div className="row"><button className="btn btn-ghost btn-sm" onClick={() => nav(`/${locale}/pay/${o.id}`)}>{t('checkout.pay', { method: methodName(o.method) })}</button>
<button className="btn btn-quiet btn-sm" onClick={() => write(() => ds.patchStudent(me.id, { orders: { [o.id]: { status: 'CANCELLED', updatedAt: new Date().toISOString(), events: [...o.events, { type: 'order.cancelled', at: new Date().toISOString() }] } } }))}>{t('common.cancel')}</button></div>
</div>}
{status === 'PAID' && <div className="card stack" aria-live="polite"><div className="done-flash"><Icon name="check" />{t('checkout.paid')}</div>
{c && first && <button className="btn btn-accent" onClick={() => nav(`/${locale}/learn/${c.slug}/${first.id}`)}>{t('checkout.start')}</button>}</div>}
{status === 'FAILED' && <div className="card stack"><p className="err">{t('checkout.failed')}</p>{o.failureReason && <p className="small">{t('checkout.failedReason', { reason: o.failureReason })}</p>}
{c && <button className="btn" onClick={() => nav(`/${locale}/checkout/${c.slug}`)}>{t('checkout.tryAgain')}</button>}</div>}
{(status === 'EXPIRED' || status === 'CANCELLED') && <div className="card stack"><p>{status === 'EXPIRED' ? t('checkout.expired') : t('checkout.cancelled')}</p>
{c && <button className="btn" onClick={() => nav(`/${locale}/checkout/${c.slug}`)}>{t('checkout.tryAgain')}</button>}</div>}
{status === 'REFUNDED' && <div className="card"><p>{t('status.REFUNDED')}</p></div>}
</section>
);
}
// ---------------------------------------------------------------- my courses + progress
function MyCourses() {
const t = useTranslations();
const { me, courses, locale, nav } = useApp();
const mine = courses.filter((c) => owns(me, c.id) && !c.isTest);
return (
<section className="stack">
<div className="row-between"><h1 style={{ fontSize: 'var(--fs-2xl)' }}>{t('my.title')}</h1>{mine.length > 0 && <button className="btn btn-ghost btn-sm" onClick={() => nav(`/${locale}/progress`)}>{t('my.viewProgress')}</button>}</div>
{mine.length ? <div className="stack">{mine.map((c) => {
const p = courseProgress(c, me); const r = resumePoint(c, me);
return (
<div key={c.id} className="card row my-row" style={{ alignItems: 'center' }}>
<div className="thumb" style={{ width: 120, flex: 'none' }}><Cover course={c} locale={locale} /></div>
<div className="grow stack-sm"><strong>{ct(c, locale).title}</strong><div className="bar"><i style={{ width: `${p.pct}%` }} /></div><span className="small muted num">{t('my.lessonsDone', { done: p.done, total: p.total })}</span></div>
{r && <button className={`btn btn-sm ${p.pct === 100 ? 'btn-ghost' : 'btn-accent'}`} onClick={() => nav(`/${locale}/learn/${c.slug}/${r.lesson.id}`)}>{p.pct === 100 ? t('course.watchAgain') : t('my.resume')}</button>}
</div>
);
})}</div> : <Empty action={<button className="btn" onClick={() => nav(`/${locale}/courses`)}>{t('landing.browse')}</button>}>{t('my.empty')}</Empty>}
</section>
);
}
// Everything a student did, newest first: lessons finished or started, purchases, reports.
type Activity = { at: string; icon: string; text: string; link?: string };
function activity(me: Student, courses: Course[], locale: Locale, t: ReturnType<typeof useTranslations>): Activity[] {
const out: Activity[] = [];
for (const [lid, pr] of Object.entries(me.progress ?? {})) {
const c = courses.find((x) => x.id === pr.courseId);
const l = c?.chapters.flatMap((ch) => ch.lessons).find((x) => x.id === lid);
if (!c || !l) continue;
out.push({ at: pr.completedAt ?? pr.updatedAt, icon: pr.completedAt ? 'check' : 'play', text: t(pr.completedAt ? 'history.done' : 'history.watched', { lesson: lessonTitle(l, locale), course: ct(c, locale).title }), link: `/${locale}/learn/${c.slug}/${lid}` });
}
for (const o of Object.values(me.orders ?? {})) {
const c = courses.find((x) => x.id === o.courseId);
if (o.paidAt && c) out.push({ at: o.paidAt, icon: 'cart', text: t('history.paid', { course: ct(c, locale).title }), link: `/${locale}/course/${c.slug}` });
}
for (const i of Object.values(me.issues ?? {})) out.push({ at: i.createdAt, icon: 'flag', text: t('history.report', { subject: i.subject }), link: `/${locale}/help` });
return out.sort((a, b) => b.at.localeCompare(a.at));
}
function Timeline({ items, grouped }: { items: Activity[]; grouped?: boolean }) {
const { nav } = useApp();
return (
<ol className="tl">{items.map((a, k) => <li key={k}>
{grouped && (k === 0 || fmtDate(items[k - 1].at) !== fmtDate(a.at)) && <h3 className="tl-day">{fmtDate(a.at)}</h3>}
<button className="tl-row" disabled={!a.link} onClick={() => a.link && nav(a.link)}>
<span className={`tl-ic tl-${a.icon}`}><Icon name={a.icon} size={16} /></span>
<span className="tl-txt">{a.text}{!grouped && <time className="small muted">{fmtDate(a.at)}</time>}</span>
{a.link && <Icon name="chevron" size={16} />}
</button>
</li>)}</ol>
);
}
function History() {
const t = useTranslations();
const { me, courses, locale } = useApp();
if (!me) return null;
const items = activity(me, courses, locale, t);
return (
<section className="pf">
<header className="pf-head"><h1>{t('history.title')}</h1><p className="muted">{t('history.lead')}</p></header>
{items.length ? <Timeline items={items} grouped /> : <Empty>{t('history.empty')}</Empty>}
</section>
);
}
// ---------------------------------------------------------------- notifications inbox
function Inbox() {
const t = useTranslations();
const { inbox, me, ds, write, nav } = useApp();
if (!me) return null;
const unread = inbox.filter((n) => !n.readAt);
const read = (id: string) => write(() => ds.patchInbox(me.id, id, { readAt: new Date().toISOString() }));
return (
<section className="stack" style={{ maxWidth: 720 }}>
<div className="row-between"><h1 style={{ fontSize: 'var(--fs-2xl)' }}>{t('notif.title')}</h1>
{unread.length > 0 && <button className="btn btn-ghost btn-sm" onClick={async () => { for (const n of unread) await read(n.id); }}>{t('notif.markAll')}</button>}</div>
{inbox.length ? <div>{inbox.map((n) => (
<div key={n.id} className="notif-item">
<span className={n.readAt ? 'read-dot' : 'unread-dot'} aria-label={n.readAt ? undefined : 'unread'} />
<div className="grow stack-sm"><strong>{n.title}</strong><p style={{ color: 'var(--ink-2)' }}>{n.body}</p><span className="small muted">{fmtDate(n.createdAt)}</span></div>
<div className="stack-sm">
{n.link && <button className="btn btn-sm" onClick={() => { if (!n.readAt) read(n.id); nav(n.link!); }}>{t('notif.open')}</button>}
{!n.readAt && !n.link && <button className="btn btn-ghost btn-sm" onClick={() => read(n.id)}><Icon name="check" size={14} /></button>}
</div>
</div>
))}</div> : <Empty>{t('notif.empty')}</Empty>}
</section>
);
}
// ---------------------------------------------------------------- help + issues (L9)
function Help() {
const t = useTranslations();
const { settings, me, signedIn, ds, write, locale, nav } = useApp();
const [type, setType] = useState<IssueType>('BUG');
const [subject, setSubject] = useState('');
const [desc, setDesc] = useState('');
const [shot, setShot] = useState<File | null>(null);
const [err, setErr] = useState('');
const [uploader, setUploader] = useState<Awaited<ReturnType<typeof ds.uploads>>>(null);
useEffect(() => { ds.uploads().then(setUploader); }, [ds]);
const submit = async (e: React.FormEvent) => {
e.preventDefault(); setErr('');
if (!me) return;
if (!subject.trim() || !desc.trim()) { setErr(t('help.required')); return; }
if (shot && shot.size > 5 * 1024 * 1024) { setErr(t('help.screenshotTooBig')); return; }
let screenshotAssetId: string | null = null;
if (shot && uploader) { try { screenshotAssetId = (await uploader.upload(shot)).id; } catch { /* report still goes without the image */ } }
const now = new Date().toISOString();
const issue: Issue = { id: newId('iss_'), type, subject: subject.trim(), description: desc.trim(), status: 'OPEN', screenshotAssetId, createdAt: now, updatedAt: now };
if (await write(() => ds.patchStudent(me.id, { issues: { [issue.id]: issue } }), t('help.sent'))) { setSubject(''); setDesc(''); setShot(null); }
};
const tel = settings.supportPhone.replace(/[^\d+]/g, '');
const mine = Object.values(me?.issues ?? {}).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
return (
<div className="help">
<header className="help-hero">
<h1>{t('help.title')}</h1>
<p className="lead">{t('help.lead')}</p>
</header>
<ul className="help-contact" aria-label={t('help.contact')}>
<li><a href={settings.telegramLink} target="_blank" rel="noreferrer"><span className="hc-ic"><Icon name="send" size={22} /></span><strong>Telegram</strong><span>{t('help.telegram')}</span></a></li>
<li><a href={`tel:${tel}`}><span className="hc-ic"><Icon name="phone" size={22} /></span><strong>{t('help.call')}</strong><span className="num">{settings.supportPhone}</span></a><CopyText text={settings.supportPhone} copyLabel={t('help.copy')} copiedLabel={t('help.copied')} /></li>
<li><a href={`mailto:${settings.supportEmail}`}><span className="hc-ic"><Icon name="mail" size={22} /></span><strong>{t('help.email')}</strong><span>{settings.supportEmail}</span></a><CopyText text={settings.supportEmail} copyLabel={t('help.copy')} copiedLabel={t('help.copied')} /></li>
</ul>
<div className="help-grid">
<section className="faq help-faq"><h2>{t('help.faq')}</h2>
{[1, 2, 3].map((i) => <details key={i}><summary>{t(`help.q${i}`)}<Icon name="plus" size={18} /></summary><p>{t(`help.a${i}`)}</p></details>)}
</section>
<div className="stack">
{signedIn ? <form className="card stack" onSubmit={submit}>
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('help.report')}</h2>
<label className="field"><span>{t('help.type')}</span><select id="itype" className="input" value={type} onChange={(e) => setType(e.target.value as IssueType)}>{ISSUE_TYPES.map((x) => <option key={x} value={x}>{t(`issueType.${x}`)}</option>)}</select></label>
<label className="field"><span>{t('help.subject')}</span><input id="isubject" className="input" value={subject} onChange={(e) => setSubject(e.target.value)} maxLength={120} /></label>
<label className="field"><span>{t('help.description')}</span><textarea id="idesc" className="input" value={desc} onChange={(e) => setDesc(e.target.value)} maxLength={2000} /></label>
{uploader && <label className="field"><span>{t('help.screenshot')}</span><input id="ishot" type="file" accept="image/png,image/jpeg,image/webp" onChange={(e) => setShot(e.target.files?.[0] ?? null)} /></label>}
{err && <p className="err" role="alert">{err}</p>}
<button className="btn btn-accent">{t('help.submit')}</button>
</form> : <div className="card stack-sm"><h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('help.report')}</h2><button className="btn" onClick={() => nav(`/${locale}/signin`)}>{t('nav.getStarted')}</button></div>}
{signedIn && <div className="card stack-sm"><h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('help.mine')}</h2>
{mine.length ? mine.map((i) => <div key={i.id} className="row-between" style={{ borderTop: '1px solid var(--line)', paddingTop: 10 }}>
<div className="grow"><strong>{i.subject}</strong><p className="small muted">{t(`issueType.${i.type}`)} · {fmtDate(i.createdAt)}</p>{i.resolutionNote && <p className="small">{i.resolutionNote}</p>}</div>
<StatusPill status={i.status} label={t(`status.${i.status}`)} /></div>) : <p className="muted">{t('help.noReports')}</p>}
</div>}
</div>
</div>
</div>
);
}
// ---------------------------------------------------------------- sign in (simulated OTP) + profile setup
function SignIn() {
const t = useTranslations();
const { viewer, account: me, ready, signIn, nav, locale, ds, reloadViewer } = useApp();
const auth = ds.auth; // real sign-in (API); without it the code is simulated and shown on screen
const [busy, setBusy] = useState(false);
const [mode, setMode] = useState<'phone' | 'email'>('phone');
const [phone, setPhone] = useState('');
const [dial, setDial] = useState(() => { const r = (typeof navigator !== 'undefined' ? navigator.language : '').split('-')[1]?.toUpperCase(); return r && DIALS[r] ? r : 'ET'; });
const [email, setEmail] = useState('');
const [pw, setPw] = useState('');
const [step, setStep] = useState<'start' | 'code' | 'setup'>('start');
const [code, setCode] = useState('');
const [entered, setEntered] = useState('');
const [tries, setTries] = useState(5);
const [wait, setWait] = useState(0);
const [err, setErr] = useState('');
useEffect(() => { if (wait <= 0) return; const id = setTimeout(() => setWait((w) => w - 1), 1000); return () => clearTimeout(id); }, [wait]);
if (!ready) return <Skeleton h={200} />;
const local = phone.replace(/\D/g, '').replace(/^0/, '');
const e164 = `+${DIALS[dial]}${local}`;
const target = mode === 'phone' ? `+${DIALS[dial]} ${phone}` : email;
const send = () => {
setErr('');
if (mode === 'phone' && !(dial === 'ET' ? /^[79]\d{8}$/.test(local) : local.length >= 4 && e164.length <= 16)) { setErr(t('auth.phoneInvalid')); return; }
if (mode === 'email' && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { setErr(t('auth.emailInvalid')); return; }
if (mode === 'email' && !validPassword(pw)) { setErr(t('auth.passwordShort')); return; }
if (auth) { void startReal(); return; }
setCode(String(Math.floor(100000 + Math.random() * 900000))); setTries(5); setEntered(''); setWait(60); setStep('code');
};
const contact = () => (mode === 'phone' ? { phone: e164 } : { email, password: pw });
// The server's own message when it gave one; a plain "couldn't reach the server" when it never answered.
const apiErr = (e: unknown) => ((e as { code?: string })?.code === 'network' ? t('auth.networkError') : (e as Error)?.message || t('auth.networkError'));
// After a real sign-in: a learner without a name yet goes to profile setup, everyone else home.
const finish = async () => {
await reloadViewer(); signIn();
const v = await ds.viewer();
if (v.name.trim()) nav(`/${locale}`); else setStep('setup');
};
const startReal = async () => {
setBusy(true);
try {
const next = await auth!.start(contact());
if (next === 'done') await finish(); else { setEntered(''); setWait(60); setStep('code'); }
} catch (e) { setErr(apiErr(e)); }
setBusy(false);
};
const verify = async (e: React.FormEvent) => {
e.preventDefault(); setErr('');
if (auth) {
setBusy(true);
try { await auth.verify(contact(), entered); await finish(); }
catch (x) { setErr(apiErr(x)); }
setBusy(false);
return;
}
if (tries <= 0) { setErr(t('auth.locked')); return; }
if (entered !== code) { const left = tries - 1; setTries(left); setErr(left ? t('auth.wrongCode', { n: left }) : t('auth.locked')); return; }
if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup');
};
if (step === 'setup') return <ProfileSetup phone={mode === 'phone' ? e164 : undefined} email={mode === 'email' ? email : undefined} />;
return (
<section className="auth">
<div className="auth-side">
<img className="auth-photo" src="/photos/habesha-bride.jpg" alt="" />
<Logo />
<h2>{t('auth.sideTitle')}</h2>
<p>{t('landing.lead')}</p>
<ul className="facts">{['fact2', 'fact3'].map((k) => <li key={k}><Icon name="check" size={16} />{t(`landing.${k}`)}</li>)}</ul>
</div>
<div className="auth-main">
{!auth && !viewer?.id ? <Empty>{t('auth.noIdentity')}</Empty> : step === 'start' ? <form className="stack" onSubmit={(e) => { e.preventDefault(); send(); }}>
<div className="stack-sm"><h1>{t('auth.welcome')}</h1><p className="muted">{t('auth.welcomeLead')}</p></div>
{me && !me.deletedAt && <button type="button" className="btn btn-accent btn-block btn-lg" onClick={() => { signIn(); nav(`/${locale}`); }}>{t('auth.continueAs', { name: me.name.split(' ')[0] })}</button>}
{/* Google / Apple need the providers' own sign-in SDKs before they can run against the API */}
{!auth && <><SocialLogins onPick={() => { if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup'); }} />
<div className="or"><span>{t('auth.or')}</span></div></>}
<h2 className="auth-h2">{mode === 'phone' ? t('auth.phoneTitle') : t('auth.emailTitle')}</h2>
{mode === 'phone' ? (
<label className="field"><span>{t('auth.phoneLabel')}</span>
<div className="row" style={{ flexWrap: 'nowrap' }}><label className="dial-pick"><span className="sr-only">{t('auth.countryCode')}</span><span aria-hidden>{flagOf(dial)} +{DIALS[dial]}</span><select value={dial} onChange={(e) => setDial(e.target.value)}>{DIAL_OPTIONS.map(([cc, name]) => <option key={cc} value={cc}>{flagOf(cc)} {name} +{DIALS[cc]}</option>)}</select></label><input id="phone" className="input" inputMode="numeric" autoComplete="tel-national" placeholder={dial === 'ET' ? '9XX XXX XXX' : t('auth.phoneLabel')} value={phone} onChange={(e) => setPhone(e.target.value)} /></div>
</label>
) : <>
<label className="field"><span>{t('auth.emailLabel')}</span><input id="email" className="input" type="email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} /></label>
<label className="field"><span>{t('auth.passwordLabel')}</span><input id="pw" className="input" type="password" autoComplete="new-password" value={pw} onChange={(e) => setPw(e.target.value)} /><span className="hint">{t('auth.passwordHint')}</span></label>
</>}
{err && <p className="err" role="alert">{err}</p>}
<button className="btn btn-block" disabled={busy}>{t('auth.sendCode')}</button>
<button type="button" className="link" onClick={() => { setMode(mode === 'phone' ? 'email' : 'phone'); setErr(''); }}>{mode === 'phone' ? t('auth.useEmail') : t('auth.usePhone')}</button>
</form> : <form className="stack" onSubmit={verify}>
<h1>{t('auth.codeTitle')}</h1>
<p>{t('auth.codeSent', { target })}</p>
{!auth && <p className="banner"><strong>{t('auth.demoCode', { code })}</strong></p>}
<label className="field"><span className="sr-only">{t('auth.codeTitle')}</span><input id="otp" className="input otp" inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={entered} onChange={(e) => setEntered(e.target.value.replace(/\D/g, ''))} /></label>
{err && <p className="err" role="alert">{err}</p>}
<button className="btn btn-accent btn-block" disabled={busy || entered.length < 4 || (!auth && (entered.length !== 6 || tries <= 0))}>{t('auth.verify')}</button>
<button type="button" className="btn btn-ghost btn-block" disabled={wait > 0} onClick={send}>{wait > 0 ? t('auth.resendIn', { s: wait }) : t('auth.resend')}</button>
<button type="button" className="link" onClick={() => setStep('start')}>{t('common.back')}</button>
</form>}
</div>
</section>
);
}
// Simulated like the phone code: any provider signs the demo viewer in (or starts profile setup).
const SOCIAL: [string, string, ReactNode][] = [
['google', 'Google', <><path fill="#FFC107" d="M43.6 20.1H42V20H24v8h11.3C33.7 32.7 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.6-.4-3.9z" /><path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z" /><path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-7.9l-6.5 5C9.5 39.6 16.2 44 24 44z" /><path fill="#1976D2" d="M43.6 20.1H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.2 5.2C37 39.2 44 34 44 24c0-1.3-.1-2.6-.4-3.9z" /></>],
['apple', 'Apple', <path fill="currentColor" transform="scale(2)" d="M12.15 6.9c-.95 0-2.42-1.08-3.96-1.04-2.04.03-3.91 1.18-4.96 3.01-2.12 3.68-.55 9.1 1.52 12.09 1.01 1.45 2.2 3.09 3.79 3.04 1.52-.07 2.09-.99 3.94-.99 1.83 0 2.35.99 3.96.95 1.64-.03 2.68-1.48 3.68-2.95 1.16-1.69 1.64-3.33 1.66-3.42-.04-.01-3.18-1.22-3.22-4.86-.03-3.04 2.48-4.49 2.6-4.56-1.43-2.09-3.62-2.32-4.39-2.38-2-.16-3.68 1.09-4.62 1.09zm3.38-3.07c.84-1.01 1.4-2.43 1.25-3.83-1.21.05-2.66.8-3.53 1.82-.78.9-1.45 2.34-1.27 3.71 1.34.1 2.71-.69 3.55-1.7z" />],
['telegram', 'Telegram', <><circle cx="24" cy="24" r="24" fill="#26A5E4" /><path fill="#fff" d="M10.8 23.6l23.2-9c1-.4 1.9.2 1.6 1.9l-4 18.6c-.3 1.3-1.1 1.6-2.1 1l-6-4.4-2.9 2.8c-.3.3-.6.6-1.2.6l.4-6.1 11.2-10.1c.5-.4-.1-.7-.8-.3l-13.8 8.7-6-1.9c-1.3-.4-1.3-1.3.4-1.8z" /></>],
['facebook', 'Facebook', <path fill="#1877F2" transform="scale(2)" d="M24 12.07C24 5.41 18.63 0 12 0S0 5.4 0 12.07C0 18.1 4.39 23.1 10.13 24v-8.44H7.08v-3.49h3.04V9.41c0-3.02 1.8-4.7 4.54-4.7 1.31 0 2.68.24 2.68.24v2.97h-1.5c-1.5 0-1.96.93-1.96 1.89v2.26h3.32l-.53 3.5h-2.8V24C19.62 23.1 24 18.1 24 12.07" />],
];
// Country dial codes (same list as the waitlist page). Ethiopia and Eritrea first, the rest by name.
const DIALS: Record<string, string> = Object.fromEntries('AF93 AL355 DZ213 AS1 AD376 AO244 AI1 AG1 AR54 AM374 AW297 AU61 AT43 AZ994 BS1 BH973 BD880 BB1 BY375 BE32 BZ501 BJ229 BM1 BT975 BO591 BA387 BW267 BR55 BN673 BG359 BF226 BI257 KH855 CM237 CA1 CV238 KY1 CF236 TD235 CL56 CN86 CO57 KM269 CG242 CD243 CR506 CI225 HR385 CU53 CY357 CZ420 DK45 DJ253 DM1 DO1 EC593 EG20 SV503 GQ240 ER291 EE372 SZ268 ET251 FJ679 FI358 FR33 GA241 GM220 GE995 DE49 GH233 GR30 GD1 GU1 GT502 GN224 GW245 GY592 HT509 HN504 HK852 HU36 IS354 IN91 ID62 IR98 IQ964 IE353 IL972 IT39 JM1 JP81 JO962 KZ7 KE254 KI686 XK383 KW965 KG996 LA856 LV371 LB961 LS266 LR231 LY218 LI423 LT370 LU352 MO853 MG261 MW265 MY60 MV960 ML223 MT356 MR222 MU230 MX52 MD373 MC377 MN976 ME382 MA212 MZ258 MM95 NA264 NP977 NL31 NZ64 NI505 NE227 NG234 KP850 MK389 NO47 OM968 PK92 PS970 PA507 PG675 PY595 PE51 PH63 PL48 PT351 PR1 QA974 RO40 RU7 RW250 KN1 LC1 VC1 WS685 SM378 ST239 SA966 SN221 RS381 SC248 SL232 SG65 SK421 SI386 SB677 SO252 ZA27 KR82 SS211 ES34 LK94 SD249 SR597 SE46 CH41 SY963 TW886 TJ992 TZ255 TH66 TL670 TG228 TO676 TT1 TN216 TR90 TM993 UG256 UA380 AE971 GB44 US1 UY598 UZ998 VU678 VE58 VN84 YE967 ZM260 ZW263'.split(' ').map((x) => [x.slice(0, 2), x.slice(2)]));
const regionName = (() => { try { const n = new Intl.DisplayNames(['en'], { type: 'region' }); return (c: string) => n.of(c) ?? c; } catch { return (c: string) => c; } })();
const DIAL_OPTIONS: [string, string][] = [['ET', regionName('ET')], ['ER', regionName('ER')], ...Object.keys(DIALS).filter((c) => c !== 'ET' && c !== 'ER').map((c) => [c, regionName(c)] as [string, string]).sort((a, b) => a[1].localeCompare(b[1]))];
const flagOf = (cc: string) => String.fromCodePoint(...[...cc].map((ch) => 127397 + ch.charCodeAt(0)));
function SocialLogins({ onPick }: { onPick(provider: string): void }) {
const t = useTranslations();
return (
<div className="social" role="group" aria-label={t('auth.socialLabel')}>
{SOCIAL.map(([id, name, mark]) => <button key={id} type="button" className="social-btn" aria-label={t('auth.continueWith', { name })} onClick={() => onPick(id)}>
<svg viewBox="0 0 48 48" width="20" height="20" aria-hidden>{mark}</svg>{name}
</button>)}
</div>
);
}
export function LocationFields({ country, city, onCountry, onCity, labels }: { country: string; city: string; onCountry(v: string): void; onCity(v: string): void; labels: { country: string; city: string; pick: string; type: string } }) {
return <>
<label className="field"><span>{labels.country}</span>
<select id="country" className="input" value={country} onChange={(e) => { onCountry(e.target.value); onCity(''); }}>{COUNTRIES.map(([code, name]) => <option key={code} value={code}>{name}</option>)}</select></label>
<label className="field"><span>{labels.city}</span>
{country === 'ET'
? <select id="city" className="input" value={city} onChange={(e) => onCity(e.target.value)}><option value="">{labels.pick}</option>{ET_CITIES.map((c) => <option key={c} value={c}>{c}</option>)}</select>
: <input id="city" className="input" placeholder={labels.type} value={city} onChange={(e) => onCity(e.target.value)} />}
</label>
</>;
}
function ProfileSetup({ phone, email }: { phone?: string; email?: string }) {
const t = useTranslations();
const { viewer, ds, write, locale, setLocale, signIn, nav } = useApp();
const [name, setName] = useState(viewer?.name ?? '');
const [country, setCountry] = useState('ET');
const [city, setCity] = useState('');
const [lang, setLang] = useState<Locale>(locale);
const [err, setErr] = useState('');
const save = async (e: React.FormEvent) => {
e.preventDefault(); setErr('');
if (!name.trim()) { setErr(t('setup.nameRequired')); return; }
const locErr = validateLocation(country, city);
if (locErr) { setErr(t(`setup.${locErr}`)); return; }
const now = new Date().toISOString();
const s: Student = { id: viewer!.id!, name: name.trim(), phone, email, country, city: city.trim(), locale: lang, status: 'ACTIVE', createdAt: now, updatedAt: now, lastActiveAt: now, enrollments: {}, orders: {}, progress: {}, issues: {}, watchSec: {} };
if (await write(() => ds.saveStudent(s))) { signIn(); if (lang !== locale) setLocale(lang); nav(`/${lang}`); }
};
return (
<section className="stack" style={{ maxWidth: 480, margin: '0 auto', width: '100%' }}>
<form className="card stack" onSubmit={save}>
<h1 style={{ fontSize: 'var(--fs-xl)' }}>{t('setup.title')}</h1>
<label className="field"><span>{t('setup.name')}</span><input id="name" className="input" autoComplete="name" value={name} onChange={(e) => setName(e.target.value)} /></label>
<LocationFields country={country} city={city} onCountry={setCountry} onCity={setCity} labels={{ country: t('setup.country'), city: t('setup.city'), pick: t('setup.cityPick'), type: t('setup.cityType') }} />
<label className="field"><span>{t('setup.language')}</span><select id="slang" className="input" value={lang} onChange={(e) => setLang(e.target.value as Locale)}>{LOCALES.map((l) => <option key={l} value={l}>{LOCALE_NAMES[l]}</option>)}</select></label>
{err && <p className="err" role="alert">{err}</p>}
<button className="btn btn-accent btn-block">{t('setup.save')}</button>
</form>
</section>
);
}
// ---------------------------------------------------------------- profile (§5.11)
const NOTIF_TYPES = ['PAYMENT', 'NEW_LESSON', 'ISSUE', 'ANNOUNCEMENT'] as const;
function Profile() {
const t = useTranslations();
const { me, ds, write, courses, categories, locale, setLocale, signOut, nav } = useApp();
const [name, setName] = useState(me?.name ?? '');
const [phone, setPhone] = useState(me?.phone ?? '');
const [email, setEmail] = useState(me?.email ?? '');
const [country, setCountry] = useState(me?.country ?? 'ET');
const [city, setCity] = useState(me?.city ?? '');
const [err, setErr] = useState('');
const [receipt, setReceipt] = useState<Order | null>(null);
const [confirmDelete, setConfirmDelete] = useState(false);
if (!me) return null;
const save = async (e: React.FormEvent) => {
e.preventDefault(); setErr('');
if (!name.trim()) { setErr(t('setup.nameRequired')); return; }
const locErr = validateLocation(country, city);
if (locErr) { setErr(t(`setup.${locErr}`)); return; }
await write(() => ds.patchStudent(me.id, { name: name.trim(), phone, email, country, city: city.trim(), updatedAt: new Date().toISOString() }), t('common.saved'));
};
const pref = (type: string, ch: 'EMAIL' | 'SMS') => me.notificationPrefs?.[type]?.[ch] !== false;
const orders = Object.values(me.orders ?? {}).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
const courseTitle = (id: string) => { const c = courses.find((x) => x.id === id); return c ? ct(c, locale).title : id; };
const mine = courses.filter((c) => owns(me, c.id) && !c.isTest);
const finished = Object.values(me.progress ?? {}).filter((x) => x.completedAt).length;
const watched = Object.values(me.watchSec ?? {}).reduce((a, b) => a + b, 0);
const recent = activity(me, courses, locale, t).slice(0, 5);
const where = [me.city, COUNTRIES.find(([code]) => code === me.country)?.[1]].filter(Boolean).join(', ');
return (
<section className="pf">
<header className="pf-hero">
<span className="pf-avatar" aria-hidden>{initials(me.name)}</span>
<div className="pf-id"><h1>{me.name}</h1><p>{where && <>{where} · </>}{t('profile.since', { date: fmtDate(me.createdAt) })}</p></div>
</header>
<dl className="pf-stats">
<div><dt>{t('profile.statCourses')}</dt><dd className="num">{mine.length}</dd></div>
<div><dt>{t('profile.statLessons')}</dt><dd className="num">{finished}</dd></div>
<div><dt>{t('profile.statTime')}</dt><dd className="num">{formatDuration(watched)}</dd></div>
</dl>
<section className="pf-sec" id="progress">
<h2>{t('my.progressTitle')}</h2>
{mine.length ? <ul className="pf-courses">{mine.map((c) => {
const pr = courseProgress(c, me);
const r = resumePoint(c, me);
return <li key={c.id} className="pf-course">
<img src={c.coverAssetId ? ds.assetUrl(c.coverAssetId) : coursePhoto(c, categories.map((k) => k.id))} alt="" loading="lazy" />
<div className="pf-c-main">
<strong>{ct(c, locale).title}</strong>
<div className="bar"><i style={{ width: `${pr.pct}%` }} /></div>
<span className="small muted num">{t('my.lessonsDone', { done: pr.done, total: pr.total })} · {pr.pct}%</span>
</div>
{r && <button className={`btn btn-sm ${pr.pct === 100 ? 'btn-ghost' : 'btn-accent'}`} onClick={() => nav(`/${locale}/learn/${c.slug}/${r.lesson.id}`)}>{pr.pct === 100 ? t('course.watchAgain') : t('course.continue', { n: r.index + 1 })}</button>}
<details className="pf-more"><summary>{t('profile.lessonsList')}<Icon name="down" size={16} /></summary>
{[...c.chapters].sort((a, b) => a.sortOrder - b.sortOrder).map((ch) => <div key={ch.id}><p className="small" style={{ fontWeight: 700, padding: '8px 4px 2px' }}>{tr(ch.translations, locale)?.title}</p>{ch.lessons.filter((l) => l.isPublished).sort((a, b) => a.sortOrder - b.sortOrder).map((l) => <LessonRow key={l.id} c={c} l={l} />)}</div>)}
{!!c.assessments?.length && <div><p className="small" style={{ fontWeight: 700, padding: '8px 4px 2px' }}>{t('assess.title')}</p>{c.assessments.map((a) => <AssessmentRow key={a.id} c={c} a={a} />)}</div>}
</details>
</li>;
})}</ul> : <Empty action={<button className="btn" onClick={() => nav(`/${locale}/courses`)}>{t('landing.browse')}</button>}>{t('my.empty')}</Empty>}
</section>
<section className="pf-sec">
<div className="row-between"><h2>{t('history.title')}</h2>{recent.length > 0 && <button className="btn btn-ghost btn-sm" onClick={() => nav(`/${locale}/history`)}>{t('history.seeAll')}</button>}</div>
{recent.length ? <Timeline items={recent} /> : <p className="muted">{t('history.empty')}</p>}
</section>
<h2 className="pf-h">{t('profile.account')}</h2>
<div className="two-col">
<form className="card stack" onSubmit={save}>
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('profile.details')}</h2>
<label className="field"><span>{t('setup.name')}</span><input id="pname" className="input" value={name} onChange={(e) => setName(e.target.value)} /></label>
<label className="field"><span>{t('profile.phone')}</span><input id="pphone" className="input" inputMode="tel" value={phone} onChange={(e) => setPhone(e.target.value)} /></label>
<label className="field"><span>{t('profile.email')}</span><input id="pemail" className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} /></label>
<LocationFields country={country} city={city} onCountry={setCountry} onCity={setCity} labels={{ country: t('setup.country'), city: t('setup.city'), pick: t('setup.cityPick'), type: t('setup.cityType') }} />
<label className="field"><span>{t('common.language')}</span><select id="plang" className="input" value={locale} onChange={(e) => setLocale(e.target.value as Locale)}>{LOCALES.map((l) => <option key={l} value={l}>{LOCALE_NAMES[l]}</option>)}</select></label>
{err && <p className="err" role="alert">{err}</p>}
<button className="btn">{t('common.save')}</button>
</form>
<div className="stack">
<div className="card stack-sm">
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('profile.prefs')}</h2>
<p className="small muted">{t('profile.prefsNote')}</p>
<div className="tbl-wrap" style={{ border: 0 }}><table className="tbl"><thead><tr><th></th><th>{t('channel.EMAIL')}</th><th>{t('channel.SMS')}</th></tr></thead><tbody>
{NOTIF_TYPES.map((type) => <tr key={type}><td>{t(`notifType.${type}`)}</td>{(['EMAIL', 'SMS'] as const).map((ch) => <td key={ch}>
<input type="checkbox" aria-label={`${t(`notifType.${type}`)} · ${t(`channel.${ch}`)}`} checked={type === 'PAYMENT' || pref(type, ch)} disabled={type === 'PAYMENT'}
onChange={(e) => write(() => ds.patchStudent(me.id, { notificationPrefs: { [type]: { [ch]: e.target.checked } } }))} style={{ width: 20, height: 20, accentColor: 'var(--ink)' }} /></td>)}</tr>)}
</tbody></table></div>
</div>
<div className="card stack-sm">
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('profile.sessions')}</h2>
<div className="row-between"><span><Icon name="shield" size={16} /> {t('profile.thisDevice')}</span><button className="btn btn-ghost btn-sm" onClick={() => { signOut(); nav(`/${locale}`); }}>{t('profile.signOutSession')}</button></div>
</div>
<div className="card stack-sm">
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('profile.purchases')}</h2>
{orders.length ? orders.map((o) => <div key={o.id} className="row-between" style={{ borderTop: '1px solid var(--line)', paddingTop: 10 }}>
<div className="grow"><strong>{courseTitle(o.courseId)}</strong><p className="small muted num">{fmtDate(o.createdAt)} · {formatMoney(o.amountMinor, o.currency)}</p></div>
<StatusPill status={effectiveStatus(o)} label={t(`status.${effectiveStatus(o)}`)} />
<button className="btn btn-ghost btn-sm" onClick={() => effectiveStatus(o) === 'PAID' || o.status === 'REFUNDED' ? setReceipt(o) : nav(`/${locale}/orders/${o.id}`)}>{t('notif.open')}</button>
</div>) : <p className="muted">{t('profile.noPurchases')}</p>}
</div>
<div className="card stack-sm">
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('profile.delete')}</h2>
{confirmDelete ? <>
<p className="small">{t('profile.deleteBody')}</p>
<div className="row"><button className="btn btn-danger btn-sm" onClick={async () => { if (await write(() => ds.patchStudent(me.id, { deletedAt: new Date().toISOString(), status: 'DEACTIVATED' }), t('profile.deleted'))) nav(`/${locale}`); }}>{t('profile.deleteConfirm')}</button>
<button className="btn btn-ghost btn-sm" onClick={() => setConfirmDelete(false)}>{t('common.cancel')}</button></div>
</> : <button className="btn btn-ghost btn-sm" style={{ alignSelf: 'flex-start' }} onClick={() => setConfirmDelete(true)}>{t('profile.delete')}</button>}
</div>
</div>
</div>
{receipt && <Modal title={t('checkout.orderTitle', { id: receipt.id })} onClose={() => setReceipt(null)}>
<dl className="kv">
<dt>{t('nav.courses')}</dt><dd>{courseTitle(receipt.courseId)}</dd>
<dt>{t('checkout.total')}</dt><dd className="num">{formatMoney(receipt.amountMinor, receipt.currency)}</dd>
<dt>ArifPay</dt><dd>{methodName(receipt.method)}</dd>
<dt>{t(`status.${receipt.status}`)}</dt><dd>{fmtDate(receipt.paidAt)}</dd>
</dl>
<button className="btn" onClick={() => setReceipt(null)}>{t('common.close')}</button>
</Modal>}
</section>
);
}