مدرسة لوبونتا العالمية

LuBonta Global School

تعليم ذكي لأبنائنا وبناتنا في كل مكان — من تراث العالم إلى مدنه الحديثة، ومن المدرسة إلى الجامعة

١الطالب

٢اختر الصف والمادة والدرس

نسخة اختبار v0.7.4 (بيئة الاختبار فقط). المحتوى التعليمي من إعداد لوبونتا ومبني على أهداف الدروس، ولا يعيد نشر نصوص الكتب المدرسية؛ أسماء الوحدات والدروس مأخوذة من فهارس موثّقة المصدر. لا يُعرض درس على أنه «جاهز» إلا بعد مراجعة مشرف تربوي.

لوبونتا
تقييمشرحتدريباختبارتقرير
استمع إلى المعلّم…
`, 'text/html'); } /* ==== catalog UI (v0.7.0-dev) ==== */ const CAT_COUNTRIES = [['SA','السعودية','Saudi Arabia'],['AE','الإمارات','UAE'],['KW','الكويت','Kuwait'],['QA','قطر','Qatar'],['BH','البحرين','Bahrain'],['OM','عُمان','Oman'],['EG','مصر','Egypt'],['JO','الأردن','Jordan'],['US','الولايات المتحدة','United States'],['GB','المملكة المتحدة','United Kingdom']]; const catCountryName = cc => { const c = CAT_COUNTRIES.find(x => x[0] === cc); return c ? (LANG === 'en' ? c[2] : c[1]) : cc; }; const catCountrySel = (id, sel, extra) => ``; function catCardHTML(c, opts) { opts = opts || {}; const logo = c.logo ? `` : `${c.flag}`; const pill = `${H(c.statusLabel)}`; const btn = opts.preview ? '' : c.canSubscribe ? `` : c.canNotify ? `` : ''; return `
${logo}

${H(c.name)} — ${pill}

${H(c.typeLabel)}${c.owner ? ' · ' + H(c.owner) : ''}
${c.text ? `

${H(c.text)}

` : ''}${btn}${opts.preview ? `

${t('معاينة: هكذا يراها الزائر', 'Preview: this is what visitors see')}

` : ''}
`; } async function catVisitorHTML(u) { const cc = VIEW.catCountry || 'SA', list = await API.catalog.publicList(cc, VIEW.catCity || '', LANG).catch(() => []); return `

${t('المناهج في بلدك', 'Curricula in your country')}

${catCountrySel('catCountry', cc, 'data-chg="catCountry"')}
${list.length ? list.map(c => catCardHTML(c)).join('') : `

${t('لا توجد مناهج معروضة لهذا البلد بعد.', 'No curricula are listed for this country yet.')}

`} ${u ? '' : `

${t('طلب الإشعار لولي الأمر بعد تسجيل الدخول. لا نطلب أي بيانات اتصال من الأطفال.', 'Notification requests are for signed-in parents. We never ask children for contact details.')}

`}
`; } /* ---------------- tabs per role ---------------- */ const TABS = { student: () => [['st_home', t('دراستي', 'My studies')], ['st_rep', t('تقاريري', 'My reports')], ['st_hw', t('واجباتي', 'Homework')], ['st_acc', t('حسابي', 'Account')]], parent: () => [['pa_kids', t('أبنائي', 'My children')], ['pa_rep', t('التقارير', 'Reports')], ['pa_perm', t('الأذونات', 'Permissions')], ['pa_bill', t('الاشتراكات والفواتير', 'Subscriptions & invoices')], ['pa_set', t('الإعدادات', 'Settings')]], teacher: () => [['te_st', t('طلابي المصرّح بهم', 'Authorized students')], ['ac_set', t('حسابي', 'Account')]], school_admin: () => [['sa_school', t('المدرسة', 'School')], ['te_st', t('الطلاب المصرّح بهم', 'Authorized students')], ['ac_set', t('حسابي', 'Account')]], curriculum_supervisor: () => [['cu_tree', t('المناهج والاعتماد', 'Curriculum & approval')], ['cat_admin', t('إدارة المناهج (مشاهدة)', 'Curriculum management (view)')], ['ac_set', t('حسابي', 'Account')]], curriculum_manager: () => [['cat_admin', t('إدارة المناهج', 'Curriculum management')], ['ac_set', t('حسابي', 'Account')]], deputy: () => [['cat_admin', t('إدارة المناهج', 'Curriculum management')], ['ac_set', t('حسابي', 'Account')]], viewer: () => [['cat_admin', t('إدارة المناهج (مشاهدة)', 'Curriculum management (view)')], ['ac_set', t('حسابي', 'Account')]], support: () => [['su_links', t('توثيق أولياء الأمور', 'Guardian verification')], ['su_tk', t('طلبات الدعم والشكاوى', 'Tickets & complaints')], ['cp_tech', t('الحالة التقنية', 'Technical status')], ['ac_set', t('حسابي', 'Account')]], finance: () => [['fi_sum', t('الملخص المالي', 'Financial summary')], ['fi_price', t('التسعير والضريبة', 'Pricing & tax')], ['fi_inv', t('الفواتير والاستردادات', 'Invoices & refunds')], ['fi_exp', t('المصروفات والقسائم', 'Expenses & coupons')], ['ac_set', t('حسابي', 'Account')]], founder: () => [['cp_kpi', t('مؤشرات المؤسس', 'Founder KPIs')], ['cp_edu', t('الإدارة التعليمية', 'Education')], ['fi_sum', t('الإدارة المالية', 'Finance')], ['fi_price', t('التسعير والضريبة', 'Pricing & tax')], ['cp_tech', t('الإدارة التقنية', 'Technical')], ['cp_ops', t('الإدارة التشغيلية', 'Operations')], ['cu_tree', t('اعتماد المحتوى', 'Content approval')], ['cat_admin', t('إدارة المناهج', 'Curriculum management')], ['ac_set', t('حسابي', 'Account')]] }; /* ---------------- views (each loads its own data through API) ---------------- */ const VIEWS = { /* ===== student ===== */ async st_home(u) { const [plan, cr, ws] = await Promise.all([API.school.plan(u.id, { nextLessons: [] }), API.billing.credits(u.id), API.school.weakStrong(u.id)]); return `

${t('أهلًا', 'Welcome')} ${H(u.name)} 👋

${t('بياناتك منفصلة عن بقية الطلاب: دفترك وتقدّمك وأسئلتك لا يراها غيرك. ولي أمرك يرى ملخص تقدّمك وعدد أسئلتك فقط.', 'Your data is separate from other students. Your guardian sees your progress summary and question count only.')}

${t('خطتي الشخصية', 'My personal plan')}

${t('هدف هذا الأسبوع', 'This week')}: ${plan.weekMinutesTarget} ${t('دقيقة', 'min')} · ${t('درستَ', 'studied')} ${plan.weekMinutesLast}

    ${plan.items.map(i => `
  1. ${H(i.text)} ${i.kind === 'review' ? `` : ''}
  2. `).join('')}
${ws.weak.length ? `

${t('مهارات أقوّيها', 'Skills to strengthen')}: ${ws.weak.map(s => `${H(s.label)} ${Math.round(s.ewma * 100)}%`).join(' ')}

` : ''}

${t('رصيد الحصص', 'Session credits')}

${cr.length ? cr.map(c => `

${H(c.packageName)}: ${c.remaining} / ${c.total} ${H(c.status)}

`).join('') : `

${t('لا توجد باقة؛ الحصص في بيئة الاختبار متاحة دون رصيد وتُسجَّل «بلا رصيد».', 'No package; in the test environment lessons still run and are recorded as "no credit".')}

`}
`; }, async st_rep(u) { return `

${t('تقاريري', 'My reports')}

${reportControls(u.id, 'sr')}
${VIEW.lastReport && VIEW.lastReport.student.id === u.id ? reportHTML(VIEW.lastReport) + exportBtns(u.id) : ''}
`; }, async st_hw(u) { const list = await API.homework.list(u.id); return `

${t('واجباتي', 'My homework')}

${list.length ? list.map(h => hwCard(h, true)).join('') : `

${t('لا توجد واجبات. يمكنك طلب تدريب من خطتك الشخصية.', 'No homework. You can request practice from your plan.')}

`}
`; }, async st_acc() { return (await VIEWS._security()) + `

${t('ربط ولي أمر آخر', 'Link another guardian')}

${t('أنشئ رمزًا مؤقتًا (24 ساعة) وأعطه لولي أمرك. يوثّق فريق الدعم صفة الولاية قبل أن يرى أي بيانات.', 'Create a 24-hour code for your guardian. Support verifies guardianship before any data is shown.')}

${t('تغيير كلمة المرور', 'Change password')}

${pwForm()}
`; }, async _security() { const [devs, keys] = await Promise.all([API.auth.devices().catch(() => []), REMOTE ? API.passkeys.list().catch(() => []) : Promise.resolve([])]); const pkOk = REMOTE && window.PublicKeyCredential; const keysHtml = `

${t('الدخول السريع ببصمة الوجه أو مفتاح المرور', 'Quick sign-in with Face ID or a passkey')}

${t('تبقى صورة وجهك وبصمتك على جهازك فقط؛ المدرسة تحفظ مفتاحًا عامًا لا يكشف شيئًا عنك.', 'Your face and fingerprint stay on your device; the school keeps only a public key.')}

${pkOk ? `` : `

${t('متاح عند فتح المدرسة من الرابط الآمن (https) على جهاز يدعم مفاتيح المرور.', 'Available on the secure (https) link on a device that supports passkeys.')}

`} ${keys.length ? `${keys.map(k => ``).join('')}
${t('المفتاح', 'Passkey')}${t('أُضيف', 'Added')}${t('آخر استخدام', 'Last used')}
${H(k.label)}${fmtD(k.created)}${fmtDT(k.lastUsed)}
` : ''}
`; const devHtml = `

${t('الأجهزة المسجّل دخولها', 'Signed-in devices')}

${devs.map(d => ``).join('')}
${t('الجهاز', 'Device')}${t('الطريقة', 'Method')}${t('آخر نشاط', 'Last active')}${t('ينتهي', 'Expires')}
${H(d.device)}${d.current ? ` ${t('هذا الجهاز', 'This device')}` : ''}${d.method === 'passkey' ? t('بصمة / مفتاح مرور', 'Passkey') : t('كلمة مرور', 'Password')}${d.remember ? ' · ' + t('محفوظ', 'remembered') : ''}${fmtDT(d.lastSeen)}${fmtD(d.exp)}${d.current ? '' : ``}
${devs.length > 1 ? `` : ''}

${t('إذا فقدت جهازك ألغِ دخوله من هنا، واحذف مفتاح المرور الخاص به.', 'If you lose a device, sign it out here and remove its passkey.')}

