/* ============================================================
🔗 أزرار مشاركة لينكات الدروس + إغلاق الصفحة بعد واتساب
============================================================ */
(function() {
// ===== 1) أزرار المشاركة جنب كل درس =====
function addShareButtons() {
const home = document.getElementById("homeScreen");
if (!home || !home.classList.contains("active")) return;
const list = document.getElementById("lessonsList");
if (!list) return;
if (list.querySelector(".share-link-btn")) return;
list.querySelectorAll(".lesson-item").forEach(link => {
if (link.querySelector(".share-link-btn")) return;
const href = link.getAttribute("href") || "";
const match = href.match(/stage=([^&]+)&lesson=([^&]+)/);
if (!match) return;
const fullURL = location.origin + location.pathname + "?stage=" + match[1] + "&lesson=" + match[2];
const btn = document.createElement("button");
btn.className = "share-link-btn";
btn.innerHTML = "📤";
btn.title = "انسخ لينك الدرس";
btn.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
if (navigator.clipboard) {
navigator.clipboard.writeText(fullURL).then(() => {
btn.innerHTML = "✅";
setTimeout(() => { btn.innerHTML = "📤"; }, 1500);
});
} else {
const ta = document.createElement("textarea");
ta.value = fullURL;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
btn.innerHTML = "✅";
setTimeout(() => { btn.innerHTML = "📤"; }, 1500);
}
};
link.insertBefore(btn, link.firstChild);
});
}
// راقب ظهور الصفحة الرئيسية
new MutationObserver(() => {
const home = document.getElementById("homeScreen");
if (home && home.classList.contains("active")) {
setTimeout(addShareButtons, 200);
}
}).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["class"] });
document.addEventListener("DOMContentLoaded", () => setTimeout(addShareButtons, 500));
// ===== 2) إغلاق الصفحة بعد إرسال الواتساب =====
document.addEventListener("click", function(e) {
const btn = e.target.closest("#whatsappBtn");
if (!btn) return;
setTimeout(() => {
const result = document.getElementById("resultScreen");
if (!result) return;
result.innerHTML = `
✅
تم إرسال نتيجتك
شكراً لك على إتمام الامتحان بنجاح 🌟
لا يمكن إعادة الامتحان مرة أخرى.
📱 يمكنك إغلاق هذه الصفحة الآن
`;
window.history.pushState(null, "", window.location.href);
window.onpopstate = function() {
window.history.pushState(null, "", window.location.href);
};
setTimeout(() => { try { window.close(); } catch(e) {} }, 3000);
}, 500);
}, true);
// ===== 3) كود Admin Panel =====
const STORAGE_KEY = "admin_edits_v1";
let adminState = { stage: null, unit: null, lesson: null, edits: {}, deleted: {}, added: {} };
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
adminState = { ...adminState, ...saved };
} catch (e) {}
function saveEdits() {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(adminState)); } catch (e) {}
}
const $id = id => document.getElementById(id);
function openAdmin() {
document.querySelectorAll(".screen").forEach(s => s.classList.remove("active"));
$id("adminScreen").classList.add("active");
window.scrollTo({ top: 0 });
initAdminFilters();
}
function closeAdmin() {
document.querySelectorAll(".screen").forEach(s => s.classList.remove("active"));
$id("homeScreen").classList.add("active");
window.scrollTo({ top: 0 });
}
function initAdminFilters() {
const stageSel = $id("adminStage");
if (!stageSel || typeof CURRICULUM === "undefined") return;
stageSel.innerHTML = "";
Object.keys(CURRICULUM).forEach(key => {
const opt = document.createElement("option");
opt.value = key;
opt.textContent = CURRICULUM[key].name;
stageSel.appendChild(opt);
});
if (!adminState.stage || !CURRICULUM[adminState.stage]) adminState.stage = Object.keys(CURRICULUM)[0];
stageSel.value = adminState.stage;
stageSel.onchange = () => {
adminState.stage = stageSel.value;
adminState.unit = null; adminState.lesson = null;
fillUnits();
};
fillUnits();
}
function fillUnits() {
const unitSel = $id("adminUnit");
if (!unitSel) return;
const stage = CURRICULUM[adminState.stage];
if (!stage) return;
unitSel.innerHTML = "";
stage.units.forEach((u, i) => {
const opt = document.createElement("option");
opt.value = i; opt.textContent = u.name;
unitSel.appendChild(opt);
});
if (adminState.unit === null || adminState.unit >= stage.units.length) adminState.unit = 0;
unitSel.value = adminState.unit;
unitSel.onchange = () => {
adminState.unit = parseInt(unitSel.value);
adminState.lesson = null;
fillLessons();
};
fillLessons();
}
function fillLessons() {
const lessonSel = $id("adminLesson");
if (!lessonSel) return;
const stage = CURRICULUM[adminState.stage];
const unit = stage.units[adminState.unit];
if (!unit) return;
lessonSel.innerHTML = "";
unit.lessons.forEach((l, i) => {
const opt = document.createElement("option");
opt.value = i; opt.textContent = l.name;
lessonSel.appendChild(opt);
});
if (adminState.lesson === null || adminState.lesson >= unit.lessons.length) adminState.lesson = 0;
lessonSel.value = adminState.lesson;
lessonSel.onchange = () => {
adminState.lesson = parseInt(lessonSel.value);
renderAdminQuestions();
};
renderAdminQuestions();
}
function getLessonQuestions() {
const stage = CURRICULUM[adminState.stage];
const unit = stage.units[adminState.unit];
const lesson = unit.lessons[adminState.lesson];
const key = adminState.stage + "_" + unit.id + "_" + lesson.id;
let questions = lesson.questions.map((q, i) => ({
...q, originalIndex: i,
isEdited: !!adminState.edits[key + "_" + i],
isDeleted: !!adminState.deleted[key + "_" + i]
}));
const added = adminState.added[key] || [];
added.forEach((q, i) => {
questions.push({ ...q, originalIndex: "new_" + i, isEdited: false, isDeleted: false, isNew: true });
});
return { questions, key, lesson };
}
function renderAdminQuestions() {
const list = $id("adminQuestionsList");
if (!list) return;
const { questions, key } = getLessonQuestions();
$id("adminQCount").textContent = questions.filter(q => !q.isDeleted).length;
let editCount = 0;
Object.keys(adminState.edits).forEach(k => { if (k.startsWith(key + "_")) editCount++; });
$id("adminEditCount").textContent = editCount;
if (!questions.length) {
list.innerHTML = 'لا توجد أسئلة. اضغط "إضافة سؤال".
';
return;
}
list.innerHTML = "";
const letters = ["A","B","C","D"];
questions.forEach((q, displayIdx) => {
const item = document.createElement("div");
item.className = "admin-q-item";
if (q.isEdited) item.classList.add("edited");
if (q.isDeleted) item.classList.add("deleted");
let optionsHtml = "";
q.options.forEach((opt, oi) => {
const cls = oi === q.correct ? "admin-q-opt correct" : "admin-q-opt";
optionsHtml += '' + letters[oi] + '. ' + opt + (oi === q.correct ? " ✓" : "") + '
';
});
let actions = "";
if (q.isDeleted) {
actions = '';
} else {
actions = '' +
'';
}
const badge = q.isNew ? 'جديد' : '';
const editedBadge = q.isEdited ? 'مُعدّل' : '';
item.innerHTML = 'السؤال ' + (displayIdx + 1) + ' ' + badge + ' ' + editedBadge + '
' +
'' + q.text + '
' +
'' + optionsHtml + '
' +
'' + actions + '
';
list.appendChild(item);
});
}
let currentEdit = null;
function openEditModal(question, originalIndex) {
currentEdit = { question, originalIndex };
$id("editTitle").textContent = originalIndex === "new" ? "➕ إضافة سؤال جديد" : "✏️ تعديل السؤال";
$id("editQuestionText").value = question ? question.text : "";
for (let i = 0; i < 4; i++) {
$id("editOpt" + i).value = question && question.options[i] ? question.options[i] : "";
}
const correct = question ? question.correct : 0;
document.getElementById("opt" + correct + "radio").checked = true;
$id("editDelete").style.display = originalIndex === "new" ? "none" : "block";
$id("editModal").classList.remove("hidden");
updatePreview();
}
function closeEditModal() {
$id("editModal").classList.add("hidden");
currentEdit = null;
}
function updatePreview() {
const p = $id("editPreview");
if (!p) return;
p.innerHTML = $id("editQuestionText").value;
if (window.MathJax && window.MathJax.typesetPromise) {
window.MathJax.typesetPromise([p]).catch(()=>{});
}
}
function saveEdit() {
if (!currentEdit) return;
const text = $id("editQuestionText").value.trim();
if (!text) { alert("اكتب نص السؤال"); return; }
const options = [];
for (let i = 0; i < 4; i++) {
const val = $id("editOpt" + i).value.trim();
if (!val) { alert("املأ كل الاختيارات"); return; }
options.push(val);
}
const correct = parseInt(document.querySelector('input[name="correctOpt"]:checked')?.value || 0);
const newQ = { text, options, correct };
const { key } = getLessonQuestions();
if (currentEdit.originalIndex === "new") {
if (!adminState.added[key]) adminState.added[key] = [];
adminState.added[key].push(newQ);
} else if (typeof currentEdit.originalIndex === "string" && currentEdit.originalIndex.startsWith("new_")) {
const idx = parseInt(currentEdit.originalIndex.replace("new_", ""));
if (adminState.added[key] && adminState.added[key][idx]) adminState.added[key][idx] = newQ;
} else {
adminState.edits[key + "_" + currentEdit.originalIndex] = newQ;
}
saveEdits();
closeEditModal();
renderAdminQuestions();
}
function deleteQuestion(originalIndex) {
if (!confirm("حذف هذا السؤال؟")) return;
const { key } = getLessonQuestions();
adminState.deleted[key + "_" + originalIndex] = true;
saveEdits();
renderAdminQuestions();
}
function restoreQuestion(originalIndex) {
const { key } = getLessonQuestions();
delete adminState.deleted[key + "_" + originalIndex];
saveEdits();
renderAdminQuestions();
}
function exportAppJs() {
const modified = JSON.parse(JSON.stringify(CURRICULUM));
Object.keys(adminState.deleted).forEach(k => {
const parts = k.split("_");
const stage = parts[0], unitId = parts[1], lessonId = parts[2], idx = parseInt(parts[3]);
if (isNaN(idx)) return;
const s = modified[stage]; if (!s) return;
s.units.forEach(u => {
if (String(u.id) !== String(unitId)) return;
u.lessons.forEach(l => {
if (String(l.id) !== String(lessonId)) return;
if (l.questions[idx]) l.questions[idx] = { __DEL: true };
});
});
});
Object.keys(adminState.edits).forEach(k => {
const parts = k.split("_");
const stage = parts[0], unitId = parts[1], lessonId = parts[2], idx = parseInt(parts[3]);
if (isNaN(idx)) return;
const e = adminState.edits[k];
const s = modified[stage]; if (!s) return;
s.units.forEach(u => {
if (String(u.id) !== String(unitId)) return;
u.lessons.forEach(l => {
if (String(l.id) !== String(lessonId)) return;
if (l.questions[idx]) l.questions[idx] = { text: e.text, options: e.options, correct: e.correct };
});
});
});
Object.keys(adminState.added).forEach(k => {
const parts = k.split("_");
const stage = parts[0], unitId = parts[1], lessonId = parts[2];
const s = modified[stage]; if (!s) return;
s.units.forEach(u => {
if (String(u.id) !== String(unitId)) return;
u.lessons.forEach(l => {
if (String(l.id) !== String(lessonId)) return;
adminState.added[k].forEach(q => {
l.questions.push({ text: q.text, options: q.options, correct: q.correct });
});
});
});
});
Object.keys(modified).forEach(stage => {
modified[stage].units.forEach(u => {
u.lessons.forEach(l => {
l.questions = l.questions.filter(q => !q.__DEL);
});
});
});
let js = "/* app.js - نسخة معدلة " + new Date().toLocaleString("ar-EG") + " */\n\n";
js += "const MY_WHATSAPP = \"" + (typeof MY_WHATSAPP !== "undefined" ? MY_WHATSAPP : "201110415311") + "\";\n";
js += "const LESSON_DURATION = 15*60;\nconst UNIT_DURATION = 60*60;\nconst UNIT_EXAM_COUNT = 30;\n\n";
js += "const Q = (text, options, correct) => ({ text, options, correct });\n\n";
js += "const CURRICULUM = " + JSON.stringify(modified, null, 2) + ";\n";
const blob = new Blob([js], { type: "text/javascript" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = "app.js";
document.body.appendChild(a); a.click(); document.body.removeChild(a);
URL.revokeObjectURL(url);
alert("✅ تم تنزيل app.js الجديد");
}
const KEYS = [
{t:"∠",l:"∠"},{t:"⊥",l:"⊥"},{t:"∥",l:"∥"},{t:"△",l:"△"},
{t:"□",l:"□"},{t:"○",l:"○"},{t:"⊙",l:"⊙"},{t:"°",l:"°"},
{t:"π",l:"π"},{t:"θ",l:"θ"},{t:"α",l:"α"},{t:"β",l:"β"},
{t:"$x^2$",l:"x²"},{t:"$x^3$",l:"x³"},{t:"$\\frac{a}{b}$",l:"a/b"},{t:"$\\sqrt{x}$",l:"√x"},
{t:"$\\sqrt[3]{x}$",l:"∛x"},{t:"$\\times$",l:"×"},{t:"$\\div$",l:"÷"},{t:"$\\pm$",l:"±"},
{t:"$\\neq$",l:"≠"},{t:"$\\leq$",l:"≤"},{t:"$\\geq$",l:"≥"},{t:"$\\infty$",l:"∞"},
{t:"$\\rightarrow$",l:"→"},{t:"$\\leftarrow$",l:"←"},{t:"$\\Rightarrow$",l:"⇒"},{t:"$\\pi$",l:"π"},
{t:"$a^2+b^2=c^2$",l:"فيثاغورس"},{t:"$\\triangle$",l:"△"},{t:"$\\angle$",l:"∠"},{t:"$90°$",l:"90°"}
];
function initKeyboard() {
const kb = $id("mathKeyboard");
if (!kb) return;
kb.innerHTML = "";
KEYS.forEach(k => {
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = k.l;
btn.title = k.t;
btn.onclick = () => insertAtCursor(k.t);
kb.appendChild(btn);
});
}
function insertAtCursor(text) {
const target = document.activeElement;
if (target && (target.tagName === "TEXTAREA" || target.tagName === "INPUT")) {
const s = target.selectionStart || 0;
const e = target.selectionEnd || 0;
const v = target.value;
target.value = v.slice(0, s) + text + v.slice(e);
target.selectionStart = target.selectionEnd = s + text.length;
target.focus();
} else {
const ta = $id("editQuestionText");
if (ta) { ta.value += text; ta.focus(); }
}
updatePreview();
}
window.__adminEdit = function(orig, disp) {
const { questions } = getLessonQuestions();
openEditModal(questions[disp], orig);
};
window.__adminDelete = deleteQuestion;
window.__adminRestore = restoreQuestion;
document.addEventListener("DOMContentLoaded", () => {
const openBtn = $id("openAdmin");
const backBtn = $id("backFromAdmin");
const addBtn = $id("addQuestionBtn");
const saveBtn = $id("saveAllBtn");
const exportBtn = $id("exportBtn");
const resetBtn = $id("resetBtn");
const editClose = $id("editClose");
const editCancel = $id("editCancel");
const editSave = $id("editSave");
const editDelete = $id("editDelete");
const editQText = $id("editQuestionText");
const modal = $id("editModal");
if (openBtn) openBtn.onclick = openAdmin;
if (backBtn) backBtn.onclick = closeAdmin;
if (addBtn) addBtn.onclick = () => openEditModal(null, "new");
if (saveBtn) saveBtn.onclick = () => { saveEdits(); alert("✅ تم الحفظ في المتصفح"); };
if (exportBtn) exportBtn.onclick = () => { if (confirm("تنزيل app.js الجديد؟")) exportAppJs(); };
if (resetBtn) resetBtn.onclick = () => {
if (!confirm("حذف كل التعديلات؟")) return;
adminState.edits = {}; adminState.deleted = {}; adminState.added = {};
saveEdits(); renderAdminQuestions();
};
if (editClose) editClose.onclick = closeEditModal;
if (editCancel) editCancel.onclick = closeEditModal;
if (editSave) editSave.onclick = saveEdit;
if (editDelete) editDelete.onclick = () => {
if (currentEdit && currentEdit.originalIndex !== "new") {
deleteQuestion(currentEdit.originalIndex);
closeEditModal();
}
};
if (editQText) editQText.addEventListener("input", updatePreview);
if (modal) modal.addEventListener("click", e => { if (e.target === modal) closeEditModal(); });
initKeyboard();
});
console.log("✅ Admin Panel + Share + Close loaded");
})();