- Signed-out visitors no longer see owned/progress state (store hides me) - Course page play button moved off the Ge'ez cover title - Phone course thumbnails show the title; small thumbnails no longer clip - Card grid fills the row; text never squeezed by buttons on phones - Press feedback, touch-safe hover, toast enter transition, custom ease-out - Add emil-design-eng and grill-me skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1214 lines
83 KiB
TypeScript
1214 lines
83 KiB
TypeScript
'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 { CopyText, Cover, Empty, FeedbackButton, fmtDate, Icon, Logo, MakeupBox, 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 ?? '';
|
||
const lessonNumber = (c: Course, id: string) => publishedLessons(c).findIndex((l) => l.id === id) + 1;
|
||
|
||
function CourseCard({ c }: { c: Course }) {
|
||
const { locale, nav, me, signedIn } = useApp();
|
||
const t = useTranslations();
|
||
const { catName } = useCatalog();
|
||
const p = courseProgress(c, me);
|
||
const mine = signedIn && owns(me, c.id);
|
||
return (
|
||
<button className="ccard" onClick={() => nav(`/${locale}/course/${c.slug}`)}>
|
||
<Cover course={c} locale={locale} badge={<span className="pill">{catName(c.categoryId)}</span>} />
|
||
<div className="ccard-body">
|
||
<h3>{ct(c, locale).title}</h3>
|
||
<span className="meta"><span><Icon name="video" size={14} />{t('course.lessons', { n: p.total })}</span><span><Icon name="clock" size={14} />{formatDuration(courseDuration(c))}</span></span>
|
||
<span className="ccard-by">{t('course.by', { name: c.instructorName })}</span>
|
||
<div className="ccard-foot">
|
||
{mine ? <><div className="bar grow" aria-label={`${p.pct}%`}><i style={{ width: `${p.pct}%` }} /></div><span className="small num">{p.pct}%</span></>
|
||
: <>{c.prices.ETB != null ? <strong className="num">{formatMoney(c.prices.ETB, 'ETB')}</strong> : <span />}<span className="ccard-cta">{t('course.viewDetails')}</span></>}
|
||
</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, setLocale } = useApp();
|
||
const section = route[1] ?? '';
|
||
const unread = signedIn ? inbox.filter((n) => !n.readAt).length : 0;
|
||
const mainRef = useRef<HTMLElement>(null);
|
||
const go = (p: string) => nav(`/${locale}${p}`);
|
||
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 === 'my' && section === 'progress') ? 'page' : undefined);
|
||
|
||
return (
|
||
<div lang={locale}>
|
||
<div className="demo-strip">{t('common.demoBanner')}</div>
|
||
<header className="s-top">
|
||
<div className="s-top-in">
|
||
<button className="brand" onClick={() => go('')}><Logo /><span>{settings.brandName}</span></button>
|
||
<nav className="s-nav" aria-label="Main">
|
||
{links.map(([p, , label]) => <button key={p} aria-current={current(p)} onClick={() => go(p ? '/' + p : '')}>{label}</button>)}
|
||
</nav>
|
||
<div className="s-actions">
|
||
<FeedbackButton label={t('common.feedback')} target={() => mainRef.current} />
|
||
<label className="lang-pick" title={t('common.language')}><Icon name="globe" size={16} /><span className="sr-only">{t('common.language')}</span>
|
||
<select id="lang" 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>
|
||
{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-quiet btn-sm hide-sm" onClick={() => go('/signin')}>{t('nav.signIn')}</button>
|
||
<button className="btn btn-accent btn-sm" onClick={() => go('/signin')}>{t('nav.getStarted')}</button>
|
||
</>}
|
||
</div>
|
||
</div>
|
||
</header>
|
||
<main className="s-main" ref={mainRef}>
|
||
{settings.maintenanceBanner && <div className="banner small" role="status">{settings.maintenanceBanner}</div>}
|
||
<StudentRoutes />
|
||
</main>
|
||
<Footer />
|
||
<nav className="s-tabs" aria-label="Main">
|
||
{tabs.map(([p, icon, label]) => <button key={p} aria-current={current(p)} onClick={() => go(p ? '/' + p : '')}><Icon name={icon} size={22} />{label}</button>)}
|
||
</nav>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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 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}/progress`)}><Icon name="chart" size={16} />{t('nav.progress')}</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, setLocale, categories, courses, viewer, signedIn, me } = useApp();
|
||
const instructors = [...new Set(courses.filter((c) => isStudentVisible(c, me) && !c.isTest).map((c) => c.instructorName))].slice(0, 3);
|
||
const go = (p: string) => nav(`/${locale}${p}`);
|
||
return (
|
||
<footer className="foot">
|
||
<div className="foot-wrap">
|
||
<div className="foot-top">
|
||
<div className="foot-story">
|
||
<h2 className="foot-word">{settings.brandName}</h2>
|
||
<p className="foot-tag">{t('footer.tagline')}</p>
|
||
<p className="foot-desc">{t('landing.footer')}</p>
|
||
{instructors.length > 0 && <ul className="foot-people">{instructors.map((n) => <li key={n}><strong>{n}</strong><span>{t('footer.instructors')}</span></li>)}</ul>}
|
||
</div>
|
||
<MakeupBox />
|
||
</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('/progress')}>{t('nav.progress')}</button>}
|
||
<button onClick={() => go('/help')}>{t('nav.help')}</button>
|
||
</div>
|
||
<div><h3>{t('footer.support')}</h3>
|
||
<a href={settings.telegramLink} target="_blank" rel="noreferrer">{t('help.telegram')}</a>
|
||
<span className="num">{settings.supportPhone}</span>
|
||
</div>
|
||
<div><h3>{t('common.language')}</h3>{LOCALES.map((l) => <button key={l} lang={l} aria-current={l === locale} onClick={() => setLocale(l)}>{LOCALE_NAMES[l]}</button>)}</div>
|
||
</nav>
|
||
<div className="foot-base"><Logo size={22} /><span>© {new Date().getFullYear()} {settings.brandName}</span><span className="foot-rights">{t('footer.rights')}</span></div>
|
||
</div>
|
||
</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><MyProgress /></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
|
||
|
||
const CAT_LOOK: [string, string][] = [['brush', 'rose'], ['sparkle', 'plum'], ['shield', 'sage'], ['book', 'sand']];
|
||
|
||
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 lessons = visible.reduce((s, c) => s + publishedLessons(c).length, 0);
|
||
const total = visible.reduce((s, c) => s + courseDuration(c), 0);
|
||
const cats = categories.filter((c) => c.isActive);
|
||
const watch = () => { if (lead) nav(preview ? `/${locale}/learn/${lead.slug}/${preview.id}` : `/${locale}/course/${lead.slug}`); };
|
||
const stats: [string, ReactNode, string][] = [['grid', visible.length, 'statCourses'], ['video', lessons, 'statLessons'], ['clock', formatDuration(total), 'statHours'], ['globe', LOCALES.length, 'statLanguages']];
|
||
return (
|
||
<>
|
||
<section className="l-hero">
|
||
<div className="l-hero-in">
|
||
<div className="hero-copy">
|
||
<span className="eyebrow-pill"><Icon name="sparkle" size={14} />{t('landing.eyebrow')}</span>
|
||
<h1>{t('landing.title')}</h1>
|
||
<p className="lead">{t('landing.lead')}</p>
|
||
<div className="row">
|
||
<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">{['fact1', 'fact2', 'fact3'].map((k) => <li key={k}><Icon name="check" size={16} />{t(`landing.${k}`)}</li>)}</ul>
|
||
</div>
|
||
{!catalogLoaded ? <Skeleton h={340} /> : lead ? (
|
||
<div className="hero-art">
|
||
<button className="hero-frame" onClick={watch} aria-label={t('course.watchPreview')}>
|
||
<Cover course={lead} locale={locale} />
|
||
<span className="play-big" aria-hidden><Icon name="play" size={22} /></span>
|
||
</button>
|
||
<div className="float float-a"><strong className="num">{lessons}</strong><span>{t('landing.statLessons')}</span></div>
|
||
<div className="float float-b"><span className="small muted">{t('course.by', { name: lead.instructorName })}</span><strong>{ct(lead, locale).title}</strong>{lead.prices.ETB != null && <span className="num small">{formatMoney(lead.prices.ETB, 'ETB')}</span>}</div>
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
</section>
|
||
|
||
<section className="statbar">
|
||
{stats.map(([icon, n, k]) => <div key={k}><span className="stat-ic"><Icon name={icon} size={20} /></span><div><strong className="num">{n}</strong><span>{t(`landing.${k}`)}</span></div></div>)}
|
||
</section>
|
||
|
||
{cats.length > 0 && <section className="stack-lg">
|
||
<div className="section-c"><h2>{t('landing.catTitle')}</h2><p>{t('landing.catLead')}</p></div>
|
||
<div className="cat-grid">{cats.map((c, i) => {
|
||
const [icon, tone] = CAT_LOOK[i % CAT_LOOK.length];
|
||
return (
|
||
<button key={c.id} className="cat-card" onClick={() => nav(`/${locale}/courses/${c.slug}`)}>
|
||
<span className={`cat-ic tone-${tone}`}><Icon name={icon} size={22} /></span>
|
||
<h3>{tr(c.translations, locale)?.name}</h3>
|
||
<span className="small muted">{t('catalog.count', { n: visible.filter((x) => x.categoryId === c.id).length })}</span>
|
||
<span className="cat-link">{t('landing.viewCourses')}<Icon name="chevron" size={14} /></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="how-panel">
|
||
<div className="stack"><h2>{t('landing.howTitle')}</h2><ol className="steps"><li>{t('landing.how1')}</li><li>{t('landing.how2')}</li><li>{t('landing.how3')}</li></ol></div>
|
||
<div className="stack-sm"><h3>{t('landing.payTitle')}</h3><div className="pay-logos">{METHODS.map((m) => <span key={m.id} className="pay-logo"><PayLogo id={m.id} />{m.name}</span>)}</div></div>
|
||
</section>
|
||
|
||
<section className="cta-band">
|
||
<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>
|
||
</>
|
||
);
|
||
}
|
||
|
||
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 (
|
||
<>
|
||
<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>}
|
||
{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="grid-cards">{[...others.filter((c) => c.isFeatured), ...others.filter((c) => !c.isFeatured)].slice(0, 4).map((c) => <CourseCard key={c.id} c={c} />)}</div></section>}
|
||
</>
|
||
);
|
||
}
|
||
|
||
function ContinueCard({ c }: { c: Course }) {
|
||
const t = useTranslations();
|
||
const { me, locale, nav } = useApp();
|
||
const p = courseProgress(c, me);
|
||
const r = resumePoint(c, me);
|
||
return (
|
||
<section className="continue" aria-label={t('home.continue')}>
|
||
<Cover course={c} locale={locale} />
|
||
<div className="stack-sm">
|
||
<span className="small" style={{ opacity: .8 }}>{t('home.continue')}</span>
|
||
<h2 style={{ fontSize: 'var(--fs-xl)' }}>{ct(c, locale).title}</h2>
|
||
{r && <p style={{ opacity: .85 }}>{r.index + 1}. {lessonTitle(r.lesson, locale)}</p>}
|
||
<div className="bar"><i style={{ width: `${p.pct}%` }} /></div>
|
||
<span className="small num" style={{ opacity: .8 }}>{t('my.lessonsDone', { done: p.done, total: p.total })}</span>
|
||
{r && <div><button className="btn btn-accent" onClick={() => nav(`/${locale}/learn/${c.slug}/${r.lesson.id}`)}><Icon name="play" size={16} />{p.pct === 100 ? t('course.watchAgain') : t('course.continue', { n: r.index + 1 })}</button></div>}
|
||
</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 [dq, setDq] = useState('');
|
||
useEffect(() => { const id = setTimeout(() => setDq(q.trim().toLowerCase()), 300); return () => clearTimeout(id); }, [q]);
|
||
const cat = categories.find((c) => c.slug === categorySlug);
|
||
const list = visible.filter((c) => (!cat || c.categoryId === cat.id) && (!dq || [
|
||
...Object.values(c.translations).map((x) => x?.title ?? ''), c.instructorName,
|
||
...Object.values(categories.find((k) => k.id === c.categoryId)?.translations ?? {}).map((x) => x?.name ?? ''),
|
||
].some((s) => s.toLowerCase().includes(dq))));
|
||
return (
|
||
<section className="stack">
|
||
<h1 style={{ fontSize: 'var(--fs-2xl)' }}>{cat ? catName(cat.id) : t('catalog.title')}</h1>
|
||
<label className="field"><span className="sr-only">{t('catalog.search')}</span>
|
||
<input id="search" className="input" type="search" placeholder={t('catalog.search')} value={q} onChange={(e) => setQ(e.target.value)} />
|
||
</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} /> : list.length ? <>
|
||
<p className="muted small" aria-live="polite">{t('catalog.count', { n: list.length })}</p>
|
||
<div className="grid-cards">{list.map((c) => <CourseCard key={c.id} c={c} />)}</div>
|
||
</> : <Empty action={dq ? <button className="btn btn-ghost" onClick={() => setQ('')}>{t('catalog.all')}</button> : undefined}>{dq ? t('catalog.empty', { q }) : 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 } = useApp();
|
||
const { catName } = useCatalog();
|
||
const [tab, setTab] = useState('overview');
|
||
const c = courses.find((x) => x.slug === slug);
|
||
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 cat = categories.find((k) => k.id === c.categoryId);
|
||
const chapters = [...c.chapters].sort((a, b) => a.sortOrder - b.sortOrder);
|
||
const play = mine && r ? `/${locale}/learn/${c.slug}/${r.lesson.id}` : preview ? `/${locale}/learn/${c.slug}/${preview.id}` : null;
|
||
const playLabel = mine && r ? (done ? t('course.watchAgain') : t('course.continue', { n: r.index + 1 })) : t('course.watchPreview');
|
||
const share = () => { navigator.clipboard?.writeText(location.href).then(() => toast(t('course.linkCopied')), () => { /* clipboard blocked */ }); };
|
||
const teaches = courses.filter((x) => x.instructorName === c.instructorName && isStudentVisible(x, me)).length;
|
||
const tabs: [string, string][] = [['overview', t('course.tabOverview')], ...(text.outcomes?.length ? [['outcomes', t('course.outcomes')] as [string, string]] : []), ['instructor', t('course.tabInstructor')]];
|
||
return (
|
||
<div className="c-page">
|
||
<nav className="crumbs" aria-label="Breadcrumb">
|
||
<button onClick={() => nav(`/${locale}`)} aria-label={t('nav.home')}><Icon name="home" size={16} /></button><Icon name="chevron" size={14} />
|
||
<button onClick={() => nav(`/${locale}/courses`)}>{t('nav.courses')}</button>
|
||
{cat && <><Icon name="chevron" size={14} /><button aria-current="page" onClick={() => nav(`/${locale}/courses/${cat.slug}`)}>{catName(cat.id)}</button></>}
|
||
</nav>
|
||
<div className="c-layout">
|
||
<div className="c-main">
|
||
<div className="stack-sm">
|
||
{c.status === 'ARCHIVED' && <div><StatusPill status="ARCHIVED" /></div>}
|
||
<h1>{text.title}</h1>
|
||
{text.subtitle && <p className="c-sub">{text.subtitle}</p>}
|
||
</div>
|
||
<ul className="c-meta">
|
||
<li><Icon name="video" size={18} /><div><strong className="num">{lessons.length}</strong><span>{t('course.lessonsLabel')}</span></div></li>
|
||
<li><Icon name="clock" size={18} /><div><strong className="num">{formatDuration(courseDuration(c))}</strong><span>{t('course.duration')}</span></div></li>
|
||
<li><Icon name="globe" size={18} /><div><strong>{LOCALE_NAMES[c.instructionLocale]}</strong><span>{t('course.language')}</span></div></li>
|
||
<li><Icon name="calendar" size={18} /><div><strong className="num">{fmtDate(c.updatedAt)}</strong><span>{t('course.lastUpdated')}</span></div></li>
|
||
</ul>
|
||
<div className="c-media">
|
||
<button className="c-screen" disabled={!play} onClick={() => play && nav(play)} aria-label={playLabel}>
|
||
<Cover course={c} locale={locale} />
|
||
{play && <span className="play-big" aria-hidden><Icon name="play" size={24} /></span>}
|
||
</button>
|
||
<div className="c-actions">
|
||
{play && <button className="btn btn-quiet btn-sm" onClick={() => nav(play)}><Icon name="play" size={14} />{playLabel}</button>}
|
||
<span className="grow" />
|
||
<button className="btn btn-quiet btn-sm" onClick={share}><Icon name="share" size={16} />{t('course.share')}</button>
|
||
</div>
|
||
</div>
|
||
{pre && !preDone && <div className="banner">{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></div>}
|
||
<div className="tabs" role="tablist">{tabs.map(([k, label]) => <button key={k} role="tab" className="tab" aria-selected={tab === k} onClick={() => setTab(k)}>{label}</button>)}</div>
|
||
{tab === 'overview' && <div className="c-overview">
|
||
<div className="stack">
|
||
{text.description && <p style={{ whiteSpace: 'pre-line' }}>{text.description}</p>}
|
||
{text.audience && <p className="small"><strong>{t('course.audience')}: </strong>{text.audience}</p>}
|
||
</div>
|
||
<dl className="c-summary">
|
||
<div><dt><Icon name="user" size={16} />{t('course.instructor')}</dt><dd>{c.instructorName}</dd></div>
|
||
<div><dt><Icon name="video" size={16} />{t('course.lessonsLabel')}</dt><dd className="num">{lessons.length}</dd></div>
|
||
<div><dt><Icon name="clock" size={16} />{t('course.duration')}</dt><dd className="num">{formatDuration(courseDuration(c))}</dd></div>
|
||
<div><dt><Icon name="globe" size={16} />{t('course.language')}</dt><dd>{LOCALE_NAMES[c.instructionLocale]}</dd></div>
|
||
<div><dt><Icon name="shield" size={16} />{t('course.access')}</dt><dd>{t('course.lifetime')}</dd></div>
|
||
</dl>
|
||
</div>}
|
||
{tab === 'outcomes' && <ol className="outcomes">{text.outcomes?.map((o, i) => <li key={i}>{o}</li>)}</ol>}
|
||
{tab === 'instructor' && <div className="row"><span className="avatar avatar-lg" aria-hidden>{initials(c.instructorName)}</span><div><strong>{c.instructorName}</strong><p className="small muted">{t('course.teaches', { n: teaches })}</p></div></div>}
|
||
</div>
|
||
|
||
<aside className="c-side">
|
||
<div className="card buybox">
|
||
{mine ? <>
|
||
<div className="row-between"><span className="pill pill-ok"><Icon name="check" size={14} />{done ? t('course.completed') : t('course.owned')}</span><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>
|
||
{r && <button className={`btn btn-block ${done ? 'btn-ghost' : 'btn-accent'}`} onClick={() => nav(`/${locale}/learn/${c.slug}/${r.lesson.id}`)}>{playLabel}</button>}
|
||
</> : <>
|
||
{c.prices.ETB != null && <div><div className="price num">{formatMoney(c.prices.ETB, 'ETB')}</div><p className="small muted">{t('checkout.lifetime')}</p></div>}
|
||
<button className="btn btn-accent btn-block" disabled={c.status !== 'PUBLISHED' || c.prices.ETB == null} onClick={() => nav(`/${locale}/checkout/${c.slug}`)}>{t('course.buy', { price: formatMoney(c.prices.ETB ?? 0, 'ETB') })}</button>
|
||
{preview && <button className="btn btn-ghost btn-block" onClick={() => nav(`/${locale}/learn/${c.slug}/${preview.id}`)}><Icon name="play" size={16} />{t('course.watchPreview')}</button>}
|
||
</>}
|
||
{c.sequentialLessons && <p className="small muted">{t('course.sequential')}</p>}
|
||
</div>
|
||
<div className="card c-content">
|
||
<div className="c-content-h"><h2>{t('course.content')}</h2><span className="small muted num">{t('course.lessons', { n: lessons.length })} · {formatDuration(courseDuration(c))}</span></div>
|
||
{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={i === 0}>
|
||
<summary><span className="grow"><strong>{tr(ch.translations, locale)?.title}</strong><span className="small muted num">{d}/{ls.length} · {formatDuration(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} />)}
|
||
</details>
|
||
);
|
||
})}
|
||
{!!c.assessments?.length && <details className="ch" open>
|
||
<summary><span className="grow"><strong>{t('assess.title')}</strong><span className="small muted num">{c.assessments.filter((a) => me?.assessments?.[a.id]?.passed).length}/{c.assessments.length}</span></span><Icon name="down" size={18} /></summary>
|
||
{c.assessments.map((a) => <AssessmentRow key={a.id} c={c} a={a} />)}
|
||
</details>}
|
||
</div>
|
||
</aside>
|
||
</div>
|
||
</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);
|
||
return (
|
||
<button className="lesson-row" aria-current={current} onClick={() => nav(`/${locale}/learn/${c.slug}/${l.id}`)}>
|
||
<span className={`ic ${done ? 'done' : ''}`}>{done ? <Icon name="check" size={14} /> : access.ok ? <Icon name="play" size={12} /> : <Icon name="lock" size={14} />}</span>
|
||
<span className="grow"><span style={{ display: 'block', fontWeight: 700 }}>{n}. {lessonTitle(l, locale)}</span>
|
||
<span className="small muted num">{clock(l.durationSec)}{l.isPreview && !owns(me, c.id) ? ` · ${t('course.preview')}` : ''}{!access.ok && access.reason === 'COMING_SOON' ? ` · ${t('course.comingSoon')}` : ''}</span></span>
|
||
<Icon name="chevron" size={16} />
|
||
</button>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- assessments
|
||
|
||
function AssessmentRow({ c, a }: { c: Course; a: Assessment }) {
|
||
const t = useTranslations();
|
||
const { me, locale, nav } = useApp();
|
||
const r = me?.assessments?.[a.id];
|
||
const ch = a.chapterId ? c.chapters.find((x) => x.id === a.chapterId) : undefined;
|
||
const where = ch ? t('assess.chapter', { chapter: tr(ch.translations, locale)?.title ?? '' }) : t('assess.final');
|
||
return (
|
||
<button className="lesson-row" onClick={() => nav(`/${locale}/assess/${c.slug}/${a.id}`)}>
|
||
<span className={`ic ${r?.passed ? 'done' : ''}`}>{r?.passed ? <Icon name="check" size={14} /> : owns(me, c.id) ? <Icon name="quiz" size={14} /> : <Icon name="lock" size={14} />}</span>
|
||
<span className="grow"><span style={{ display: 'block', fontWeight: 700 }}>{tr(a.translations, locale)?.title}</span>
|
||
<span className="small muted num">{where} · {t('assess.questions', { n: a.questions.length })}</span>
|
||
{r && <span className={`small num ${r.passed ? 'quiz-ok' : 'quiz-todo'}`}>{r.passed ? t('assess.passed') : t('assess.notPassed')} · {t('assess.best', { pct: r.bestPct })}</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 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 p = courseProgress(c, me);
|
||
const idx = lessons.indexOf(lesson);
|
||
const next = lessons[idx + 1];
|
||
const notes = tr(lesson.translations, locale)?.description;
|
||
const chapter = c.chapters.find((ch) => ch.lessons.some((l) => l.id === lesson.id));
|
||
return (
|
||
<div className="stack">
|
||
<div className="row-between">
|
||
<button className="btn btn-quiet" onClick={() => nav(`/${locale}/course/${c.slug}`)}><Icon name="back" size={16} />{t('player.back')}</button>
|
||
<span className="small muted">{ct(c, locale).title}</span>
|
||
</div>
|
||
<div className="p-wrap">
|
||
<div className="stack">
|
||
<div className="stack-sm">
|
||
<span className="small muted">{tr(chapter?.translations, locale)?.title}</span>
|
||
<h1 style={{ fontSize: 'var(--fs-xl)' }}>{idx + 1}. {lessonTitle(lesson, locale)}</h1>
|
||
</div>
|
||
{access.ok ? <VideoPanel key={lesson.id} c={c} lesson={lesson} next={next} /> : (
|
||
<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>
|
||
)}
|
||
<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 || ct(c, locale).subtitle || ct(c, locale).description}</p>
|
||
</div>
|
||
</div>
|
||
<aside className="card p-side p-side-order stack-sm" aria-label={t('player.contents')}>
|
||
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('course.content')}</h2>
|
||
{owns(me, c.id) && <div className="panel stack-sm" style={{ padding: 14 }}>
|
||
<span className="small num">{t('player.progress', { done: p.done, total: p.total })}</span>
|
||
<div className="bar"><i style={{ width: `${p.pct}%` }} /></div>
|
||
</div>}
|
||
{[...c.chapters].sort((a, b) => a.sortOrder - b.sortOrder).map((ch) => {
|
||
const ls = [...ch.lessons].sort((a, b) => a.sortOrder - b.sortOrder).filter((l) => l.isPublished);
|
||
return ls.length ? <div key={ch.id}><p className="small" style={{ fontWeight: 700, padding: '10px 4px 4px' }}>{tr(ch.translations, locale)?.title}</p>{ls.map((l) => <LessonRow key={l.id} c={c} l={l} current={l.id === lesson.id} />)}</div> : null;
|
||
})}
|
||
</aside>
|
||
</div>
|
||
{viewer && !viewer.id && <p className="small muted">{t('auth.noIdentity')}</p>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function VideoPanel({ c, lesson, next }: { c: Course; lesson: Lesson; next?: Lesson }) {
|
||
const t = useTranslations();
|
||
const { me, locale, nav, ds, write, signedIn, viewer } = useApp();
|
||
const vimeo = !lesson.videoAssetId; // no upload yet: play the Vimeo placeholder instead
|
||
const [vdur, setVdur] = useState(0);
|
||
const dur = (vimeo && vdur) || lesson.durationSec || 1;
|
||
const saved = me?.progress?.[lesson.id];
|
||
const [pos, setPos] = useState(() => (saved && !saved.completedAt ? Math.min(saved.positionSec, dur - 5) : 0));
|
||
const [playing, setPlaying] = useState(false);
|
||
const [rate, setRate] = useState(1);
|
||
const conn = typeof navigator !== 'undefined' ? (navigator as any).connection : undefined;
|
||
const [saver, setSaver] = useState<boolean>(() => !!conn && (conn.saveData || /2g|3g/.test(conn.effectiveType ?? '')));
|
||
const [quality, setQuality] = useState('auto');
|
||
const [justDone, setJustDone] = useState(false);
|
||
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);
|
||
else if (m.event === 'pause' || m.event === 'ended') setPlaying(false);
|
||
else if (m.method === 'getDuration' && m.value) setVdur(m.value);
|
||
};
|
||
addEventListener('message', on);
|
||
return () => removeEventListener('message', on);
|
||
}, [vimeo]);
|
||
// heartbeat every 15 s while playing, and on pause / leave (§5.8)
|
||
useEffect(() => { if (!playing) { heartbeat(); return; } const id = setInterval(heartbeat, 15000); return () => clearInterval(id); }, [playing, heartbeat]);
|
||
useEffect(() => {
|
||
const vis = () => document.visibilityState === 'hidden' && heartbeat();
|
||
addEventListener('visibilitychange', vis); addEventListener('pagehide', heartbeat);
|
||
return () => { removeEventListener('visibilitychange', vis); removeEventListener('pagehide', heartbeat); heartbeat(); };
|
||
}, [heartbeat]);
|
||
useEffect(() => { const v = videoRef.current; if (v) v.playbackRate = rate; }, [rate]);
|
||
useEffect(() => { if (vimeo && rate !== 1) vcall('setPlaybackRate', rate); }, [rate]);
|
||
|
||
const toggle = () => {
|
||
const v = videoRef.current;
|
||
if (v) { v.paused ? v.play().catch(() => setPlaying(false)) : v.pause(); return; }
|
||
vcall(playing ? 'pause' : 'play');
|
||
};
|
||
const seek = (to: number) => { const n = Math.max(0, Math.min(dur, to)); setPos(n); if (videoRef.current) videoRef.current.currentTime = n; else vcall('setCurrentTime', n); };
|
||
const full = () => { screenRef.current?.requestFullscreen?.().catch(() => { /* not allowed in this frame */ }); };
|
||
const onKey = (e: React.KeyboardEvent) => {
|
||
if ((e.target as HTMLElement).tagName === 'SELECT' || (e.target as HTMLElement).tagName === 'INPUT') return;
|
||
if (e.key === ' ') { e.preventDefault(); toggle(); } else if (e.key === 'ArrowLeft') seek(pos - 10); else if (e.key === 'ArrowRight') seek(pos + 10); else if (e.key === 'f') full(); else if (e.key === 'm' && videoRef.current) videoRef.current.muted = !videoRef.current.muted;
|
||
};
|
||
const mark = (me?.phone || me?.email || viewer?.name || 'student').replace(/^(.{3}).*(.{2})$/, '$1•••$2');
|
||
const done = isCompleted(me, lesson.id) || justDone;
|
||
const pct = courseProgress(c, me).pct;
|
||
return (
|
||
<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)} onPause={() => setPlaying(false)} onEnded={() => setPlaying(false)} />
|
||
) : (
|
||
<iframe ref={frameRef} src={VIMEO_PLACEHOLDER} onLoad={vlisten} title={lessonTitle(lesson, locale)} allow="autoplay; fullscreen; picture-in-picture" allowFullScreen />
|
||
)}
|
||
{canSave && <span className="wm" aria-hidden>{mark}</span>}
|
||
{!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>
|
||
{vimeo && <p className="small muted">{t('player.demoVideo')}</p>}
|
||
{done && (
|
||
<div className="done-flash" role="status"><Ring pct={pct} /><span className="grow">{t('player.completed')}</span>
|
||
{next && <button className="btn btn-sm" onClick={() => nav(`/${locale}/learn/${c.slug}/${next.id}`)}>{t('player.next')}</button>}
|
||
</div>
|
||
)}
|
||
{!done && next && <div><button className="btn btn-ghost btn-sm" onClick={() => nav(`/${locale}/learn/${c.slug}/${next.id}`)}>{t('player.next')}<Icon name="chevron" size={14} /></button></div>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- checkout (simulated ArifPay, §8.3 state machine)
|
||
|
||
function Checkout({ slug }: { slug?: string }) {
|
||
const t = useTranslations();
|
||
const { courses, 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 (
|
||
<section className="stack" style={{ maxWidth: 560 }}>
|
||
<h1 style={{ fontSize: 'var(--fs-2xl)' }}>{t('checkout.title')}</h1>
|
||
<div className="card row" style={{ flexWrap: 'nowrap' }}>
|
||
<div className="thumb" style={{ width: 110, flex: 'none' }}><Cover course={c} locale={locale} /></div>
|
||
<div className="grow stack-sm"><strong>{ct(c, locale).title}</strong><span className="small muted">{t('checkout.lifetime')}</span></div>
|
||
</div>
|
||
<fieldset className="stack-sm" style={{ border: 0, padding: 0, margin: 0 }}>
|
||
<legend className="sr-only">{t('checkout.title')}</legend>
|
||
{METHODS.map((m) => (
|
||
<label key={m.id} className="card check" style={{ padding: 16, alignItems: 'center' }}>
|
||
<input type="radio" name="method" value={m.id} checked={method === m.id} onChange={() => setMethod(m.id)} />
|
||
<PayLogo id={m.id} /><span className="grow" style={{ fontWeight: 700 }}>{m.name}</span><span className="pill">{m.via}</span>
|
||
</label>
|
||
))}
|
||
</fieldset>
|
||
<div className="row-between"><span>{t('checkout.total')}</span><strong className="price num">{formatMoney(c.prices.ETB ?? 0, 'ETB')}</strong></div>
|
||
{err && <p className="err" role="alert">{err}</p>}
|
||
<button className="btn btn-accent btn-block" disabled={busy} onClick={start}>{t('checkout.pay', { method: methodName(method) })}</button>
|
||
<p className="small muted">{t('checkout.simulated')}</p>
|
||
</section>
|
||
);
|
||
}
|
||
|
||
/** 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>
|
||
);
|
||
}
|
||
|
||
function MyProgress() {
|
||
const t = useTranslations();
|
||
const { me, courses, locale, nav } = useApp();
|
||
const mine = courses.filter((c) => owns(me, c.id) && !c.isTest);
|
||
return (
|
||
<section className="stack">
|
||
<h1 style={{ fontSize: 'var(--fs-2xl)' }}>{t('my.progressTitle')}</h1>
|
||
{!mine.length && <Empty action={<button className="btn" onClick={() => nav(`/${locale}/courses`)}>{t('landing.browse')}</button>}>{t('my.empty')}</Empty>}
|
||
{mine.map((c) => (
|
||
<div key={c.id} className="card stack-sm">
|
||
<div className="row prog-head"><Ring pct={courseProgress(c, me).pct} /><div className="grow"><h2 style={{ fontSize: 'var(--fs-lg)' }}>{ct(c, locale).title}</h2></div>
|
||
<button className="btn btn-ghost btn-sm" onClick={() => nav(`/${locale}/course/${c.slug}`)}>{t('course.content')}</button></div>
|
||
{[...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>}
|
||
</div>
|
||
))}
|
||
</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 (
|
||
<section className="two-col">
|
||
<div className="stack">
|
||
<h1 style={{ fontSize: 'var(--fs-2xl)' }}>{t('help.title')}</h1>
|
||
<div className="faq"><h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('help.faq')}</h2>
|
||
{[1, 2, 3].map((i) => <details key={i}><summary>{t(`help.q${i}`)}</summary><p>{t(`help.a${i}`)}</p></details>)}
|
||
</div>
|
||
<div className="card stack-sm"><h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('help.contact')}</h2>
|
||
<a className="btn btn-ghost" href={settings.telegramLink} target="_blank" rel="noreferrer"><Icon name="send" size={16} />{t('help.telegram')}</a>
|
||
<div className="row"><a className="btn btn-ghost grow" href={`tel:${tel}`}><Icon name="phone" size={16} />{t('help.call')}: <span className="num">{settings.supportPhone}</span></a><CopyText text={settings.supportPhone} copyLabel={t('help.copy')} copiedLabel={t('help.copied')} /></div>
|
||
<div className="row"><span className="grow small">{settings.supportEmail}</span><CopyText text={settings.supportEmail} copyLabel={t('help.copy')} copiedLabel={t('help.copied')} /></div>
|
||
</div>
|
||
</div>
|
||
<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.signIn')}</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>
|
||
</section>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- sign in (simulated OTP) + profile setup
|
||
|
||
function SignIn() {
|
||
const t = useTranslations();
|
||
const { viewer, account: me, ready, signIn, nav, locale } = useApp();
|
||
const [mode, setMode] = useState<'phone' | 'email'>('phone');
|
||
const [phone, setPhone] = useState('');
|
||
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 target = mode === 'phone' ? `+251 ${phone}` : email;
|
||
const send = () => {
|
||
setErr('');
|
||
if (mode === 'phone' && !/^\d{9}$/.test(phone.replace(/\s/g, ''))) { 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; }
|
||
setCode(String(Math.floor(100000 + Math.random() * 900000))); setTries(5); setEntered(''); setWait(60); setStep('code');
|
||
};
|
||
const verify = (e: React.FormEvent) => {
|
||
e.preventDefault(); setErr('');
|
||
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' ? `+251${phone.replace(/\s/g, '')}` : undefined} email={mode === 'email' ? email : undefined} />;
|
||
return (
|
||
<section className="auth">
|
||
<div className="auth-side">
|
||
<Logo />
|
||
<h2>{t('auth.sideTitle')}</h2>
|
||
<p>{t('auth.sideBody')}</p>
|
||
<ul className="facts">{['fact1', 'fact2', 'fact3'].map((k) => <li key={k}><Icon name="check" size={16} />{t(`landing.${k}`)}</li>)}</ul>
|
||
</div>
|
||
<div className="auth-main">
|
||
{!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>
|
||
<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' }}><span className="pill" style={{ padding: '10px 12px' }}>+251</span><input id="phone" className="input" inputMode="numeric" autoComplete="tel-national" placeholder="9XX XXX XXX" 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">{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>
|
||
<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={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>
|
||
);
|
||
}
|
||
|
||
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, 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; };
|
||
return (
|
||
<section className="stack">
|
||
<h1 style={{ fontSize: 'var(--fs-2xl)' }}>{t('profile.title')}</h1>
|
||
<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>
|
||
);
|
||
}
|