`; const fedList = REMOTE ? await API.federation.list().catch(() => []) : [], fedAll = REMOTE && window.LBS_FED || []; const fedHtml = fedAll.length ? `

${t('الحسابات المرتبطة', 'Linked accounts')}

${t('اربط حسابك مرة واحدة، ثم ادخل بضغطة دون كلمة مرور.', 'Link once, then sign in with one tap.')}

${fedAll.map(p => { const l = fedList.find(x => x.provider === p.id); return `
${H(p.label)}${l ? `${t('مرتبط', 'Linked')}${l.email ? ' · ' + H(l.email) : ''} ` : `${t('ربط', 'Link')}`}
`; }).join('')}
` : ''; return fedHtml + keysHtml + devHtml; }, async ac_set() { return (await VIEWS._security()) + `

${t('تغيير كلمة المرور', 'Change password')}

${pwForm()}

${t('الدعم', 'Support')}

${ticketForm()}
`; }, /* ===== parent ===== */ async pa_kids() { const kids = await API.people.childrenOf(); const rows = await Promise.all(kids.map(async k => { const ok = k.link.status === 'verified'; const [cr, hw] = ok ? await Promise.all([API.billing.credits(k.student.id), API.homework.list(k.student.id)]) : [[], []]; return { k, ok, cr, hw }; })); return `

${t('أبنائي', 'My children')}

${rows.length ? `${rows.map(({ k, ok, cr, hw }) => ``).join('')}
${t('الاسم', 'Name')}${t('الحساب', 'Username')}${t('الولاية', 'Guardianship')}${t('الرصيد', 'Credits')}${t('الواجبات', 'Homework')}
${H(k.student.name)}
${H(gradeName(k.student.grade || ''))}
${H(k.student.username)}${ok ? t('موثّقة', 'Verified') : t('بانتظار التوثيق', 'Pending')} ${cr.filter(c => c.status === 'active').reduce((x, c) => x + c.remaining, 0)}${hw.filter(h => h.status === 'open').length} ${t('مفتوح', 'open')} · ${hw.filter(h => h.status === 'overdue').length} ${t('فائت', 'overdue')} ${ok ? ` ` : ''}
` : `

${t('لا يوجد أبناء مرتبطون بعد.', 'No linked children yet.')}

`}

${t('إضافة ابن أو ابنة', 'Add a child')}

${t('ربط حساب طالب موجود برمز', 'Link an existing student with a code')}

`; }, async pa_rep() { const kids = (await API.people.childrenOf()).filter(k => k.link.status === 'verified'); const sid = VIEW.kid || (kids[0] && kids[0].student.id); if (!kids.length) return `
${t('لا يوجد أبناء موثّقون.', 'No verified children.')}
`; const log = await API.reports.accessLog(sid); return `

${t('تقارير الأبناء', 'Children reports')}

${reportControls(sid, 'pr')}
${VIEW.lastReport && VIEW.lastReport.student.id === sid ? reportHTML(VIEW.lastReport) + exportBtns(sid) : ''}

${t('سجل الاطلاع على بيانات', 'Access log for')} ${H((kids.find(k => k.student.id === sid) || kids[0]).student.name)}

${accessLogTable(log)}
`; }, async pa_perm() { const [kidsAll, gs, dir] = await Promise.all([API.people.childrenOf(), API.people.grantsFor(), API.people.directory()]); const kids = kidsAll.filter(k => k.link.status === 'verified'), rt = RT(); return `

${t('منح إذن اطلاع', 'Grant report access')}

${t('لا يرى المعلم أو المدرسة أي تقرير إلا بإذنك، ولمدة وأنواع تقارير تحددها، ويمكنك سحب الإذن في أي وقت. أسئلة الطالب النصية لا تُشارك أبدًا.', 'Teachers and schools see reports only with your permission, for the period and report types you choose; revoke anytime. The student\'s question texts are never shared.')}

${['daily', 'weekly', 'monthly', 'custom'].map(k => ``).join(' ')}

${t('الأذونات الحالية', 'Current permissions')}

${gs.length ? `${gs.map(g => ``).join('')}
${t('الطالب', 'Student')}${t('الجهة', 'Grantee')}${t('التقارير', 'Reports')}${t('ينتهي', 'Expires')}${t('الحالة', 'Status')}
${H(g.student)}${H(g.grantee)}${g.reportTypes.map(k => rt[k]).join('، ')}${fmtD(g.expiresAt)}${g.active ? t('فعّال', 'Active') : g.revokedAt ? t('مسحوب', 'Revoked') : t('منتهٍ', 'Expired')}${g.active ? `` : ''}
` : `

${t('لا توجد أذونات.', 'No permissions.')}

`}
`; }, async pa_bill() { return (await catVisitorHTML(ME)) + (await VIEWS.pa_bill0()); }, async pa_bill0() { const [kidsAll, book, inv] = await Promise.all([API.people.childrenOf(), API.billing.priceBook(VIEW.country || 'SA'), API.billing.myInvoices()]); const kids = kidsAll.filter(k => k.link.status === 'verified'); const credits = await Promise.all(kids.map(k => API.billing.credits(k.student.id))); return `

${t('شراء باقة', 'Buy a package')}

${book ? `

${book.approvedPrices ? '' : '' + t('أسعار مرجعية غير معتمدة', 'Reference prices, not approved') + ' '}${book.taxReviewed ? '' : '' + t('المعالجة الضريبية بانتظار المراجعة — لا تُضاف ضريبة تلقائيًا، والمستند فاتورة مبدئية', 'Tax treatment awaiting review — no tax added automatically; document is a proforma') + ''}

${kids.map(k => ``).join(' ')}
` : `

${t('لا توجد باقات لهذه الدولة بعد.', 'No packages for this country yet.')}

`}

${t('الفواتير والإيصالات', 'Invoices & receipts')}

${invoiceTable(inv, 'parent')}

${t('الحصص المستهلكة والمتبقية', 'Sessions used and remaining')}

${kids.map((k, i) => credits[i].map(c => `

${H(k.student.name)} — ${H(c.packageName)}: ${t('مستخدم', 'used')} ${c.used} · ${t('متبقٍ', 'left')} ${c.remaining} ${H(c.status)}

`).join('')).join('') || '

—

'}
`; }, async pa_set(u) { const pr = u.prefs || { edu: true, fin: true }; const kids = (await API.people.childrenOf()).filter(k => k.link.status === 'verified'); return (await VIEWS._security()) + `

${t('التنبيهات', 'Notifications')}


${t('تظهر التنبيهات داخل التطبيق. الإرسال المجدول بالبريد أو الرسائل يُفعَّل لاحقًا بعد موافقتك وربط خدمة إرسال.', 'Alerts show in the app. Scheduled email/SMS comes later after your approval and a sending service.')}

${await alertsFor(kids)}

${t('حذف بيانات ابن', 'Delete a child\'s data')}

${t('يحذف النشاط والتقارير والواجبات والمهارات ويُسحب كل إذن. تبقى الفواتير لأنها سجل نظامي.', 'Deletes activity, reports, homework and skills; revokes all grants. Invoices remain as a legal record.')}

${t('الدعم', 'Support')}

${ticketForm()}

${t('تغيير كلمة المرور', 'Change password')}

${pwForm()}
`; }, /* ===== teacher / school ===== */ async te_st(u) { const gs = (await API.people.grantsFor()).filter(g => g.active); const sid = VIEW.kid || (gs[0] && gs[0].studentId), rt = RT(); if (!gs.length) return `

${t('لا يوجد طلاب مصرّح لك بهم', 'No authorized students')}

${t('يظهر الطالب هنا فقط عندما يمنحك ولي أمره إذنًا، ولمدة محددة.', 'A student appears here only when the guardian grants you access for a set period.')}

`; const g = gs.find(x => x.studentId === sid) || gs[0]; return `

${t('الطلاب', 'Students')}

${gs.map(x => ``).join('')}
${t('الطالب', 'Student')}${t('التقارير المسموحة', 'Allowed reports')}${t('ينتهي الإذن', 'Expires')}
${H(x.student)}${x.reportTypes.map(k => rt[k]).join('، ')}${fmtD(x.expiresAt)}

${H(g.student)}

${reportControls(g.studentId, 'tr')}
${VIEW.lastReport && VIEW.lastReport.student.id === g.studentId ? reportHTML(VIEW.lastReport) + exportBtns(g.studentId) : ''}
${u.role === 'teacher' && g.reportTypes.includes('weekly') ? `
` : ''}
`; }, async sa_school() { const [schools, users] = await Promise.all([API.people.listSchools(), API.people.listUsers()]); const s = schools[0], staff = users.filter(x => x.role === 'teacher' || x.role === 'school_admin'); return `

${H(s ? s.name : '—')}

${staff.map(x => ``).join('')}
${t('الاسم', 'Name')}${t('الدور', 'Role')}
${H(x.name)}${ROLE(x.role)}

${t('إضافة معلّم', 'Add a teacher')}

${t('ترى إدارة المدرسة تقارير الطلاب الذين منح أولياء أمورهم المدرسة إذنًا فقط. بيانات كل مدرسة منفصلة عن غيرها.', 'The school sees reports only for students whose guardians granted the school access. Each school\'s data is separate.')}

`; }, /* ===== curriculum ===== */ async cat_admin(u) { const [list, stats, dels] = await Promise.all([API.catalog.list(), API.catalog.interestStats().catch(() => []), u.role === 'founder' ? API.catalog.delegations() : Promise.resolve({})]); const L = s => ({ draft: t('قيد التجهيز', 'In preparation'), soon: t('قريبًا', 'Coming soon'), active: t('متاح', 'Available'), paused: t('موقوف', 'Paused'), archived: t('مؤرشف', 'Archived') }[s] || s); const TY = { national: t('وطني', 'National'), international: t('دولي', 'International'), private_school: t('مدرسة خاصة', 'Private school'), school_group: t('مجموعة مدارس', 'School group'), custom_program: t('برنامج مخصص', 'Custom program') }; const ro = u.role === 'viewer' || u.role === 'curriculum_supervisor'; const sel = VIEW.catSel && list.find(c => c.key === VIEW.catSel); const statusSel = (a) => ro ? `${H(L(a.status))}` : ``; const where = a => a.scope === 'global' ? t('عالمي', 'Global') : a.scope === 'country' ? catCountryName(a.country) : a.scope === 'city' ? catCountryName(a.country) + ' · ' + H(a.city) : t('مدرسة', 'School') + ' · ' + H(a.schoolId); const form = c => `

${c ? t('تعديل المنهج', 'Edit curriculum') + ': ' + H(c.key) : t('إضافة منهج جديد', 'Add a new curriculum')}

${c ? '' : ``}

${t('بلد المنشأ والجهة المالكة منفصلان عن دول العرض. إضافة منهج لا تحتاج أي تعديل برمجي.', 'Origin and owning body are separate from where it is shown. Adding a curriculum needs no code change.')}

`; const detail = c => { const rows = c.availability.map(a => `${where(a)}${statusSel(a)}${fmtD(a.at)}`).join(''); return `

${t('الإتاحة حسب الدولة والمدينة والمدرسة', 'Availability by country, city and school')} — ${H(c.name.ar || c.name.en)}

${rows || ``}
${t('النطاق', 'Scope')}${t('الحالة', 'Status')}${t('آخر تغيير', 'Changed')}
${t('لا توجد إتاحة بعد', 'No availability yet')}
${ro ? '' : `
${catCountrySel('avCountry', 'SA')}

${t('«متاح» يُفعَّل من القائمة أعلاه بعد استيفاء الجاهزية (دروس معتمدة + بطاقة أسعار معتمدة) وبصلاحية الإتاحة العامة.', '“Available” is set in the list above once ready (approved lessons + approved rate card) and by someone allowed to publish.')}

`}

${t('معاينة البطاقة', 'Card preview')}

${catCountrySel('pvCountry', VIEW.pvCountry || 'SA', 'data-chg="catPv"')}
${VIEW.pv ? catCardHTML(VIEW.pv, { preview: true }) : ''}
${VIEW.hist ? `${VIEW.hist.map(e => ``).join('')}
${fmtDT(e.at)}${H(e.action)}${H(e.role)}${H(JSON.stringify(e.meta))}
` : ''}
`; }; const statsHtml = stats.length ? `${stats.map(s => ``).join('')}
${t('المنهج', 'Curriculum')}${t('الدولة', 'Country')}${t('المدينة', 'City')}${t('زوار مهتمون', 'Interested visitors')}${t('طلبات إشعار', 'Notify requests')}
${H(s.curriculum)}${H(catCountryName(s.country))}${H(s.city || '—')}${H(s.visitors)}${H(s.notify)}

${t('الأعداد الأقل من 5 تظهر «<5» حفاظًا على الخصوصية.', 'Counts under 5 show as “<5” for privacy.')}

` : `

${t('لا يوجد مهتمون بعد.', 'No interest yet.')}

`; const delHtml = u.role !== 'founder' ? '' : `

${t('تفويض النواب ومديري المناهج', 'Delegations')}

${Object.keys(dels).length ? `${Object.entries(dels).map(([id, d]) => ``).join('')}
${H(id)}${d.edit ? '✓ ' + t('تعديل', 'edit') : ''} ${d.status ? '✓ ' + t('حالة', 'status') : ''} ${d.publish ? '✓ ' + t('إتاحة', 'publish') : ''}${H((d.countries || []).join(', ') || t('كل الدول', 'all'))}
` : ''}
`; return `

${t('إدارة المناهج', 'Curriculum management')}

${list.map(c => ``).join('') || ``}
${t('المنهج', 'Curriculum')}${t('النوع', 'Type')}${t('المنشأ', 'Origin')}${t('الإتاحة', 'Availability')}
${H(c.name.ar || c.name.en)}
${H(c.key)}
${H(TY[c.type] || c.type)}${H(c.originCountry || '—')}${c.availability.map(a => `${where(a)}: ${H(L(a.status))}`).join(' ') || '—'}
${t('لا توجد مناهج بعد', 'No curricula yet')}
${ro ? `

${t('صلاحيتك مشاهدة فقط.', 'You have view-only access.')}

` : ''}
${ro ? '' : form(sel)}${sel ? detail(sel) : ''}

${t('المهتمون حسب الدولة والمدينة', 'Interest by country and city')}

${statsHtml}
${delHtml}`; }, async cu_tree(u) { const path = VIEW.path || [], cur = path.length ? path[path.length - 1] : null; const [kids, counts, crumbs] = await Promise.all([API.curriculum.children(cur), API.curriculum.statusCounts(cur || undefined), cur ? API.curriculum.path(cur) : []]); kids.sort((x, y) => String(x.id).localeCompare(String(y.id), 'ar', { numeric: true })); const lab = LB.STATUS_LABEL[LANG] || LB.STATUS_LABEL.ar, total = Object.values(counts.counts).reduce((a, b) => a + b, 0); const bc = [`${t('الدول', 'Countries')}`].concat(crumbs.map((n, i) => `${H(n.name)}`)).join(' › '); return `

${t('سجل المناهج ومسار الاعتماد', 'Curriculum registry & approval')}

${bc}
${LB.LESSON_STATUSES.map(s => `
${lab[s]}${counts.counts[s]}
`).join('')}
${t('مطابقة رسمية موثّقة', 'Verified official match')}${counts.official}
${!cur ? `` : ''} ${crumbs.some(n => n.type === 'grade') && crumbs.length ? '' : ''} ${kids.map(n => n.type === 'lesson' ? lessonRow(n, lab, u) : ``).join('')}
${t('العنصر', 'Item')}${t('النوع', 'Type')}${t('الحالة', 'Status')}
${H(n.name)}${n.meta && n.meta.placeholder ? ' ' + t('الهيكل جاهز — لا محتوى بعد', 'Framework only — no content yet') + '' : ''}${n.meta && n.meta.note ? ' ' + H(n.meta.note) + '' : ''}${H(n.type)}

${t('لا يُعتبر الدرس مطابقًا رسميًا للمنهج إلا بعد توثيق مصدره من مشرف ومراجعته تربويًا. الفهارس الحالية منقولة من مواقع غير رسمية وتحتاج مطابقة مع منصة مدرستي/عين.', 'A lesson is never treated as officially matching until a supervisor verifies its source and it passes educational review. Current indexes come from unofficial mirrors and need matching against Madrasati/Ein.')}

`; }, /* ===== support ===== */ async su_links() { const pl = await API.people.pendingLinks(); return `

${t('طلبات ربط بانتظار التوثيق', 'Links awaiting verification')}

${pl.length ? `${pl.map(l => ``).join('')}
${t('ولي الأمر', 'Parent')}${t('الطالب', 'Student')}${t('التاريخ', 'Date')}${t('وسيلة التحقق', 'Evidence')}
${H(l.parent)}${H(l.student)}${fmtD(l.at)}
` : `

${t('لا توجد طلبات.', 'No requests.')}

`}
`; }, async su_tk() { const tk = await API.support.list(); return `

${t('طلبات الدعم والشكاوى', 'Tickets & complaints')}

${tk.length ? `${tk.map(x => ``).join('')}
${t('النوع', 'Kind')}${t('الموضوع', 'Subject')}${t('من', 'From')}${t('الحالة', 'Status')}${t('الرد', 'Reply')}
${x.kind === 'complaint' ? t('شكوى', 'Complaint') : t('دعم', 'Support')}${H(x.subject)}
${H(x.body)}${x.replies.map(r => `
↩ ${H(r.text)}
`).join('')}
${ROLE(x.byRole)}${H(x.status)}
` : `

—

`}
`; }, /* ===== finance ===== */ async fi_sum() { const p = periodFromView('fs'), cur = VIEW.cur || 'SAR', [r, tb] = await Promise.all([API.billing.report({ ...p, currency: cur }), API.billing.trialBalanceFor()]), u = ['KWD', 'BHD', 'OMR', 'JOD'].includes(cur) ? 1000 : 100; return `

${t('الملخص المالي', 'Financial summary')} ${t('تجريبي', 'Sandbox')}

${periodPicker('fs')}
${[[t('الفواتير الصادرة', 'Invoices issued'), r.invoicesIssued], [t('المحصّل', 'Collected'), money(r.collectedMinor, cur, u)], [t('الاستردادات', 'Refunds'), money(r.refundsMinor, cur, u)], [t('الإيراد الصافي (دون ضريبة)', 'Net revenue (ex. tax)'), money(r.revenueNetMinor, cur, u)], [t('الضريبة المحصّلة', 'Tax collected'), money(r.taxCollectedMinor, cur, u)], [t('مستحقات غير مدفوعة', 'Outstanding'), money(r.outstandingMinor, cur, u)], [t('المصروفات التشغيلية', 'Operating expenses'), money(r.expensesMinor, cur, u)], [t('تكلفة الذكاء الاصطناعي', 'AI cost'), '$' + r.aiCostUsd], [t('الحصص المستهلكة', 'Sessions consumed'), r.sessionsConsumed], [t('تكلفة الذكاء لكل حصة', 'AI cost per session'), r.aiCostPerSessionUsd == null ? '—' : '$' + r.aiCostPerSessionUsd], [t('الربح التقديري', 'Estimated profit'), money(r.profitEstimateMinor, cur, u)]].map(([k, v]) => `
${k}${v}
`).join('')}

${H(r.fxNote)} · ${t('ميزان المراجعة', 'Trial balance')}: ${Object.entries(tb).map(([c, x]) => `${c} ${x.dr === x.cr ? '✓ ' + t('متوازن', 'balanced') : '✗'}`).join(' · ') || '—'} · ${t('تكلفة الذكاء الاصطناعي تقديرية من عدد الاستدعاءات.', 'AI cost is estimated from call counts.')}

`; }, async fi_price(u) { const c = VIEW.country || 'SA', [card, book, rule] = await Promise.all([API.billing.rateCard(c), API.billing.priceBook(c), API.billing.taxRule(c)]), tax = LB.DEFAULT_TAX[c], unit = tax.minor || 100; const q = VIEW.quote; const tr = { standard: t('ضريبة قياسية', 'Standard rate'), zero: t('نسبة صفر', 'Zero-rated'), exempt: t('معفى', 'Exempt'), unreviewed: t('بانتظار المراجعة — لا تُطبَّق', 'Awaiting review — not applied') }; return `

${t('محرك التسعير', 'Pricing engine')}

${tax.currency} ${card ? `${card.approved ? t('أسعار معتمدة', 'Approved prices') : t('أسعار مرجعية غير معتمدة', 'Reference prices, not approved')}` : ''}

${t('سعر الطالب في الساعة حسب حجم المجموعة', 'Price per student-hour by group size')}

${(card ? card.rates : []).slice().sort((a, b) => a.groupSize - b.groupSize).map(r => ``).join('')}
${t('حجم المجموعة (من)', 'Group size (from)')}${t('السعر للطالب/ساعة', 'Per student-hour')}
${r.groupSize}${money(r.perStudentHourMinor, tax.currency, unit)}
${u.role === 'founder' && card && !card.approved ? `` : ''}
${card && card.note ? `

${H(card.note)}

` : ''}

${t('حاسبة السعر', 'Price calculator')}

${q ? `

${t('سعر الطالب للحصة', 'Per student per session')}: ${money(q.perStudentSessionMinor, q.currency, q.minor)} (${t('شريحة', 'tier')} ${q.tierGroupSize}) · ${t('الإجمالي للطالب', 'Total per student')}: ${money(q.netMinor, q.currency, q.minor)} · ${t('الضريبة', 'Tax')}: ${q.taxStatus === 'pending_review' ? t('غير مطبّقة — بانتظار المراجعة', 'not applied — awaiting review') : money(q.taxMinor, q.currency, q.minor)}

` : ''}

${t('الباقات الحالية', 'Current packages')}

${(book ? book.packages : []).map(p => ``).join('')}
${t('الباقة', 'Package')}${t('الحصص', 'Sessions')}${t('السعر', 'Price')}${t('المدة', 'Days')}
${H(p.name)}${p.sessions}${money(p.priceMinor, tax.currency, unit)}${p.days}

${t('المعالجة الضريبية للتعليم', 'Tax treatment for education')}

${t('الحالية', 'Current')}: ${tr[rule.treatment]} ${rule.treatment === 'standard' ? Math.round(rule.rate * 100) + '%' : ''} ${rule.reference ? '· ' + H(rule.reference) : ''}

${t('ما لم تُراجَع المعالجة الضريبية لا تُضاف أي ضريبة تلقائيًا، ويصدر المستند «فاتورة مبدئية». النسبة الافتراضية للمملكة 15% محفوظة للمرجع فقط.', 'Until the tax treatment is reviewed, no tax is added automatically and documents are proformas. The default Saudi 15% is kept for reference only.')}

`; }, async fi_inv() { const inv = await API.billing.listInvoices(); return `

${t('الفواتير', 'Invoices')}

${invoiceTable(inv, 'finance')}
`; }, async fi_exp(u) { const [ex, cps] = await Promise.all([API.billing.listExpenses(), API.billing.listCoupons()]); return `

${t('المصروفات التشغيلية', 'Operating expenses')}

${ex.map(e => ``).join('')}
${t('التاريخ', 'Date')}${t('البند', 'Category')}${t('المبلغ', 'Amount')}${t('ملاحظة', 'Note')}
${fmtD(e.at)}${H(e.category)}${money(e.amountMinor, e.currency)}${H(e.note)}

${t('القسائم', 'Coupons')}

${cps.map(c => ``).join('')}
${t('الرمز', 'Code')}${t('الخصم', 'Discount')}${t('مستخدم', 'Used')}${t('الحالة', 'Status')}
${H(c.code)}${c.percent ? c.percent + '%' : money(c.amountMinor)}${c.used}/${c.maxUses}${c.status === 'approved' ? t('معتمدة', 'Approved') : t('بانتظار اعتماد المؤسس', 'Awaiting founder')}${u.role === 'founder' && c.status !== 'approved' ? `` : ''}
`; }, /* ===== founder control panel ===== */ async cp_kpi() { const p = periodFromView('kp'), k = await API.kpi.founder({ ...p, currency: 'SAR' }), lab = LB.STATUS_LABEL[LANG] || LB.STATUS_LABEL.ar, mx = Math.max(1, ...k.series.map(s => s.sessions)); return `

${t('مؤشرات المؤسس', 'Founder KPIs')}

${periodPicker('kp')}
${[[t('عدد الطلاب', 'Students'), k.students], [t('الطلاب النشطون', 'Active students'), k.activeStudents], [t('الحصص المنفذة', 'Sessions run'), k.sessions], [t('الدروس المكتملة', 'Lessons completed'), k.lessonsCompleted], [t('نسبة إكمال الدروس', 'Lesson completion'), k.completionRatePct == null ? '—' : k.completionRatePct + '%'], [t('جودة التعليم (متوسط الاختبارات)', 'Quality (quiz average)'), k.qualityQuizAvgPct == null ? '—' : k.qualityQuizAvgPct + '%'], [t('دقائق التعلّم', 'Learning minutes'), k.minutes], [t('أسئلة الطلاب', 'Student questions'), k.questions], [t('الإيرادات الصافية', 'Net revenue'), money(k.revenueNetMinor, 'SAR')], [t('التكلفة', 'Cost'), money(k.costMinor, 'SAR')], [t('الربح التقديري', 'Est. profit'), money(k.profitEstimateMinor, 'SAR')], [t('أولياء الأمور', 'Parents'), k.parents], [t('المعلمون', 'Teachers'), k.teachers], [t('المدارس', 'Schools'), k.schools], [t('طلبات دعم مفتوحة', 'Open tickets'), k.openTickets]].map(([l, v]) => `
${l}${v}
`).join('')}

${t('الحصص يوميًا', 'Sessions per day')}

${k.series.length ? `
${k.series.map(s => `
${s.sessions}
`).join('')}
` : `

${t('لا توجد حصص في الفترة.', 'No sessions in period.')}

`}

${t('حالة الدروس', 'Lesson status')}

${LB.LESSON_STATUSES.map(s => `${lab[s]}: ${k.lessonStatus.counts[s]}`).join(' ')}

${t('المؤشرات مجمّعة دون أسماء أو بيانات شخصية. الإيرادات من عمليات تجريبية فقط.', 'Aggregated, no names or personal data. Revenue comes from sandbox operations only.')}

`; }, async cp_edu() { const [users, schools] = await Promise.all([API.people.listUsers(), API.people.listSchools()]), by = r => users.filter(x => x.role === r).length; return `

${t('الإدارة التعليمية', 'Education management')}

${LB.ROLES.map(r => `
${ROLE(r)}${by(r)}
`).join('')}

${t('الحسابات', 'Accounts')}

${users.map(x => ``).join('')}
${t('الاسم', 'Name')}${t('الدور', 'Role')}${t('اسم المستخدم', 'Username')}${t('أُنشئ', 'Created')}
${x.role === 'student' ? '' + t('طالب (الاسم مخفي)', 'Student (name hidden)') + '' : H(x.name)}${ROLE(x.role)}${x.role === 'student' ? '•••' : H(x.username)}${fmtD(x.createdAt)}${x.role !== 'founder' ? `` : ''}

${t('إنشاء حساب بكلمة مرور مؤقتة فريدة', 'Create an account with a unique temporary password')}

${t('مدرسة جديدة', 'New school')}

${t('اطلاع على تقرير طالب (يتطلب سببًا ويُسجَّل)', 'View a student report (reason required, logged)')}

`; }, async cp_tech() { const k = await API.kpi.tech({ server: REMOTE ? t('متصل — خادم الاختبار المركزي', 'Connected — central test server') : t('غير متصل — نموذج محلي على الجهاز', 'Not connected — local device model') }); const ai = (typeof AI !== 'undefined' && AI.provider) || '—'; return `

${t('الإدارة التقنية', 'Technical')}

${[[t('الخادم', 'Server'), k.server], [t('مزوّد الذكاء الاصطناعي الحالي', 'Current AI provider'), ai], [t('استدعاءات الذكاء المسجّلة', 'AI calls recorded'), k.aiCalls], [t('الأحداث المخزنة', 'Stored events'), k.events], [t('حجم قاعدة البيانات', 'Database size'), Math.round((k.storageBytes || 0) / 1024) + ' KB'], [t('أخطاء آخر 24 ساعة', 'Errors last 24h'), k.errors24h], [t('سجل التدقيق', 'Audit log'), k.auditEntries + ' · ' + (k.auditChain.ok ? '✓ ' + t('سليم', 'intact') : '✗ ' + t('معدّل عند', 'broken at') + ' ' + k.auditChain.brokenAt)], [t('الوضع', 'Mode'), k.mode]].map(([l, v]) => `
${l}${H(v)}
`).join('')}
${k.lastErrors.length ? `

${t('آخر الأخطاء', 'Latest errors')}

${k.lastErrors.map(e => ``).join('')}
${fmtDT(e.at)}${H(e.source)}${H(e.message)}
` : ''}
`; }, async cp_ops() { const log = (await API.data.auditLog({ limit: 120 })).reverse(); return `

${t('سجل التدقيق', 'Audit log')}

${REMOTE ? '' : ``}
${REMOTE ? `

${t('النسخ الاحتياطي على الخادم يومي وتلقائي (الساعة 02:40)، ويُحفظ 14 يومًا مع بصمة تحقق. الاستعادة عبر أمر على الخادم فقط.', 'Server backups run daily (02:40), kept 14 days with checksums. Restore is a server-side command only.')}

` : ''} ${log.map(e => ``).join('')}
#${t('الوقت', 'Time')}${t('الدور', 'Role')}${t('العملية', 'Action')}${t('الهدف', 'Target')}
${e.seq}${fmtDT(e.at)}${ROLE(e.role)}${H(e.action)}${H(e.target || '')} ${e.meta ? H(JSON.stringify(e.meta)).slice(0, 80) : ''}
`; } }; /* ---------------- small builders ---------------- */ function exportBtns(sid) { return `
`; } function hwCard(h, solve) { const st = { open: ['', t('مفتوح', 'Open')], overdue: ['r', t('فائت الموعد', 'Overdue')], done: ['', t('مكتمل', 'Done')], late: ['o', t('سُلّم متأخرًا', 'Late')] }[h.status]; return `
${H(h.title)} ${st[1]} ${t('التسليم', 'Due')} ${fmtD(h.dueAt)}${h.score != null ? ' · ' + h.score + '/' + h.of : ''} ${solve && h.items && !h.submittedAt ? `
${h.items.map((it, i) => `
${i + 1}. ${H(it.prompt)} ${it.options ? `` : ``}
`).join('')}
` : ''}
`; } function invoiceTable(inv, who) { if (!inv.length) return `

—

`; return `${inv.map(i => { const p = i.payment; return ``; }).join('')}
${t('الرقم', 'No.')}${t('التاريخ', 'Date')}${t('الإجمالي', 'Total')}${t('الضريبة', 'Tax')}${t('الحالة', 'Status')}
${H(i.no)}${fmtD(i.issuedAt)}${money(i.totalMinor, i.currency, i.minor)}${i.taxStatus === 'pending_review' ? '' + t('بانتظار المراجعة', 'pending review') + '' : money(i.taxMinor, i.currency, i.minor)}${H(i.status)} ${H(i.mode)}${i.docType === 'proforma' ? ' ' + t('مبدئية', 'proforma') + '' : ''} ${who === 'parent' && i.status === 'issued' ? `` : ''} ${who === 'finance' && p && (p.refundedMinor || 0) < p.amountMinor ? `` : ''}
`; } function invoiceHTML(i) { return `

${i.docType === 'proforma' ? t('فاتورة مبدئية', 'Proforma invoice') : i.status === 'paid' ? t('إيصال دفع', 'Payment receipt') : t('فاتورة', 'Invoice')} ${H(i.no)}

${t('مدرسة لوبونتا الذكية — بيئة اختبار، ليست فاتورة ضريبية نظامية', 'LuBonta AI School — test environment, not a statutory tax invoice')}
${i.lines.map(l => ``).join('')}
${t('البيان', 'Item')}${t('المبلغ', 'Amount')}
${H(l.desc)}${money(l.unitMinor, i.currency, i.minor)}
${t('الخصم', 'Discount')} ${i.coupon ? '(' + H(i.coupon) + ')' : ''}− ${money(i.discountMinor, i.currency, i.minor)}
${t('الضريبة', 'Tax')}${i.taxStatus === 'pending_review' ? t('غير مطبّقة — المعالجة الضريبية بانتظار المراجعة', 'Not applied — tax treatment awaiting review') : money(i.taxMinor, i.currency, i.minor) + ' (' + Math.round(i.taxRate * 100) + '%)'}
${t('الإجمالي', 'Total')}${money(i.totalMinor, i.currency, i.minor)}
${t('المدفوع', 'Paid')}${money(i.paidMinor, i.currency, i.minor)}
${t('المسترد', 'Refunded')}${money(i.refundedMinor, i.currency, i.minor)}

${t('تاريخ الإصدار', 'Issued')}: ${fmtDT(i.issuedAt)}${i.paidAt ? ' · ' + t('تاريخ الدفع', 'Paid') + ': ' + fmtDT(i.paidAt) : ''}. ${i.approvedPrices ? '' : t('الأسعار مرجعية غير معتمدة.', 'Prices are unapproved reference prices.')}

`; } function accessLogTable(log) { log = log.slice().reverse().slice(0, 30); return log.length ? `${log.map(e => ``).join('')}
${t('الوقت', 'Time')}${t('من', 'Who')}${t('العملية', 'Action')}
${fmtDT(e.at)}${H(e.by)} ${ROLE(e.role)}${H(e.action)}${e.meta && e.meta.type ? ' · ' + H(e.meta.type) : ''}
` : '

—

'; } async function alertsFor(kids) { const out = []; for (const k of kids) { const [hw, cr] = await Promise.all([API.homework.list(k.student.id), API.billing.credits(k.student.id)]); const od = hw.filter(h => h.status === 'overdue').length; if (od) out.push(`⚠️ ${H(k.student.name)}: ${od} ${t('واجب فائت الموعد', 'overdue homework')}`); const act = cr.filter(c => c.status === 'active'); if (act.length && act.reduce((x, c) => x + c.remaining, 0) <= 1) out.push(`💳 ${H(k.student.name)}: ${t('الرصيد قارب على النفاد', 'credits almost used up')}`); } const unpaid = (await API.billing.myInvoices()).filter(i => i.status === 'issued').length; if (unpaid) out.push(`🧾 ${unpaid} ${t('فاتورة غير مدفوعة', 'unpaid invoice(s)')}`); return out.length ? `

${t('التنبيهات الحالية', 'Current alerts')}

` : ''; } function ticketForm() { return `
`; } function pwForm() { return `
`; } function gradeName(id) { try { for (const s of CURRIC.stages) for (const g of s.grades) if (g.id === id) return g.name; } catch (e) {} return id; } function gradeOptions() { if (typeof CURRIC === 'undefined') return ''; return CURRIC.stages.map(s => s.grades.map(g => ``).join('')).join(''); } function lessonRow(n, lab, u) { const i = LB.LESSON_STATUSES.indexOf(n.status), next = LB.LESSON_STATUSES[i + 1]; const need = { content_entered: t('مرجع المحتوى', 'content ref'), tech_tested: t('رقم سجل الاختبار', 'test run id'), pedagogy_reviewed: t('ملاحظات المراجعة', 'review notes') }[next]; return `${H(n.name)} ${n.official && n.official.verified ? '' + t('مطابق رسميًا', 'Official match') + '' : '' + t('مطابقة رسمية غير موثّقة', 'Official match unverified') + ''}lesson${lab[n.status]} ${next ? `${need ? `` : ''}` : ''} ${u.role === 'curriculum_supervisor' && !(n.official && n.official.verified) ? ` ` : ''}`; } function periodPicker(pfx) { const p = VIEW[pfx + 'P'] || 'month'; return `
${['day', 'week', 'month', 'custom'].map(k => ``).join('')} ${p === 'custom' ? `` : ''}
`; } function periodFromView(pfx) { const p = VIEW[pfx + 'P'] || 'month', n = Date.now(); if (p === 'day') return PURE.period('daily', n); if (p === 'week') return PURE.period('weekly', n); if (p === 'month') return PURE.period('monthly', n); const f = Date.parse(VIEW[pfx + 'F']), to = Date.parse(VIEW[pfx + 'T']) + DAY; return f < to ? { from: f, to } : PURE.period('monthly', n); } function showNewPassword(username, pw) { const box = document.getElementById('newPw'); if (!box) return; box.innerHTML = `
${H(username)} — ${t('كلمة المرور المؤقتة (تظهر مرة واحدة، ويُطلب تغييرها عند أول دخول)', 'temporary password (shown once; must be changed at first sign-in)')}: ${H(pw)}
`; } /* ---------------- actions ---------------- */ const ACT = { /* ---- catalog (v0.7.0-dev) ---- */ async catOpen(d) { VIEW.catSel = d.key; VIEW.pv = null; VIEW.hist = null; return render(); }, async catSave(d) { const o = { name: { ar: val('caNameAr'), en: val('caNameEn') }, type: val('caType'), originCountry: val('caOrigin').toUpperCase() || null, owner: { name: val('caOwner') }, language: val('caLang'), version: val('caVer') }; if (d.key) await API.catalog.update(d.key, o); else { const c = await API.catalog.create({ key: val('caKey'), ...o }); VIEW.catSel = c.key; } toastx(t('حُفظ', 'Saved')); return render(); }, async catAvail(d) { const scope = val('avScope'); await API.catalog.setAvailability(d.key, { scope, country: val('avCountry'), city: val('avCity'), schoolId: val('avSchool'), status: val('avStatus') }); toastx(t('أُضيفت الإتاحة', 'Availability added')); return render(); }, async catAvailStatus(d, el) { try { await API.catalog.setAvailability(d.key, { scope: d.scope, country: d.country || undefined, city: d.city || undefined, schoolId: d.school || undefined, status: el.value }); toastx(t('تغيّرت الحالة', 'Status changed')); } finally { render(); } }, async catPreview(d) { VIEW.pvCountry = val('pvCountry'); VIEW.pv = await API.catalog.preview(d.key, { country: VIEW.pvCountry, lang: LANG }); return render(); }, async catPv(d, el) { VIEW.pvCountry = el.value; }, async catHistory(d) { VIEW.hist = await API.catalog.history(d.key); return render(); }, async catLogo(d) { const f = document.getElementById('caLogo').files[0]; if (!f) throw new Error(t('اختر صورة', 'Choose an image')); const data = await new Promise((ok, no) => { const r = new FileReader(); r.onload = () => ok(String(r.result).split(',')[1]); r.onerror = no; r.readAsDataURL(f); }); await API.catalog.uploadLogo(d.key, { mime: f.type, data, source: val('caLogoSrc'), rights: val('caLogoRights') }); toastx(t('رُفع الشعار', 'Logo uploaded')); return render(); }, async catDelegate() { await API.catalog.delegate(val('dgUser'), { edit: document.getElementById('dgEdit').checked, status: document.getElementById('dgStatus').checked, publish: document.getElementById('dgPub').checked, countries: val('dgCountries').split(',').map(s => s.trim().toUpperCase()).filter(Boolean) }); toastx(t('حُفظ التفويض', 'Delegation saved')); return render(); }, async catCountry(d, el) { VIEW.catCountry = el.value; return render(); }, async catNotify(d) { const u = await me(), cc = VIEW.catCountry || 'SA'; if (u && u.role === 'parent') { if (!confirm(t('أوافق على حفظ طلب إشعاري بهذا المنهج، ويمكنني إلغاؤه في أي وقت.', 'I agree to store my notification request for this curriculum; I can cancel it at any time.'))) return; await API.catalog.notifyMe(d.key, { country: cc, consent: true }); toastx(t('سنبلغك عند توفره. يمكنك الإلغاء من نفس المكان.', 'We will notify you. You can cancel here.')); return; } await API.catalog.interest(d.key, cc, '').catch(() => null); toastx(t('سُجّل اهتمامك دون أي بيانات شخصية. لتلقي إشعار، يسجّل ولي الأمر الدخول ثم يضغط الزر.', 'Your interest was counted with no personal data. To get a notification, a parent signs in and presses the button.')); }, async catSubscribe() { TAB = 'pa_bill'; return render(); }, close, lang() { LANG = LANG === 'ar' ? 'en' : 'ar'; try { localStorage.setItem('lbs_lang', LANG) } catch (e) {} return render(); }, async login() { const rm = document.getElementById('scRemember'); const r = await API.auth.login(val('scUser'), document.getElementById('scPass').value, { remember: !rm || rm.checked }); return afterLogin(r); }, async passkeyLogin() { const o = await API.passkeys.loginOptions(); let c; try { c = await navigator.credentials.get({ publicKey: { challenge: unb64(o.challenge), rpId: o.rpId, userVerification: o.userVerification, timeout: o.timeout, allowCredentials: [] } }); } catch (e) { throw new Error(t('أُلغي الدخول بالبصمة أو لا يوجد مفتاح مرور لهذه المدرسة على الجهاز.', 'Passkey sign-in was cancelled or no passkey exists on this device.')); } const r = await API.passkeys.login({ id: c.id, response: { clientDataJSON: b64(c.response.clientDataJSON), authenticatorData: b64(c.response.authenticatorData), signature: b64(c.response.signature), userHandle: c.response.userHandle ? b64(c.response.userHandle) : null } }); return afterLogin(r); }, async passkeyAdd() { const o = await API.passkeys.registerOptions(); let c; try { c = await navigator.credentials.create({ publicKey: { ...o, challenge: unb64(o.challenge), user: { ...o.user, id: unb64(o.user.id) }, excludeCredentials: (o.excludeCredentials || []).map(x => ({ type: 'public-key', id: unb64(x.id) })) } }); } catch (e) { throw new Error(t('لم يُفعَّل: أُلغي الطلب أو أن هذا الجهاز مسجّل من قبل.', 'Not enabled: cancelled, or this device is already registered.')); } const label = (/iPhone|iPad/.test(navigator.userAgent) ? 'iPhone/iPad' : /Android/.test(navigator.userAgent) ? 'Android' : /Mac/.test(navigator.userAgent) ? 'Mac' : /Windows/.test(navigator.userAgent) ? 'Windows' : t('جهاز', 'Device')); await API.passkeys.register({ id: c.id, response: { clientDataJSON: b64(c.response.clientDataJSON), attestationObject: b64(c.response.attestationObject) } }, label); toastx(t('تم! يمكنك الدخول بالبصمة من هذا الجهاز.', 'Done! You can now sign in with your passkey on this device.')); return render(); }, async fedUnlink(d) { await API.federation.unlink(d.id); return render(); }, async passkeyRemove(d) { await API.passkeys.remove(d.id); return render(); }, async devRevoke(d) { await API.auth.revokeDevice(d.id); return render(); }, async devOthers() { const n = await API.auth.logoutOthers(); toastx(t('أُلغي دخول ', 'Signed out ') + n); return render(); }, async logout() { const wasStudent = window.LBS_SCOPE && window.LBS_SCOPE.uid; try { await API.auth.logout(); } catch (e) {} setSess(null); if (wasStudent) { location.reload(); return; } return render(); }, async registerParent() { await API.auth.register({ role: 'parent', name: val('rgName'), username: val('rgUser'), password: document.getElementById('rgPass').value }); toastx(t('أُنشئ الحساب؛ سجّل الدخول الآن', 'Account created; sign in now')); document.getElementById('scUser').value = val('rgUser'); }, async seed() { const acc = await seedDemo(); await render(); document.getElementById('scDemo').innerHTML = `
${t('الحسابات التجريبية — كلمة مرور فريدة لكل حساب', 'Demo accounts — a unique password for each')}${acc.map(([u, p]) => ``).join('')}
${H(u)}${H(p)}

${t('تظهر مرة واحدة. حساب المؤسس يطلب تغيير كلمة المرور عند أول دخول. للاختبار على هذا الجهاز فقط.', 'Shown once. The founder account must change its password at first sign-in. For testing on this device only.')}

`; window.__lbsDemo = acc; }, dlPw() { downloadBlob('lubonta-sandbox-accounts.txt', (window.__lbsDemo || []).map(r => r.join('\t')).join('\n'), 'text/plain'); }, goLearn() { close(); if (typeof goSetup === 'function') goSetup(); }, async showReport(d) { const R = await runReport(d.sid, d.p); document.getElementById(d.p + 'Out').innerHTML = reportHTML(R) + exportBtns(d.sid); }, async printRep(d) { const R = VIEW.lastReport; await API.reports.logExport(d.sid, R.type, 'pdf'); printHTML(reportHTML(R)); }, async dlRep(d) { const R = VIEW.lastReport; await API.reports.logExport(d.sid, R.type, 'html'); downloadHTML('lubonta-report-' + R.type, reportHTML(R)); }, kidReport(d) { VIEW.kid = d.sid; TAB = 'pa_rep'; return render(); }, pickKid(d, s) { VIEW.kid = s.value; VIEW.lastReport = null; return render(); }, pickStudent(d) { VIEW.kid = d.sid; VIEW.lastReport = null; return render(); }, async linkCode() { const c = await API.people.linkCode(); document.getElementById('lcOut').textContent = c; }, async addKid() { await API.auth.register({ role: 'student', name: val('kName'), username: val('kUser'), password: document.getElementById('kPass').value, birthYear: +val('kYear') || null, grade: val('kGrade'), mustChange: false }); toastx(t('أُضيف الحساب', 'Added')); return render(); }, async reqLink() { await API.people.requestLink(val('lnCode')); toastx(t('أُرسل الطلب؛ يوثّقه فريق الدعم', 'Requested; support will verify')); return render(); }, async grant() { const [type, id] = val('gTo').split(':'); const types = [...root.querySelectorAll('.gType:checked')].map(x => x.value); await API.people.grant({ studentId: val('gKid'), granteeType: type, granteeId: id, reportTypes: types, days: +val('gDays') }); toastx(t('مُنح الإذن', 'Granted')); return render(); }, async revoke(d) { await API.people.revokeGrant(d.id); return render(); }, hwFor(d) { const bank = homeworkBank(); VIEW.hwSid = d.sid; document.getElementById('hwBox').innerHTML = `

${t('واجب جديد', 'New homework')}

${t('بنك الأسئلة مأخوذ من الدروس الجاهزة في التطبيق، وهو محدود حاليًا.', 'The bank comes from the ready lessons in the app and is small for now.')}

`; }, async sendHw() { const b = homeworkBank()[+val('hwSet')]; await API.homework.assign({ studentId: VIEW.hwSid, title: b.title, items: b.items, dueDays: +val('hwDue'), lessonId: b.lessonId, skill: b.skill }); toastx(t('أُرسل الواجب', 'Homework sent')); return render(); }, async selfPractice(d) { const b = homeworkBank().find(x => x.skill === d.skill) || homeworkBank()[0]; if (!b) throw new Error(t('لا يوجد تدريب متاح', 'No practice available')); await API.homework.assign({ studentId: SESS.uid, title: t('تدريب: ', 'Practice: ') + b.title, items: b.items.slice(0, 4), dueDays: 2, lessonId: b.lessonId, skill: d.skill }); TAB = 'st_hw'; return render(); }, async submitHw(d) { const ans = [...root.querySelectorAll(`.hwA[data-hw="${d.id}"]`)].map(x => x.value); const r = await API.homework.submit(d.id, ans); toastx(`${t('النتيجة', 'Score')}: ${r.score}/${r.of}${r.late ? ' · ' + t('متأخر', 'late') : ''}`); return render(); }, async subscribe() { const ids = [...root.querySelectorAll('.bKid:checked')].map(x => x.value); const r = await API.billing.subscribe({ country: VIEW.country || 'SA', packageId: val('bPkg'), studentIds: ids, coupon: val('bCoupon') || null }); toastx(t('صدرت الفاتورة ', 'Invoice issued ') + r.invoice.no); return render(); }, async pay(d) { await API.billing.pay(d.id, { method: 'sandbox_card' }); toastx(t('تم الدفع التجريبي وتفعيل الباقة', 'Sandbox payment captured; package active')); return render(); }, async printInv(d) { printHTML(invoiceHTML(await API.billing.invoice(d.id))); }, async refund(d) { const amt = Math.round(parseFloat(val('rf_' + d.id)) * (+d.unit || 100)); await API.billing.refund(d.id, { amountMinor: amt || undefined, reason: val('rfw_' + d.id) }); toastx(t('تم الاسترداد وإصدار إشعار دائن', 'Refunded; credit note issued')); return render(); }, async savePrefs() { await API.people.setPrefs({ edu: document.getElementById('nEdu').checked, fin: document.getElementById('nFin').checked }); ME = null; toastx(t('حُفظ', 'Saved')); }, async delKid() { if (!confirmed(t('سيُحذف كل نشاط هذا الطالب نهائيًا. متابعة؟', 'This permanently deletes the student\'s activity. Continue?'))) return; const r = await API.data.deleteStudent(val('dKid'), { reason: val('dWhy') }); clearLocal(r.localKeysToClear); toastx(t('حُذفت البيانات', 'Deleted')); return render(); }, async openTk() { await API.support.open({ kind: val('tkKind'), subject: val('tkSub'), body: val('tkBody') }); toastx(t('أُرسل', 'Sent')); return render(); }, async replyTk(d) { await API.support.reply(d.id, { text: val('rp_' + d.id), status: 'answered' }); return render(); }, async closeTk(d) { await API.support.reply(d.id, { status: 'closed' }); return render(); }, async verifyLink(d) { await API.people.verifyLink(d.id, { evidence: val('ev_' + d.id) }); toastx(t('وُثّقت الولاية', 'Verified')); return render(); }, async chPw() { await API.auth.changePassword(document.getElementById('pwOld').value, document.getElementById('pwNew').value); toastx(t('تغيّرت كلمة المرور؛ سجّل الدخول مجددًا', 'Password changed; sign in again')); try { await API.auth.logout(); } catch (e) {} setSess(null); return render(); }, async addTeacher() { const u = await API.auth.register({ role: 'teacher', name: val('tName'), username: val('tUser'), generatePassword: true }); await render(); showNewPassword(u.username, u.initialPassword); }, cuIn(d) { VIEW.path = (VIEW.path || []).concat(d.id); return render(); }, cuUp(d) { VIEW.path = +d.i < 0 ? [] : (VIEW.path || []).slice(0, +d.i + 1); return render(); }, async importCur() { const r = await importCurriculum(); toastx(t('أُضيف ', 'Added ') + r.added + t(' · رُقّي ', ' · upgraded ') + (r.upgraded || 0)); return render(); }, async advance(d) { const v = val('nx_' + d.id), x = {}; if (d.to === 'content_entered') x.contentRef = v; if (d.to === 'playable') x.playable = !!((await API.curriculum.get(d.id)).meta.contentRef); if (d.to === 'tech_tested') x.testRun = v ? { id: v, passed: true } : null; if (d.to === 'pedagogy_reviewed') x.notes = v; await API.curriculum.setStatus(d.id, d.to, x); return render(); }, async official(d) { await API.curriculum.verifyOfficial(d.id, { source: val('os_' + d.id), against: t('منصة مدرستي / عين / الكتاب المدرسي', 'Madrasati / Ein / textbook') }); return render(); }, pickCur(d, s) { VIEW.cur = s.value; return render(); }, pickCountry(d, s) { VIEW.country = s.value; VIEW.quote = null; return render(); }, setPeriod(d) { VIEW[d.p + 'P'] = d.v; return render(); }, applyPeriod(d) { VIEW[d.p + 'F'] = val(d.p + 'F'); VIEW[d.p + 'T'] = val(d.p + 'T'); return render(); }, async csv(d) { downloadBlob('lubonta-' + d.k + '.csv', await API.billing.exportCSV(d.k), 'text/csv'); }, async saveRates() { const c = VIEW.country || 'SA', unit = LB.DEFAULT_TAX[c].minor || 100; const rates = val('rcRates').split(',').map(x => x.trim()).filter(Boolean).map(x => { const [g, p] = x.split(':'); return { groupSize: +g, perStudentHourMinor: Math.round(parseFloat(p) * unit) }; }); await API.billing.setRateCard(c, { rates, note: t('أسعار مرجعية — غير معتمدة حتى مراجعة المؤسس', 'Reference prices — unapproved until founder review') }); toastx(t('حُفظت الأسعار (غير معتمدة)', 'Saved (unapproved)')); return render(); }, async approveRates() { await API.billing.approveRateCard(VIEW.country || 'SA'); return render(); }, async quote() { VIEW.quote = await API.billing.quote({ country: VIEW.country || 'SA', groupSize: +val('qG'), minutes: +val('qM'), sessions: +val('qN') }); return render(); }, async pkgFromQuote() { await API.billing.packageFromQuote(VIEW.country || 'SA', { groupSize: +val('qG'), minutes: +val('qM'), sessions: +val('qN') }); toastx(t('أُنشئت الباقة', 'Package created')); return render(); }, async saveTax() { await API.billing.setTaxRule(VIEW.country || 'SA', { treatment: val('txT'), rate: parseFloat(val('txR')), reference: val('txRef') }); return render(); }, async addExp() { await API.billing.addExpense({ category: val('exCat'), amountMinor: Math.round(parseFloat(val('exAmt')) * 100), currency: val('exCur'), note: val('exNote') }); return render(); }, async addCoupon() { await API.billing.createCoupon({ code: val('cpCode'), percent: +val('cpPct'), maxUses: +val('cpUses') || 1 }); return render(); }, async approveCoupon(d) { await API.billing.approveCoupon(d.code); return render(); }, async newUser() { const u = await API.auth.register({ role: val('nuRole'), name: val('nuName'), username: val('nuUser'), schoolId: val('nuSchool') || null, generatePassword: true }); await render(); showNewPassword(u.username, u.initialPassword); }, async newSchool() { await API.people.createSchool({ name: val('nsName') }); return render(); }, async disable(d) { await API.auth.disable(d.id, true); return render(); }, async privReport() { const R = await API.reports.student(val('pvSid'), { type: 'monthly', reason: val('pvWhy') }); document.getElementById('pvOut').innerHTML = reportHTML(R); }, async verifyAudit() { const r = await API.data.verify(); toastx(r.ok ? t('السجل سليم: ', 'Log intact: ') + r.entries : t('تم اكتشاف تعديل عند القيد ', 'Tampering detected at entry ') + r.brokenAt); }, backup() { const b = SC.data.backup(localActor()); downloadBlob('lubonta-school-backup.json', JSON.stringify(b), 'application/json'); }, async restore(d, input) { const f = input.files[0]; if (!f) return; SC.data.restore(localActor(), JSON.parse(await f.text())); toastx(t('تمت الاستعادة', 'Restored')); return render(); }, purge() { const n = SC.data.purge(); toastx(t('حُذف ', 'Removed ') + n + t(' حدثًا أقدم من مدة الاحتفاظ', ' events older than retention')); } }; function confirmed(msg) { try { return window.confirm(msg); } catch (e) { return true; } } function clearLocal(suffix) { try { const ks = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && k.endsWith(suffix)) ks.push(k); } ks.forEach(k => Storage.prototype.removeItem.call(localStorage, k)); } catch (e) {} } /* ---------------- question bank for homework / post-lesson quizzes ---------------- */ function homeworkBank() { const out = []; try { if (typeof BASE_UNITS !== 'undefined' && typeof Content !== 'undefined') { Object.values(BASE_UNITS).forEach(units => units.forEach(u => u.lessons.forEach(l => { const sp = l.spec && Content.spec ? Content.spec(l) : null; if (!sp) return; const items = [...(sp.practice || []), ...(sp.quiz || [])].filter(q => q.answer != null && (q.type === 'number' || q.type === 'fraction' || q.type === 'choice' || !q.type)).map(q => ({ prompt: q.prompt, answer: String(q.answer), type: q.type === 'choice' ? 'choice' : 'number', simplest: !!q.simplest, options: q.options || null })); if (items.length) out.push({ title: l.no + ' ' + l.title, items: items.slice(0, 8), lessonId: l.no, skill: (l.spec || l.no) + ':core' }); }))); } } catch (e) { console.warn(e); } const fr = []; for (let i = 0; i < 6; i++) { const d = [5, 6, 7, 8, 9, 10][i], a = 1 + (i % 3), b = 1 + ((i + 1) % 3), add = i % 2 === 0; if (!add && a <= b) continue; const n = add ? a + b : a - b; fr.push({ prompt: `${a}/${d} ${add ? '+' : '−'} ${b}/${d} = ?`, answer: n + '/' + d, type: 'number' }); } out.unshift({ title: '9-1 / 9-2 ' + t('جمع الكسور المتشابهة وطرحها', 'Like fractions'), items: fr, lessonId: '9-1', skill: 'p5-frac-like:core' }); return out; } /* ---------------- tutor integration (student signed in) ---------------- */ // Learning events go to the server; if the network drops they wait in a per-student outbox and are re-sent. const OUTBOX_KEY = 'lb_sch_outbox'; function outbox() { try { return JSON.parse(localStorage.getItem(OUTBOX_KEY) || '[]'); } catch (e) { return []; } } function setOutbox(a) { try { localStorage.setItem(OUTBOX_KEY, JSON.stringify(a.slice(-500))); } catch (e) {} } let flushing = false; async function flushOutbox() { if (flushing) return; flushing = true; try { let q = outbox(); while (q.length) { const [name, args] = q[0]; try { await call(name, ...args); } catch (e) { if (e.offline) break; } q.shift(); setOutbox(q); } } finally { flushing = false; } } async function send(name, ...args) { try { await flushOutbox(); return await call(name, ...args); } catch (e) { if (e.offline) { const q = outbox(); q.push([name, args]); setOutbox(q); } else console.warn('school event not saved:', name, e.message); return null; } } window.addEventListener('online', () => flushOutbox()); const LIVE = { sessionId: null, start: 0, lessonId: null, subject: null, title: null, ended: false }; window.LBS_LIVE = LIVE; async function sessionEnd(complete) { if (!isStudent() || !LIVE.sessionId || LIVE.ended) return; LIVE.ended = true; const minutes = Math.max(1, Math.round((Date.now() - LIVE.start) / 60000)); if (complete) { const L = (typeof S !== 'undefined' && S.log) || [], qz = L.filter(e => e.phase === 'quiz' || e.kind === 'quiz'), ok = qz.filter(e => e.ok).length; const skills = {}; const labels = (typeof CUR !== 'undefined' && CUR && CUR.lesson && CUR.lesson.spec && CUR.lesson.spec.misLabels) || {}; if (qz.length) skills[(LIVE.lessonId || 'lesson') + ':core'] = { ok, total: qz.length, label: (LIVE.title || '') }; L.filter(e => e.err).forEach(e => { const k = LIVE.lessonId + ':' + e.err; skills[k] = skills[k] || { ok: 0, total: 0, label: t('تجنّب خطأ: ', 'Avoid: ') + (labels[e.err] || e.err) }; skills[k].total++; }); if (qz.length) await send('learning.track', { type: 'quiz', lessonId: LIVE.lessonId, lessonTitle: LIVE.title, subject: LIVE.subject, score: ok, of: qz.length, kind: 'in_lesson', skills }); await send('learning.track', { type: 'lesson_complete', lessonId: LIVE.lessonId, lessonTitle: LIVE.title, subject: LIVE.subject, score: ok, of: qz.length }); const c = await send('billing.consume', { studentId: SESS.uid, sessionId: LIVE.sessionId, lessonId: LIVE.lessonId }); if (c && c.ok === false) toastx(t('حصة دون رصيد (بيئة اختبار)', 'Session without credit (test environment)')); const calls = (typeof S !== 'undefined' && S.aiCalls) || 0; if (calls) await send('billing.aiCost', { sessionId: LIVE.sessionId, usd: calls * 0.0008, parts: { calls, note: 'estimate' } }); } await send('learning.track', { type: 'session_end', minutes, lessonId: LIVE.lessonId, subject: LIVE.subject }); } function hookTutor() { if (typeof startLesson === 'function') { const _sl = startLesson; window.startLesson = startLesson = function (o) { if (isStudent()) { if (LIVE.sessionId && !LIVE.ended) sessionEnd(false); Object.assign(LIVE, { sessionId: 'ses_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), start: Date.now(), lessonId: o && o.id || null, subject: o && o.ctx && (o.ctx.subject || o.ctx.subjectName) || null, title: o && o.lesson && o.lesson.title || null, ended: false }); send('learning.track', { type: 'session_start', lessonId: LIVE.lessonId, subject: LIVE.subject, lessonTitle: LIVE.title, sessionId: LIVE.sessionId }); if (SESS.name && typeof S !== 'undefined') S.student.name = SESS.name; } return _sl.apply(this, arguments); }; } if (typeof showReport === 'function') { const _sr = showReport; window.showReport = showReport = async function (final) { const r = await _sr.apply(this, arguments); if (final && isStudent()) { await sessionEnd(true); setTimeout(addPostLessonButtons, 60); } return r; }; } if (typeof abortLesson === 'function') { const _ab = abortLesson; window.abortLesson = abortLesson = function () { const r = _ab.apply(this, arguments); if (isStudent() && LIVE.sessionId && !LIVE.ended) sessionEnd(false); return r; }; } if (typeof qaAsk === 'function') { const _qa = qaAsk; window.qaAsk = qaAsk = function (text) { if (isStudent() && text) send('learning.track', { type: 'question', text, lessonId: LIVE.lessonId, subject: LIVE.subject, lessonTitle: LIVE.title }); return _qa.apply(this, arguments); }; } } function addPostLessonButtons() { const sheet = document.querySelector('#modalRoot .sheet .actions') || document.querySelector('#modalRoot .sheet'); if (!sheet || document.getElementById('scPostQuiz')) return; const b = document.createElement('button'); b.className = 'btn ghost'; b.id = 'scPostQuiz'; b.textContent = '📝 ' + t('اختبار قصير بعد الدرس', 'Quick post-lesson quiz'); b.onclick = postQuiz; sheet.appendChild(b); const r = document.createElement('button'); r.className = 'btn ghost'; r.textContent = '📊 ' + t('تقاريري ومدرستي', 'My reports'); r.onclick = () => { if (typeof closeModal === 'function') closeModal(); open('st_rep'); }; sheet.appendChild(r); } function postQuiz() { const sp = typeof CUR !== 'undefined' && CUR && CUR.lesson && CUR.lesson.spec; let items; if (sp) items = [...(sp.practice || []), ...(sp.quiz || [])].filter(q => q.answer != null && q.type !== 'choice').sort(() => Math.random() - 0.5).slice(0, 3).map(q => ({ prompt: q.prompt, answer: String(q.answer), simplest: !!q.simplest, skill: (LIVE.lessonId || 'lesson') + ':core', skillLabel: LIVE.title })); else items = homeworkBank()[0].items.slice(0, 3).map(i => ({ ...i, skill: (LIVE.lessonId || 'lesson') + ':core', skillLabel: LIVE.title })); if (!items.length) { toastx(t('لا توجد أسئلة إضافية لهذا الدرس', 'No extra questions')); return; } modal(`

📝 ${t('اختبار قصير بعد الدرس', 'Quick post-lesson quiz')}

${items.map((q, i) => `
${i + 1}. ${H(q.prompt)}
`).join('')}
`); document.getElementById('pqNo').onclick = closeModal; document.getElementById('pqGo').onclick = async () => { const ans = [...document.querySelectorAll('.pqA')].map(x => x.value); let r; try { r = await API.learning.gradeQuiz({ lessonId: LIVE.lessonId, lessonTitle: LIVE.title, subject: LIVE.subject, items, answers: ans, kind: 'post_lesson' }); } catch (e) { toastx(e.message); return; } document.getElementById('pqOut').innerHTML = `

${r.score}/${r.of} — ${r.results.map((x, i) => `${i + 1}: ${x.ok ? '✓' : '✗ ' + t('الصحيح ', 'correct ') + H(x.answer)}`).join(' · ')}

`; const g = document.getElementById('pqGo'); if (g) g.remove(); }; } /* ---------------- teacher dialect & gender preference (voice provider later) ---------------- */ const DIALECTS = [['auto', 'تلقائي', 'Auto'], ['ar-SA', 'سعودية', 'Saudi'], ['ar-EG', 'مصرية', 'Egyptian'], ['ar-LB', 'لبنانية', 'Lebanese'], ['ar-JO', 'أردنية', 'Jordanian'], ['ar-AE', 'إماراتية', 'Emirati'], ['ar-KW', 'كويتية', 'Kuwaiti'], ['ar-QA', 'قطرية', 'Qatari'], ['ar-BH', 'بحرينية', 'Bahraini'], ['ar-OM', 'عُمانية', 'Omani'], ['ar-XA', 'فصحى', 'MSA']]; function hookVoicePrefs() { if (typeof Speech === 'undefined' || !Speech.pickVoice) return; const _pv = Speech.pickVoice.bind(Speech); Speech.pickVoice = function () { _pv(); const pref = S.settings && S.settings.tDialect; if (!this.ok || !pref || pref === 'auto') return; const vs = speechSynthesis.getVoices().filter(v => v.lang && v.lang.replace('_', '-').toLowerCase().startsWith(pref.toLowerCase())); if (vs.length) this.voice = vs[0]; }; if (typeof showSettings === 'function') { const _ss = showSettings; window.showSettings = showSettings = function () { const r = _ss.apply(this, arguments); setTimeout(() => { const sheet = document.querySelector('#modalRoot .sheet'); if (!sheet || document.getElementById('sTDialect')) return; const all = Speech.ok ? speechSynthesis.getVoices().filter(v => /^ar/i.test(v.lang)) : []; const box = document.createElement('div'); box.className = 'card'; box.style.margin = '8px 0'; box.innerHTML = `

${t('لهجة المدرّس وصوته', 'Teacher dialect & voice')}

${t('تظهر فقط اللهجات المتوفرة فعلًا على هذا الجهاز. ربط مزوّد أصوات عربية مؤجّل بقرار المؤسس؛ عند ربطه تظهر أصواته هنا دون إعادة بناء التطبيق.', 'Only dialects actually available on this device are enabled. A cloud Arabic voice provider is postponed by the founder; its voices will appear here without rebuilding the app.')}

`; const acts = sheet.querySelector('.actions'); sheet.insertBefore(box, acts || null); const save = () => { S.settings.tDialect = document.getElementById('sTDialect').value; S.settings.tGender = document.getElementById('sTGender').value; store.set('lb_settings', S.settings); Speech.pickVoice(); }; document.getElementById('sTDialect').onchange = save; document.getElementById('sTGender').onchange = save; }, 30); return r; }; } if (typeof teacher === 'function' && typeof TEACHERS !== 'undefined') { const _te = teacher; window.teacher = teacher = function () { const g = S.settings && S.settings.tGender; const T0 = _te.apply(this, arguments); if (!g || g === 'auto' || (g === 'm') === !!T0.m) return T0; const alt = Object.values(TEACHERS).find(x => !!x.m === (g === 'm')); return alt || T0; }; } } /* ---------------- boot ---------------- */ async function boot() { hookTutor(); hookVoicePrefs(); entryLabel(); // back from Google / Apple / Facebook / My LuBonta: the server already set the session cookie const qp = new URLSearchParams(location.search); if (REMOTE && (qp.has('signed') || qp.has('linked') || qp.has('fed_error'))) { if (qp.has('signed')) { try { const u = await API.people.me(); setSess({ uid: u.id, role: u.role, exp: Date.now() + 30 * DAY, name: u.name }); ME = u; } catch (e) {} } const FE = { fed_no_account: t('لا يوجد حساب مدرسة مربوط بهذا الحساب. ادخل مرة بحسابك ثم اربطه من «حسابي»، أو اطلب حسابًا من المدرسة.', 'No school account is linked to this sign-in. Sign in once, then link it from Account.'), fed_student: t('حساب الطالب لا يُربط بحساب اجتماعي.', 'Student accounts cannot be linked to a social account.'), fed_taken: t('هذا الحساب مربوط بمستخدم آخر.', 'This sign-in is linked to another user.') }; const er = qp.get('fed_error'); if (er) setTimeout(() => toastx(FE[er] || t('تعذّر الدخول عبر الحساب الخارجي، حاول مرة أخرى.', 'External sign-in failed, please try again.')), 600); if (qp.has('linked')) setTimeout(() => toastx(t('تم ربط الحساب. يمكنك الدخول به من الآن.', 'Linked. You can sign in with it from now on.')), 600); ['signed', 'linked', 'fed_error'].forEach(k => qp.delete(k)); history.replaceState(null, '', location.pathname + (qp.toString() ? '?' + qp : '') + location.hash); } if (REMOTE && SESS) { const u = await me(); if (!u) setSess(null); else if (isStudent()) flushOutbox(); entryLabel(); } if (!REMOTE) { try { SC.data.purge(); } catch (e) {} } if (sessionStorage.getItem('lbs_open')) { sessionStorage.removeItem('lbs_open'); open(); } if (/[?&]school\b/.test(location.search)) open(); window.LBS_READY = true; } if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else setTimeout(boot, 0); })(); /* ---------------- wire up ---------------- */ function wire(){ $('#consent').checked=!!store.get('lb_consent',false); $('#consent').onchange=()=>store.set('lb_consent',$('#consent').checked); $$('#genderChips .chip').forEach(b=>b.onclick=()=>{$$('#genderChips .chip').forEach(x=>x.classList.remove('sel'));b.classList.add('sel');S.student.g=b.dataset.g;store.set('lb_student',S.student);if(typeof renderStudentPicker==='function')renderStudentPicker()}); const saved=store.get('lb_student',null); if(saved){$('#stName').value=saved.name||'';S.student.g=saved.g||'m';$$('#genderChips .chip').forEach(x=>x.classList.toggle('sel',x.dataset.g===S.student.g))} $('#openReports').onclick=showHistory;$('#openCoverage').onclick=showCoverage;$('#openAdmin').onclick=showAdmin;$('#openSettings1').onclick=showSettings;$('#openSettings2').onclick=showSettings;$('#endBtn').onclick=endLesson; // toolbar $$('.tool[data-tool]').forEach(b=>b.onclick=()=>{$$('.tool[data-tool]').forEach(x=>x.classList.remove('sel'));b.classList.add('sel');Board.tool=b.dataset.tool;Board.sc.style.cursor=b.dataset.tool==='text'?'text':'crosshair'}); $$('.sw').forEach(b=>b.onclick=()=>{$$('.sw').forEach(x=>x.classList.remove('sel'));b.classList.add('sel');Board.color=b.dataset.color;if(Board.tool==='eraser'){$('.tool[data-tool=pen]').click()}}); $$('.szb').forEach(b=>b.onclick=()=>{$$('.szb').forEach(x=>x.classList.remove('sel'));b.classList.add('sel');Board.size=+b.dataset.size}); $('#undoBtn').onclick=()=>{Board.strokes.pop();Board.renderStudent()}; $('#clearBtn').onclick=()=>{Board.strokes=[];Board.renderStudent()}; $('#saveBtn').onclick=()=>Board.save();$('#loadBtn').onclick=()=>Board.load(); $('#imgBtn').onclick=()=>$('#imgFile').click();$('#imgFile').onchange=e=>{const f=e.target.files[0];if(f)Board.insertImage(f);e.target.value=''}; // answers const sub=()=>submitAnswer(readTyped(),'typed'); $('#checkBtn').onclick=sub; $('#numIn').addEventListener('keydown',e=>{if(e.key==='Enter'){if($('#denIn').value||/\//.test(normDigits($('#numIn').value))||!$('#numIn').value)sub();else $('#denIn').focus()}}); $('#numIn').addEventListener('input',e=>{if(/[\/÷]/.test(e.target.value)){const [a,b]=e.target.value.split(/[\/÷]/);e.target.value=a;$('#denIn').value=b||'';$('#denIn').focus()}}); $('#denIn').addEventListener('keydown',e=>{if(e.key==='Enter')sub()}); $('#boardAnsBtn').onclick=boardAnswer;$('#micBtn').onclick=micAnswer; $('#hintBtn').onclick=()=>{const p=S.pending;if(!p||!p.hint)return;S.usedHint=true;Speech.speak(p.hint);showBubble(p.hint);addChat('t','💡 '+p.hint)}; $('#askBtn').onclick=()=>{const v=$('#askIn').value;$('#askIn').value='';studentQuestion(v)}; $('#askIn').addEventListener('keydown',e=>{if(e.key==='Enter'){$('#askBtn').click()}}); $('#againBtn').onclick=explainAgain; $('#textIn').addEventListener('keydown',e=>{if(e.key==='Enter')sub()}); $('#hwBtn').onclick=()=>{if(!AI.vision){toast('قراءة الصور تحتاج مزوّد ذكاء اصطناعي يدعم الصور.',4000);return}$('#hwFile').click()}; $('#hwFile').onchange=e=>{const f=e.target.files[0];e.target.value='';if(f)imageHelp(f,$('#askIn').value.trim());$('#askIn').value=''}; $('#lookBtn').onclick=async()=>{if(!Board.hasInk()){toast('اكتب أو ارسم على السبورة أولًا ✍️');return}const q=$('#askIn').value.trim();$('#askIn').value='';imageHelp(await Board.studentBlob(),q||'انظر إلى ما كتبته أو رسمته على السبورة وعلّق عليه.')}; $('#btnRepeat').onclick=()=>{if(S.lastSay&&!Speech.resolver){Speech.speak(S.lastSay)}}; $('#btnSkip').onclick=()=>{Board.skip=true;Speech.stop()}; $('#btnVoice').onclick=()=>{S.settings.voice=!S.settings.voice;store.set('lb_settings',S.settings);voiceBtn();if(!S.settings.voice)Speech.stop()}; Board.init(); AI.init().then(()=>renderBrowse()); renderBrowse();renderStudentPicker(); } wire();