Spaces:
Running
Running
Update index.html
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152import gradio as grimport sqlite3import osimport google.generativeai as genai
DB_FILE = "tasks.db"
genai.configure(api_key=os.environ.get("GOOGLE_API_KEY"))
# ---------- قاعدة البيانات ----------
def init_db(): conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS tasks ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, priority TEXT, time_needed TEXT, done INTEGER DEFAULT 0 ) """) conn.commit() conn.close()
def get_all_tasks_raw(): conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("SELECT id, title, priority, time_needed, done FROM tasks ORDER BY id") rows = cursor.fetchall() conn.close() return [ {"id": r[0], "title": r[1], "priority": r[2], "time_needed": r[3], "done": r[4]} for r in rows ]
def add_task_db(title, priority, time_needed): conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute( "INSERT INTO tasks (title, priority, time_needed, done) VALUES (?, ?, ?, 0)", (title, priority, time_needed) ) conn.commit() conn.close()
def set_done(task_id, value): conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("UPDATE tasks SET done = ? WHERE id = ?", (value, task_id)) conn.commit() conn.close()
def toggle_done_by_title(title): conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("SELECT id, done FROM tasks WHERE LOWER(title) = LOWER(?)", (title,)) row = cursor.fetchone() conn.close() if row is None: return f'لا توجد مهمة باسم "{title}".' task_id, done = row set_done(task_id, 0 if done else 1) return f'تم تحديث حالة مهمة "{title}".'
def delete_task_by_title(title): conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("DELETE FROM tasks WHERE LOWER(title) = LOWER(?)", (title,)) affected = cursor.rowcount conn.commit() conn.close() if affected == 0: return f'لا توجد مهمة باسم "{title}".' return f'تم حذف مهمة "{title}".'
def filter_tasks_by_status(done_status_text): tasks = get_all_tasks_raw() want_done = 1 if done_status_text.strip() in ["تم", "خلصت", "done"] else 0 matched = [t for t in tasks if t["done"] == want_done] if not matched: return "لا توجد مهام مطابقة." lines = [f'{t["title"]} - {t["priority"]}' for t in matched] return "\n".join(lines)
# ---------- تأثيرات بصرية على كامل الصفحة ----------
CONFETTI_JS = """() => { if (!window.__confettiLoaded) { var script = document.createElement('script'); script.src = "https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"; script.onload = function() { confetti({ particleCount: 200, spread: 100, origin: { y: 0.5 } }); }; document.head.appendChild(script); window.__confettiLoaded = true; } else { confetti({ particleCount: 200, spread: 100, origin: { y: 0.5 } }); }}"""
ANGRY_EMOJI_JS = """() => { const overlay = document.createElement('div'); overlay.innerText = '😡'; overlay.style.position = 'fixed'; overlay.style.top = '0'; overlay.style.left = '0'; overlay.style.width = '100vw'; overlay.style.height = '100vh'; overlay.style.display = 'flex'; overlay.style.alignItems = 'center'; overlay.style.justifyContent = 'center'; overlay.style.fontSize = '220px'; overlay.style.zIndex = '99999'; overlay.style.pointerEvents = 'none'; overlay.style.animation = 'fadeOutEmoji 1.3s ease forwards';
if (!document.getElementById('emoji-anim-style')) { const style = document.createElement('style'); style.id = 'emoji-anim-style'; style.innerHTML = ` @keyframes fadeOutEmoji { 0% { opacity: 0; transform: scale(0.4); } 20% { opacity: 1; transform: scale(1.15); } 40% { transform: scale(1); } 100% { opacity: 0; } } `; document.head.appendChild(style); }
document.body.appendChild(overlay); setTimeout(() => overlay.remove(), 1400);}"""
CUSTOM_CSS = """#chat-col { border-radius: 18px; box-shadow: 0 2px 16px rgba(0,0,0,0.08); padding: 18px; background: var(--background-fill-secondary);}#chat-col .message { border-radius: 16px !important;}.task-row { border-bottom: 1px solid var(--border-color-primary); padding: 10px 0;}"""
# ---------- دوال الواجهة العادية ----------
def add_task_ui(title, priority, time_needed, counter): title = title.strip() if not title: return counter, "الرجاء إدخال عنوان المهمة." add_task_db(title, priority, time_needed.strip()) return counter + 1, "تمت إضافة المهمة بنجاح."
# ---------- دوال الوكيل الذكي ----------
agent_tools = [ { "function_declarations": [ { "name": "agent_toggle_task", "description": "Mark a task as done or undone by its exact title (toggles current status).", "parameters": { "type": "object", "properties": { "title": {"type": "string", "description": "Exact task title"}, }, "required": ["title"], }, }, { "name": "agent_delete_task", "description": "Delete a task by its exact title.", "parameters": { "type": "object", "properties": { "title": {"type": "string", "description": "Exact task title to delete"}, }, "required": ["title"], }, }, { "name": "agent_filter_tasks", "description": "List tasks filtered by status: 'تم' for completed tasks, 'لسه' for pending tasks.", "parameters": { "type": "object", "properties": { "status": {"type": "string", "description": "'تم' or 'لسه'"}, }, "required": ["status"], }, }, ] }]
available_functions = { "agent_toggle_task": toggle_done_by_title, "agent_delete_task": delete_task_by_title, "agent_filter_tasks": filter_tasks_by_status,}
def run_agent(user_message, history, counter): if not user_message.strip(): return history, "", counter
model = genai.GenerativeModel( model_name="gemini-1.5-flash", tools=agent_tools, system_instruction=( "أنت مساعد ذكي داخل تطبيق إدارة مهام. رد بأسلوب ودود ومختصر بالعربية. " "استخدم الأدوات المتاحة لتنفيذ طلبات المستخدم المتعلقة بحذف المهام، " "تغيير حالتها، أو فلترتها." ), ) chat = model.start_chat() response = chat.send_message(user_message) part = response.candidates[0].content.parts[0]
if hasattr(part, "function_call") and part.function_call.name: func_name = part.function_call.name func_args = dict(part.function_call.args) result = available_functions.get(func_name, lambda **kw: "دالة غير معروفة")(**func_args)
follow_up = chat.send_message( genai.protos.Content( parts=[genai.protos.Part( function_response=genai.protos.FunctionResponse( name=func_name, response={"result": result} ) )] ) ) final_text = follow_up.text counter += 1 else: final_text = response.text
history.append({"role": "user", "content": user_message}) history.append({"role": "assistant", "content": final_text}) return history, "", counter
# ---------- الواجهة ----------
init_db()theme = gr.themes.Soft(primary_hue="indigo", neutral_hue="slate")
with gr.Blocks(title="مدير المهام", theme=theme, css=CUSTOM_CSS) as demo:
refresh_counter = gr.State(0)
gr.Markdown("# مدير المهام")
with gr.Row():
with gr.Column(scale=2): with gr.Tabs():
with gr.Tab("قائمة المهام"):
@gr.render(inputs=refresh_counter) def render_tasks(_): tasks = get_all_tasks_raw() if not tasks: gr.Markdown("لا توجد مهام بعد.") return for t in tasks: with gr.Row(elem_classes="task-row"): info = f'**{t["title"]}** — {t["priority"]}' if t["time_needed"]: info += f' — {t["time_needed"]}' if t["done"]: info += " ✅" gr.Markdown(info, scale=3)
done_btn = gr.Button("فعلتها", scale=1, variant="primary") not_done_btn = gr.Button("لم أفعلها", scale=1, variant="stop")
done_btn.click( fn=lambda tid=t["id"], c=refresh_counter: (set_done(tid, 1), c)[1] + 1, outputs=refresh_counter, js=CONFETTI_JS, ) not_done_btn.click( fn=lambda tid=t["id"], c=refresh_counter: (set_done(tid, 0), c)[1] + 1, outputs=refresh_counter, js=ANGRY_EMOJI_JS, )
with gr.Tab("إضافة مهمة"): title_in = gr.Textbox(label="عنوان المهمة", placeholder="مثال: ذاكر بايثون") priority_in = gr.Dropdown( label="الأولوية", choices=["منخفض", "عادي", "عالي"], value="عادي" ) time_in = gr.Textbox( label="الوقت اللازم (اختياري)", placeholder="مثال: 30 دقيقة" ) add_btn = gr.Button("إضافة", variant="primary") add_status = gr.Textbox(label="الحالة", interactive=False)
add_btn.click( add_task_ui, inputs=[title_in, priority_in, time_in, refresh_counter], outputs=[refresh_counter, add_status], )
with gr.Column(scale=1, elem_id="chat-col"): gr.Markdown("### 🤖 المساعد الذكي") chatbot = gr.Chatbot(label="", height=420, type="messages", show_label=False) msg = gr.Textbox( label="", placeholder="اكتب طلبك هنا... مثال: احذف مهمة اقرأ كتاب", show_label=False, ) msg.submit( run_agent, inputs=[msg, chatbot, refresh_counter], outputs=[chatbot, msg, refresh_counter], )
demo.launch()<!DOCTYPE html><html lang="ar" dir="rtl" data-theme="paper" data-lang="ar"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>مكتبة إمام المتقين | Imam Al-Muttaqin Library</title><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Amiri:wght@400;700&family=Tajawal:wght@400;500;700&family=Lora:ital,wght@0,500;0,600;1,500&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<!-- ============================================================ Supabase (قاعدة بيانات حقيقية + تسجيل دخول حقيقي - مجاني)============================================================= --><script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.js"></script>
<style> :root{ --radius: 14px; } html[data-theme="paper"]{ --bg:#F6EFDD; --bg-elevated:#FFFDF6; --text:#2B2113; --muted:#8C7B5E; --accent:#0F5C4E; --accent-2:#B9902E; --accent-soft:#E6E0C8; --border:#E3D6B4; --shadow: 0 10px 30px rgba(60,40,10,0.10); } html[data-theme="sepia"]{ --bg:#EFE0BE; --bg-elevated:#F7EED2; --text:#4A3826; --muted:#8a7455; --accent:#8C5A2B; --accent-2:#6E3B2E; --accent-soft:#e6cf9e; --border:#DEC98F; --shadow: 0 10px 30px rgba(80,55,20,0.14); } html[data-theme="night"]{ --bg:#11141B; --bg-elevated:#1A1D29; --text:#EDE7D6; --muted:#9b95a6; --accent:#D4AF37; --accent-2:#4C9A8C; --accent-soft:#2a2717; --border:#2A2D3D; --shadow: 0 10px 30px rgba(0,0,0,0.45); } *{box-sizing:border-box;} body{margin:0; background:var(--bg); color:var(--text); transition:background .25s, color .25s;} html[data-lang="ar"] body{font-family:'Tajawal', sans-serif;} html[data-lang="en"] body{font-family:'Inter', sans-serif;} html[data-lang="ar"] .display{font-family:'Amiri', serif;} html[data-lang="en"] .display{font-family:'Lora', serif;}
#app{min-height:100vh; display:flex; flex-direction:column;}
.ribbon{ height:10px; width:100%; background: repeating-linear-gradient(135deg, var(--accent) 0 6px, transparent 6px 12px), repeating-linear-gradient(45deg, var(--accent-2) 0 6px, transparent 6px 12px); background-size:12px 12px, 12px 12px; background-position:0 0, 6px 0; opacity:.9; } .ribbon.thin{height:4px;}
#loginScreen{ min-height:100vh; display:flex; align-items:center; justify-content:center; padding:24px; background: radial-gradient(circle at 30% 15%, var(--accent-soft), var(--bg) 62%); } .login-card{ width:100%; max-width:400px; background:var(--bg-elevated); border:1px solid var(--border); border-radius: 20px; padding:0 0 30px; box-shadow:var(--shadow); text-align:center; overflow:hidden; } .login-emblem{ width:60px; height:60px; margin:26px auto 14px; border-radius:50%; background:linear-gradient(160deg, var(--accent), var(--accent-2)); display:flex; align-items:center; justify-content:center; color:var(--bg-elevated); font-size:28px; } .login-body{padding:0 28px;} .login-card h1{font-size:23px; margin:0 0 6px; line-height:1.5;} .login-card p.sub{color:var(--muted); font-size:13.5px; margin:0 0 24px;} .authTabs{display:flex; gap:6px; background:var(--bg); border-radius:10px; padding:4px; margin-bottom:18px;} .authTabBtn{flex:1; border:none; background:none; padding:9px; border-radius:8px; cursor:pointer; font-size:13.5px; color:var(--muted); font-family:inherit;} .authTabBtn.active{background:var(--bg-elevated); color:var(--text); font-weight:700; box-shadow:0 1px 5px rgba(0,0,0,.08);} .field{text-align:start; margin-bottom:12px;} .field label{display:block; font-size:12.5px; color:var(--muted); margin-bottom:5px;} .field input{ width:100%; padding:11px 13px; border-radius:10px; border:1px solid var(--border); background:var(--bg); color:var(--text); font-family:inherit; font-size:14px; } .field input:focus, .btn:focus-visible, .chip:focus-visible, .icon-btn:focus-visible{outline:2px solid var(--accent); outline-offset:2px;} .btn{ width:100%; padding:12px 16px; border-radius:10px; border:1px solid var(--border); background:var(--bg-elevated); color:var(--text); font-size:15px; cursor:pointer; display:flex; align-items:center; justify-content:center; gap:10px; margin-bottom:10px; font-family:inherit; transition:transform .12s, background .2s; } .btn:hover{transform:translateY(-1px); background:var(--accent-soft);} .btn.primary{background:linear-gradient(160deg, var(--accent), var(--accent-2)); color:var(--bg-elevated); border-color:transparent; font-weight:700;} .btn.primary:hover{filter:brightness(1.06);} .btn:disabled{opacity:.6; cursor:default; transform:none;} .divider-text{color:var(--muted); font-size:12px; margin:14px 0; display:flex; align-items:center; gap:10px;} .divider-text::before, .divider-text::after{content:""; flex:1; height:1px; background:var(--border);} .guest-link{background:none; border:none; color:var(--muted); text-decoration:underline; cursor:pointer; font-size:13px; font-family:inherit;} .authMsg{font-size:12.5px; padding:9px 12px; border-radius:8px; margin-bottom:12px; text-align:start; display:none;} .authMsg.show{display:block;} .authMsg.err{background:#F4D9D3; color:#7B2D26;} .authMsg.ok{background:#DCEEE6; color:#0F5C4E;} .spinner{width:16px; height:16px; border-radius:50%; border:2px solid rgba(255,255,255,.4); border-top-color:currentColor; animation:spin .7s linear infinite;} @keyframes spin{to{transform:rotate(360deg);}}
.config-warning{ font-size:11.5px; background:var(--accent-soft); color:var(--text); border-radius:10px; padding:10px 12px; margin:16px 28px 0; text-align:start; line-height:1.7; }
.topbar{ display:flex; align-items:center; justify-content:space-between; padding:14px 18px; background:var(--bg-elevated); border-bottom:1px solid var(--border); position:sticky; top:0; z-index:20; } .brand{display:flex; align-items:center; gap:10px;} .brand-mark{width:36px; height:36px; border-radius:9px; background:linear-gradient(160deg, var(--accent), var(--accent-2)); color:var(--bg-elevated); display:flex; align-items:center; justify-content:center; font-size:16px;} .brand-name{font-size:17px; font-weight:700;} .top-controls{display:flex; align-items:center; gap:8px;} .icon-btn{ width:38px; height:38px; border-radius:50%; border:1px solid var(--border); background:var(--bg-elevated); color:var(--text); cursor:pointer; display:flex; align-items:center; justify-content:center; font-size:15px; } select.theme-select{ border:1px solid var(--border); background:var(--bg-elevated); color:var(--text); border-radius:20px; padding:6px 10px; font-size:12px; font-family:inherit; cursor:pointer; } .avatar-btn{ width:38px; height:38px; border-radius:50%; background:linear-gradient(160deg, var(--accent), var(--accent-2)); color:var(--bg-elevated); border:none; font-weight:700; cursor:pointer; font-size:14px; }
main{flex:1; padding:18px 18px 90px; max-width:920px; margin:0 auto; width:100%;} .tab-panel[hidden]{display:none;}
.section-head{display:flex; align-items:baseline; justify-content:space-between; margin-bottom:6px;} .section-head h2{margin:0; font-size:20px;} .muted-line{color:var(--muted); font-size:13px; margin:10px 0 16px;}
.grid{display:grid; grid-template-columns:repeat(auto-fill, minmax(150px,1fr)); gap:14px;} .book-card{ background:var(--bg-elevated); border:1px solid var(--border); border-radius:12px; padding:14px; cursor:pointer; position:relative; overflow:hidden; transition:transform .15s, box-shadow .15s; } .book-card:hover{transform:translateY(-3px); box-shadow:var(--shadow);} .book-card::before{content:""; position:absolute; inset-inline-start:0; top:0; bottom:0; width:5px; background:var(--cat-color, var(--accent));} .book-title{font-weight:700; font-size:15px; margin:4px 0 3px; line-height:1.4;} .book-author{color:var(--muted); font-size:12.5px; margin:0 0 8px;} .book-tag{display:inline-block; font-size:11px; padding:3px 9px; border-radius:20px; background:var(--accent-soft); color:var(--text);} .fav-mark{position:absolute; inset-inline-end:10px; top:10px; font-size:15px;} .skeleton{background:linear-gradient(90deg, var(--accent-soft) 25%, var(--border) 37%, var(--accent-soft) 63%); background-size:400% 100%; animation:shimmer 1.4s ease infinite; border-radius:12px; height:96px;} @keyframes shimmer{0%{background-position:100% 0;}100%{background-position:-100% 0;}}
.empty-state{grid-column:1/-1; text-align:center; padding:48px 20px; color:var(--muted);} .empty-state .ee-icon{font-size:34px; margin-bottom:10px;} .empty-state p{margin:0; font-size:13.5px; line-height:1.8;}
.shuffle-btn{border:1px solid var(--border); background:var(--bg-elevated); color:var(--text); border-radius:20px; padding:8px 16px; cursor:pointer; font-family:inherit; font-size:13px;}
.adhkar-list{display:flex; flex-direction:column; gap:16px;} .adhkar-card{ background:var(--bg-elevated); border:1px solid var(--border); border-radius:16px; padding:26px 22px; text-align:center; position:relative; } .adhkar-card .orn-line{color:var(--accent-2); font-size:19px; letter-spacing:8px; margin-bottom:16px;} .adhkar-card .orn-line.bottom{margin-bottom:0; margin-top:16px;} .adhkar-card .adhkar-text{font-family:'Amiri', serif; font-size:17.5px; line-height:2.4; color:var(--text);} .adhkar-card .adhkar-source{color:var(--accent); font-size:12.5px; font-weight:700; margin-top:14px;}
.search-box{display:flex; gap:8px; margin-bottom:16px;} .search-box input{ flex:1; padding:12px 16px; border-radius:12px; border:1px solid var(--border); background:var(--bg-elevated); color:var(--text); font-family:inherit; font-size:14px; } .chips{display:flex; flex-wrap:wrap; gap:8px; margin-bottom:18px;} .chip{ padding:7px 14px; border-radius:20px; border:1px solid var(--border); background:var(--bg-elevated); color:var(--text); font-size:13px; cursor:pointer; font-family:inherit; } .chip.active{background:var(--accent); color:var(--bg-elevated); border-color:var(--accent);}
.bottom-nav{ position:fixed; bottom:0; inset-inline:0; background:var(--bg-elevated); border-top:1px solid var(--border); display:flex; z-index:20; } .nav-btn{ flex:1; border:none; background:none; padding:12px 0 10px; color:var(--muted); cursor:pointer; display:flex; flex-direction:column; align-items:center; gap:3px; font-size:11px; font-family:inherit; } .nav-btn.active{color:var(--accent); font-weight:700;} .nav-icon{font-size:18px;}
.drawer-overlay{position:fixed; inset:0; background:rgba(0,0,0,.35); z-index:30;} .drawer-overlay[hidden]{display:none;} .drawer{ position:fixed; top:0; bottom:0; width:min(85vw, 340px); background:var(--bg-elevated); z-index:31; box-shadow:var(--shadow); padding:22px; overflow-y:auto; } .drawer[hidden]{display:none;} html[dir="rtl"] .drawer{right:0; border-inline-start:1px solid var(--border);} html[dir="ltr"] .drawer{left:0; border-inline-end:1px solid var(--border);} .drawer-profile{display:flex; align-items:center; gap:12px; margin-bottom:22px;} .drawer-avatar{width:52px; height:52px; border-radius:50%; background:linear-gradient(160deg, var(--accent), var(--accent-2)); color:var(--bg-elevated); display:flex; align-items:center; justify-content:center; font-weight:700; font-size:18px;} .drawer-name{font-weight:700; font-size:16px;} .drawer-sub{color:var(--muted); font-size:12px;} .drawer-tabs{display:flex; gap:6px; margin-bottom:14px; background:var(--bg); border-radius:10px; padding:4px;} .drawer-tab-btn{flex:1; border:none; background:none; padding:8px; border-radius:8px; cursor:pointer; font-size:13px; color:var(--muted); font-family:inherit;} .drawer-tab-btn.active{background:var(--bg-elevated); color:var(--text); font-weight:700; box-shadow:0 1px 4px rgba(0,0,0,.08);} .drawer-list-item{display:flex; justify-content:space-between; gap:8px; padding:10px 0; border-bottom:1px solid var(--border); font-size:13.5px;} .drawer-empty{color:var(--muted); font-size:13px; text-align:center; padding:26px 0;} .drawer-section{margin-top:22px; padding-top:14px; border-top:1px solid var(--border);} .drawer-section h4{margin:0 0 10px; font-size:13px; color:var(--muted); font-weight:700;} .logout-btn{width:100%; margin-top:20px; padding:10px; border-radius:10px; border:1px solid var(--border); background:none; color:var(--accent); cursor:pointer; font-family:inherit; font-weight:600;} .close-drawer{float:inline-end; border:none; background:none; font-size:18px; cursor:pointer; color:var(--muted);}
.modal-overlay{position:fixed; inset:0; background:rgba(0,0,0,.45); z-index:40; display:flex; align-items:center; justify-content:center; padding:20px;} .modal-overlay[hidden]{display:none;} .modal{background:var(--bg-elevated); border-radius:18px; max-width:420px; width:100%; padding:26px; position:relative; box-shadow:var(--shadow); max-height:88vh; overflow-y:auto;} .modal-close{position:absolute; inset-inline-end:16px; top:14px; border:none; background:none; font-size:18px; cursor:pointer; color:var(--muted);} .modal-cover{height:80px; border-radius:10px; margin-bottom:16px; display:flex; align-items:center; justify-content:center; color:#fff; font-size:26px;} .modal h3{margin:0 0 4px;} .modal .modal-author{color:var(--muted); font-size:13px; margin:0 0 14px;} .modal .modal-desc{font-size:13.5px; line-height:1.8; margin-bottom:20px;} .modal-actions{display:flex; flex-direction:column; gap:8px;} .modal-actions .btn{margin-bottom:0;} .rating-row{display:flex; align-items:center; justify-content:center; gap:4px; margin:4px 0 18px;} .rating-row .star{font-size:24px; cursor:pointer; color:var(--border); transition:color .15s;} .rating-row .star.filled{color:var(--accent-2);} .rating-row .rating-summary{color:var(--muted); font-size:12px; margin-inline-start:8px;}
/* ---------- Highlights & Comments (new) ---------- */ .modal-section{margin-top:20px; padding-top:16px; border-top:1px solid var(--border); text-align:start;} .modal-section h4{margin:0 0 10px; font-size:13px; color:var(--muted); font-weight:700;} .add-highlight-row, .add-comment-row{display:flex; flex-direction:column; gap:8px; margin-bottom:14px;} .add-highlight-row textarea, .add-comment-row textarea{ width:100%; min-height:60px; padding:10px 12px; border-radius:10px; border:1px solid var(--border); background:var(--bg); color:var(--text); font-family:inherit; font-size:13.5px; resize:vertical; } .highlight-item{background:var(--accent-soft); border-radius:10px; padding:10px 12px; margin-bottom:8px; font-size:13px;} .highlight-item p{margin:0 0 6px; font-style:italic; line-height:1.6;} .comment-item{border-bottom:1px solid var(--border); padding:10px 0; font-size:13px;} .comment-item:last-child{border-bottom:none;} .comment-head{display:flex; justify-content:space-between; align-items:center; margin-bottom:3px; gap:8px;} .comment-item p{margin:0; line-height:1.7;} .mini-del{border:none; background:none; color:var(--muted); cursor:pointer; font-size:12px; font-family:inherit; flex-shrink:0;} .mini-del:hover{color:var(--accent);}
/* ---------- Confetti (new) ---------- */ @keyframes confetti-fall{ 0%{ transform:translateY(0) rotate(0deg); opacity:1; } 100%{ transform:translateY(105vh) rotate(560deg); opacity:0; } }
.reader-overlay{position:fixed; inset:0; background:var(--bg); z-index:50; display:flex; flex-direction:column;} .reader-overlay[hidden]{display:none;} .reader-topbar{background:var(--bg-elevated); border-bottom:1px solid var(--border); padding:12px 16px; display:flex; align-items:center; justify-content:space-between; gap:10px;} .reader-topbar .rt-side{font-size:12px; color:var(--muted); flex:1;} .reader-topbar .rt-side.rt-end{text-align:end;} .reader-topbar .rt-center{font-weight:700; font-size:14px; color:var(--accent); white-space:nowrap;} .reader-back{border:none; background:none; font-size:16px; color:var(--text); cursor:pointer; padding:0 4px;} .reader-page{flex:1; overflow-y:auto; padding:28px 22px 100px; max-width:640px; margin:0 auto; width:100%;} .reader-page .rp-chapter{font-size:12px; color:var(--accent); font-weight:700; margin-bottom:10px;} .reader-page .rp-text{font-size:16.5px; line-height:2.3;} html[data-lang="ar"] .reader-page .rp-text{font-family:'Amiri', serif;} .reader-nav{position:fixed; bottom:74px; inset-inline:0; display:flex; justify-content:space-between; padding:0 16px; pointer-events:none;} .reader-nav button{pointer-events:auto; width:42px; height:42px; border-radius:50%; border:1px solid var(--border); background:var(--bg-elevated); box-shadow:var(--shadow); cursor:pointer; font-size:16px; color:var(--text);} .reader-bottombar{background:var(--bg-elevated); border-top:1px solid var(--border); display:grid; grid-template-columns:repeat(4,1fr); z-index:51;} .reader-bottombar button{border:none; background:none; padding:10px 4px 12px; display:flex; flex-direction:column; align-items:center; gap:4px; font-size:10.5px; color:var(--text); cursor:pointer; font-family:inherit;} .reader-bottombar button .rb-icon{font-size:18px;}
.toc-overlay{position:fixed; inset:0; background:rgba(0,0,0,.4); z-index:60; display:flex; align-items:flex-end; justify-content:center;} .toc-overlay[hidden]{display:none;} .toc-panel{background:var(--bg-elevated); width:100%; max-width:480px; border-radius:18px 18px 0 0; padding:20px 20px 26px; max-height:70vh; overflow-y:auto;} .toc-panel-head{display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;} .toc-panel-head h4{margin:0; font-size:15px;} .toc-item{display:flex; justify-content:space-between; padding:12px 2px; border-bottom:1px solid var(--border); cursor:pointer; font-size:14px;} .toc-item:hover{color:var(--accent);} .toc-item span.tp{color:var(--muted); font-size:12px;}
.toast{position:fixed; bottom:96px; left:50%; transform:translateX(-50%); background:var(--text); color:var(--bg); padding:10px 20px; border-radius:20px; font-size:13px; z-index:80; opacity:0; pointer-events:none; transition:opacity .25s; white-space:nowrap;} .toast.show{opacity:1;}
::selection{background:var(--accent); color:var(--bg-elevated);} [hidden]{display:none !important;} @media (prefers-reduced-motion: reduce){ *{animation-duration:0.001ms !important; transition-duration:0.001ms !important;} }</style></head><body><div class="ribbon"></div><div id="app">
<!-- LOGIN / SIGNUP SCREEN --> <div id="loginScreen"> <div class="login-card"> <div class="login-emblem">📖</div> <div class="login-body"> <h1 class="display" data-t="appName">مكتبة إمام المتقين</h1> <p class="sub" data-t="loginSubtitle">مكتبتك العربية للقراءة والاكتشاف</p>
<div class="authTabs"> <button class="authTabBtn active" id="authTabLogin" onclick="switchAuthTab('login')" data-t="loginTab">تسجيل الدخول</button> <button class="authTabBtn" id="authTabSignup" onclick="switchAuthTab('signup')" data-t="signupTab">حساب جديد</button> </div>
<div class="authMsg" id="authMsg"></div>
<!-- LOGIN FORM --> <form id="loginForm" onsubmit="return handleLogin(event)"> <div class="field"> <label data-t="emailLabel">البريد الإلكتروني</label> <input type="email" id="loginEmail" required autocomplete="email"> </div> <div class="field"> <label data-t="passwordLabel">كلمة المرور</label> <input type="password" id="loginPassword" required autocomplete="current-password"> </div> <button class="btn primary" type="submit" id="loginSubmitBtn"><span data-t="loginBtn">تسجيل الدخول</span></button> <button type="button" class="guest-link" onclick="handleForgotPassword()" data-t="forgotPassword">نسيت كلمة المرور؟</button> </form>
<!-- SIGNUP FORM --> <form id="signupForm" hidden onsubmit="return handleSignup(event)"> <div class="field"> <label data-t="nameLabel">الاسم</label> <input type="text" id="signupName" required autocomplete="name"> </div> <div class="field"> <label data-t="emailLabel">البريد الإلكتروني</label> <input type="email" id="signupEmail" required autocomplete="email"> </div> <div class="field"> <label data-t="passwordLabel">كلمة المرور</label> <input type="password" id="signupPassword" required minlength="6" autocomplete="new-password"> </div> <button class="btn primary" type="submit" id="signupSubmitBtn"><span data-t="signupBtn">إنشاء حساب</span></button> </form>
<div class="divider-text" data-t="or">أو</div> <button class="btn" onclick="loginWithGoogle()"> <span>G</span><span data-t="continueGoogle">المتابعة عبر Google</span> </button> <button class="guest-link" onclick="continueAsGuest()" data-t="continueGuest">تصفح كضيف بدون حساب</button> </div> <div class="config-warning" id="configWarning" hidden></div> </div> </div>
<!-- MAIN APP --> <div id="mainApp" hidden> <header class="topbar"> <div class="brand"> <div class="brand-mark">📚</div> <div class="brand-name display" data-t="appName">مكتبة إمام المتقين</div> </div> <div class="top-controls"> <select class="theme-select" id="themeSelect" onchange="setTheme(this.value)"> <option value="paper" data-t="themePaper">فاتح</option> <option value="sepia" data-t="themeSepia">ورقي</option> <option value="night" data-t="themeNight">داكن</option> </select> <button class="icon-btn" onclick="toggleLang()" id="langBtn">EN</button> <button class="avatar-btn" id="avatarBtn" onclick="openDrawer()">?</button> </div> </header>
<main> <!-- HOME TAB --> <section class="tab-panel" id="homeTab"> <div class="section-head"> <h2 class="display" data-t="homeTitle">اختيارات لك اليوم</h2> <button class="shuffle-btn" onclick="shuffleHome()" data-t="shuffleBtn">🔀 تبديل</button> </div> <div class="ribbon thin"></div> <p class="muted-line" data-t="homeSub">كتب مختارة من رفوف المكتبة في كل مرة تفتح فيها الصفحة</p> <div class="grid" id="homeGrid"></div> </section>
<!-- SEARCH TAB --> <section class="tab-panel" id="searchTab" hidden> <div class="section-head"> <h2 class="display" data-t="searchTitle">البحث في المكتبة</h2> </div> <div class="ribbon thin"></div> <div class="search-box" style="margin-top:16px;"> <input type="text" id="searchInput" data-t-ph="searchPlaceholder" placeholder="ابحث عن كتاب أو مؤلف..." oninput="renderSearch()"> </div> <p class="muted-line" data-t="categoriesLabel" style="margin-top:0;">التصنيفات</p> <div class="chips" id="categoryChips"></div> <div class="grid" id="searchGrid"></div> </section>
<!-- ADHKAR TAB --> <section class="tab-panel" id="adhkarTab" hidden> <div class="section-head"> <h2 class="display" data-t="adhkarTitle">أذكار أهل البيت</h2> </div> <div class="ribbon thin"></div> <p class="muted-line" data-t="adhkarSub">أذكار وأدعية مختارة، تُضاف من لوحة تحكم المدير</p> <div class="adhkar-list" id="adhkarList"></div> </section> </main>
<nav class="bottom-nav"> <button class="nav-btn active" id="navHome" onclick="switchTab('home')"> <span class="nav-icon">🏠</span><span data-t="navHome">الرئيسية</span> </button> <button class="nav-btn" id="navSearch" onclick="switchTab('search')"> <span class="nav-icon">🔎</span><span data-t="navSearch">البحث</span> </button> <button class="nav-btn" id="navAdhkar" onclick="switchTab('adhkar')"> <span class="nav-icon">📿</span><span data-t="navAdhkar">الأذكار</span> </button> </nav>
<!-- DRAWER (Profile) --> <div class="drawer-overlay" id="drawerOverlay" hidden onclick="closeDrawer()"></div> <aside class="drawer" id="profileDrawer" hidden> <button class="close-drawer" onclick="closeDrawer()">✕</button> <div class="drawer-profile"> <div class="drawer-avatar" id="drawerAvatar">?</div> <div> <div class="drawer-name" id="drawerName">—</div> <div class="drawer-sub" id="drawerSub">—</div> </div> </div> <div class="drawer-tabs"> <button class="drawer-tab-btn active" id="tabFav" onclick="switchDrawerTab('fav')" data-t="favoritesTab">المفضلة</button> <button class="drawer-tab-btn" id="tabHist" onclick="switchDrawerTab('hist')" data-t="historyTab">سجل القراءة</button> </div> <div id="drawerListContainer"></div>
<div class="drawer-section"> <h4 data-t="settingsLabel">الإعدادات</h4> <button class="btn" onclick="toggleLang()"><span data-t="switchLangBtn">التبديل إلى English</span></button> </div>
<button class="logout-btn" onclick="logout()" data-t="logoutBtn">تسجيل الخروج</button> </aside>
<!-- BOOK MODAL --> <div class="modal-overlay" id="modalOverlay" hidden onclick="closeModalOnOverlay(event)"> <div class="modal" id="bookModal"></div> </div>
<div class="toast" id="toast"></div> </div></div>
<script>/* ========================================================================= إعدادات الاتصال بـ Supabase ========================================================================= */const SUPABASE_URL = 'https://nshuwvmaidlagypifyde.supabase.co';const SUPABASE_ANON_KEY = 'sb_publishable_nUbqTqIfATYfIZSPC8auFg_5ubR5cJ6';
const CONFIGURED = SUPABASE_URL.startsWith('http') && SUPABASE_ANON_KEY.length > 20;let supabaseClient = null;if(CONFIGURED){ supabaseClient = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);} else { document.addEventListener('DOMContentLoaded', ()=>{ const w = document.getElementById('configWarning'); w.hidden = false; w.textContent = state && state.lang==='en' ? 'Not connected to a database yet: add your Supabase Project URL and anon key at the top of the script to enable real accounts and books.' : 'لم يتم الربط بقاعدة بيانات بعد: أضف رابط مشروع Supabase والمفتاح العام أعلى الكود لتفعيل الحسابات الحقيقية والكتب.'; });}
/* ---------------- Categories (يمكن لاحقًا سحبها من جدول categories) ---------------- */const CATEGORIES = [ {key:'literature', ar:'أدب', en:'Literature', color:'#0F5C4E'}, {key:'religion', ar:'دين', en:'Religion', color:'#B9902E'}, {key:'history', ar:'تاريخ', en:'History', color:'#7B2D26'}, {key:'spelling', ar:'الإملاء', en:'Spelling', color:'#4C6B8A'}, {key:'morphology', ar:'الصرف', en:'Morphology', color:'#6B4C6B'},];
/* ---------------- الكتب — تُجلب حصرًا من قاعدة البيانات، لا يوجد بيانات وهمية ---------------- */let BOOKS = [];let ADHKAR = [];let RATINGS = [];let COMMENTS = []; // تعليقات الكتاب المفتوح حاليًاlet HIGHLIGHTS = []; // تأشيرات المستخدم الحالي على الكتاب المفتوح
/* ---------------- Translations ---------------- */const I18N = { ar:{ appName:'مكتبة إمام المتقين', loginSubtitle:'مكتبتك العربية للقراءة والاكتشاف', loginTab:'تسجيل الدخول', signupTab:'حساب جديد', emailLabel:'البريد الإلكتروني', passwordLabel:'كلمة المرور', nameLabel:'الاسم', loginBtn:'تسجيل الدخول', signupBtn:'إنشاء حساب', forgotPassword:'نسيت كلمة المرور؟', continueGoogle:'المتابعة عبر Google', or:'أو', continueGuest:'تصفح كضيف بدون حساب', themePaper:'فاتح', themeSepia:'ورقي', themeNight:'داكن', homeTitle:'اختيارات لك اليوم', shuffleBtn:'🔀 تبديل', homeSub:'كتب مختارة من رفوف المكتبة في كل مرة تفتح فيها الصفحة', searchTitle:'البحث في المكتبة', searchPlaceholder:'ابحث عن كتاب أو مؤلف...', categoriesLabel:'التصنيفات', navHome:'الرئيسية', navSearch:'البحث', navAdhkar:'الأذكار', adhkarTitle:'أذكار أهل البيت', adhkarSub:'أذكار وأدعية مختارة، تُضاف من لوحة تحكم المدير', emptyAdhkar:'أذكار أهل البيت فارغة حاليًا', emptyAdhkarDesc:'أضف أذكارًا من لوحة تحكم المدير لتظهر هنا فورًا لجميع المستخدمين.', favoritesTab:'المفضلة', historyTab:'سجل القراءة', settingsLabel:'الإعدادات', switchLangBtn:'التبديل إلى English', logoutBtn:'تسجيل الخروج', by:'تأليف', addFav:'➕ أضف إلى المفضلة', removeFav:'✓ في المفضلة', markRead:'📖 وضع علامة مقروء', markedRead:'✓ تمت قراءته', emptyFav:'لا توجد كتب في المفضلة بعد. أضف كتابًا من المكتبة!', emptyHist:'لم تُسجَّل قراءة أي كتاب بعد.', noResults:'لا توجد نتائج مطابقة', guestName:'ضيف', guestSub:'وضع الضيف — لن تُحفظ مفضلتك أو سجل قراءتك', readBtn:'📖 قراءة الكتاب', noPdfMsg:'لم يتم رفع ملف PDF لهذا الكتاب بعد', emptyLibrary:'المكتبة فارغة حاليًا', emptyLibraryDesc:'أضف كتبًا من لوحة تحكم المدير لتظهر هنا فورًا لجميع المستخدمين.', notConnected:'لم يتم الاتصال بقاعدة البيانات بعد', notConnectedDesc:'أضف بيانات Supabase أعلى ملف الكود لتفعيل الحسابات والكتب.', loading:'جارِ التحميل...', errInvalidCreds:'البريد الإلكتروني أو كلمة المرور غير صحيحة', errEmailTaken:'هذا البريد مستخدم بالفعل', errGeneric:'حدث خطأ، حاول مرة أخرى', errWeakPass:'كلمة المرور يجب أن تكون 6 أحرف على الأقل', checkEmailMsg:'تم إرسال رابط تأكيد إلى بريدك الإلكتروني', resetSentMsg:'تم إرسال رابط استعادة كلمة المرور إلى بريدك', needAccountMsg:'سجّل دخولك لحفظ المفضلة وسجل القراءة', highlightsLabel:'تأشيراتي', highlightPlaceholder:'اكتب مقطعًا تريد تمييزه أو ملاحظة...', saveHighlightBtn:'💾 حفظ التأشير', noHighlights:'لا توجد تأشيرات بعد', commentsLabel:'التعليقات', commentPlaceholder:'شارك رأيك حول الكتاب...', postCommentBtn:'📝 نشر التعليق', noComments:'لا توجد تعليقات بعد، كن أول من يعلق', deleteBtn:'حذف', }, en:{ appName:'Imam Al-Muttaqin Library', loginSubtitle:'Your Arabic library for reading and discovery', loginTab:'Log in', signupTab:'Create account', emailLabel:'Email', passwordLabel:'Password', nameLabel:'Name', loginBtn:'Log in', signupBtn:'Create account', forgotPassword:'Forgot password?', continueGoogle:'Continue with Google', or:'or', continueGuest:'Browse as guest', themePaper:'Light', themeSepia:'Sepia', themeNight:'Dark', homeTitle:'Picked for you today', shuffleBtn:'🔀 Shuffle', homeSub:'A selection from the library shelves, refreshed each visit', searchTitle:'Search the library', searchPlaceholder:'Search for a book or author...', categoriesLabel:'Categories', navHome:'Home', navSearch:'Search', navAdhkar:'Adhkar', adhkarTitle:'Ahlul Bayt Adhkar', adhkarSub:'Selected supplications and remembrances, added from the admin dashboard', emptyAdhkar:'No adhkar added yet', emptyAdhkarDesc:'Add adhkar from the admin dashboard and they will appear here instantly for every user.', favoritesTab:'Favorites', historyTab:'Reading history', settingsLabel:'Settings', switchLangBtn:'Switch to العربية', logoutBtn:'Log out', by:'by', addFav:'➕ Add to favorites', removeFav:'✓ In favorites', markRead:'📖 Mark as read', markedRead:'✓ Read', emptyFav:'No favorites yet. Add a book from the library!', emptyHist:'No books marked as read yet.', noResults:'No matching results', guestName:'Guest', guestSub:'Guest mode — favorites and history won\'t be saved', readBtn:'📖 Read book', noPdfMsg:'No PDF has been uploaded for this book yet', emptyLibrary:'The library is empty right now', emptyLibraryDesc:'Add books from the admin dashboard and they will appear here instantly for every user.', notConnected:'Not connected to a database yet', notConnectedDesc:'Add your Supabase credentials at the top of the code to enable accounts and books.', loading:'Loading...', errInvalidCreds:'Incorrect email or password', errEmailTaken:'This email is already registered', errGeneric:'Something went wrong, please try again', errWeakPass:'Password must be at least 6 characters', checkEmailMsg:'A confirmation link has been sent to your email', resetSentMsg:'A password reset link has been sent to your email', needAccountMsg:'Log in to save favorites and reading history', highlightsLabel:'My Highlights', highlightPlaceholder:'Write a passage or note to save...', saveHighlightBtn:'💾 Save highlight', noHighlights:'No highlights yet', commentsLabel:'Comments', commentPlaceholder:'Share your thoughts about the book...', postCommentBtn:'📝 Post comment', noComments:'No comments yet, be the first', deleteBtn:'Delete', }};
/* ---------------- State ---------------- */let state = { lang:'ar', theme:'paper', loggedIn:false, isGuest:false, user:null, favorites:new Set(), history:new Set(), myRatings:{}, activeTab:'home', drawerTab:'fav', selectedCategory:null, homeShuffled:[], booksLoaded:false, readerBookId:null, currentPage:1, bookmarks:{},};let authMode = 'login';
function catInfo(key){ return CATEGORIES.find(c=>c.key===key) || {ar:key, en:key, color:'#0F5C4E'}; }function t(key){ return I18N[state.lang][key] || key; }function escapeHtml(str){ return (str||'').replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}
/* ---------------- Auth: forms & tabs ---------------- */function switchAuthTab(mode){ authMode = mode; document.getElementById('authTabLogin').classList.toggle('active', mode==='login'); document.getElementById('authTabSignup').classList.toggle('active', mode==='signup'); document.getElementById('loginForm').hidden = mode !== 'login'; document.getElementById('signupForm').hidden = mode !== 'signup'; hideAuthMsg();}function showAuthMsg(text, type){ const el = document.getElementById('authMsg'); el.textContent = text; el.className = 'authMsg show ' + type;}function hideAuthMsg(){ document.getElementById('authMsg').className = 'authMsg';}function setBtnLoading(btnId, loading, labelKey){ const btn = document.getElementById(btnId); btn.disabled = loading; btn.innerHTML = loading ? '<span class="spinner"></span>' : `<span data-t="${labelKey}">${t(labelKey)}</span>`;}
/* ---------------- Auth: real Supabase accounts ---------------- */async function handleLogin(e){ e.preventDefault(); if(!requireConfig()) return false; hideAuthMsg(); const email = document.getElementById('loginEmail').value.trim(); const password = document.getElementById('loginPassword').value; setBtnLoading('loginSubmitBtn', true); const { data, error } = await supabaseClient.auth.signInWithPassword({ email, password }); setBtnLoading('loginSubmitBtn', false, 'loginBtn'); if(error){ showAuthMsg(error.message.includes('Invalid') ? t('errInvalidCreds') : t('errGeneric'), 'err'); return false; } await onAuthenticated(data.user); return false;}async function handleSignup(e){ e.preventDefault(); if(!requireConfig()) return false; hideAuthMsg(); const name = document.getElementById('signupName').value.trim(); const email = document.getElementById('signupEmail').value.trim(); const password = document.getElementById('signupPassword').value; if(password.length < 6){ showAuthMsg(t('errWeakPass'), 'err'); return false; } setBtnLoading('signupSubmitBtn', true); const { data, error } = await supabaseClient.auth.signUp({ email, password, options:{ data:{ full_name:name } } }); setBtnLoading('signupSubmitBtn', false, 'signupBtn'); if(error){ showAuthMsg(error.message.includes('already') ? t('errEmailTaken') : t('errGeneric'), 'err'); return false; } if(data.session){ await onAuthenticated(data.user); } else { showAuthMsg(t('checkEmailMsg'), 'ok'); } return false;}async function loginWithGoogle(){ if(!requireConfig()) return; await supabaseClient.auth.signInWithOAuth({ provider:'google' });}async function handleForgotPassword(){ if(!requireConfig()) return; const email = document.getElementById('loginEmail').value.trim(); if(!email){ showAuthMsg(t('emailLabel'), 'err'); return; } const { error } = await supabaseClient.auth.resetPasswordForEmail(email); showAuthMsg(error ? t('errGeneric') : t('resetSentMsg'), error ? 'err' : 'ok');}function requireConfig(){ if(!CONFIGURED){ showAuthMsg(t('notConnected') + ' — ' + t('notConnectedDesc'), 'err'); return false; } return true;}function continueAsGuest(){ state.isGuest = true; state.loggedIn = true; state.user = { name:t('guestName'), sub:t('guestSub'), initial:'؟' }; enterApp();}async function onAuthenticated(user){ state.isGuest = false; state.loggedIn = true; const fullName = user.user_metadata && user.user_metadata.full_name ? user.user_metadata.full_name : user.email; state.user = { id:user.id, name:fullName, sub:user.email, initial:(fullName||'?').trim().charAt(0).toUpperCase() }; await loadUserData(); enterApp();}async function logout(){ closeDrawer(); if(supabaseClient && !state.isGuest){ await supabaseClient.auth.signOut(); } state.loggedIn = false; state.isGuest = false; state.user = null; state.favorites = new Set(); state.history = new Set(); state.bookmarks = {}; document.getElementById('mainApp').hidden = true; document.getElementById('loginScreen').hidden = false; document.getElementById('loginForm').reset(); document.getElementById('signupForm').reset();}function enterApp(){ document.getElementById('loginScreen').hidden = true; document.getElementById('mainApp').hidden = false; Promise.all([loadBooks(), loadAdhkar(), loadRatings()]).then(()=>{ shuffleHome(); renderAll(); });}
/* على تحميل الصفحة: تحقق من وجود جلسة محفوظة (تسجيل دخول تلقائي) */window.addEventListener('DOMContentLoaded', async ()=>{ if(!CONFIGURED) return; const { data } = await supabaseClient.auth.getSession(); if(data.session && data.session.user){ await onAuthenticated(data.session.user); }});
/* ---------------- جلب الكتب من قاعدة البيانات (جدول books) ---------------- */async function loadBooks(){ const grid = document.getElementById('homeGrid'); if(grid) grid.innerHTML = Array(6).fill('<div class="skeleton"></div>').join(''); if(!CONFIGURED){ BOOKS = []; state.booksLoaded = true; return; } const { data, error } = await supabaseClient .from('books') .select('*') .order('created_at', { ascending:false }); if(error){ console.error(error); BOOKS = []; } else { BOOKS = (data || []).map(row => ({ id: row.id, cat: row.category, title: { ar:row.title_ar, en:row.title_en }, author: { ar:row.author_ar, en:row.author_en }, desc: { ar:row.desc_ar, en:row.desc_en }, color: row.cover_color, pdfUrl: row.pdf_url, totalPages: row.total_pages, })); } state.booksLoaded = true;}
/* ---------------- جلب أذكار أهل البيت من قاعدة البيانات (جدول adhkar) ---------------- */async function loadAdhkar(){ if(!CONFIGURED){ ADHKAR = []; return; } const { data, error } = await supabaseClient .from('adhkar') .select('*') .order('created_at', { ascending:false }); if(error){ console.error(error); ADHKAR = []; } else { ADHKAR = (data || []).map(row => ({ id: row.id, text: row.text_ar, source: row.source, ornament: row.ornament || 'hizb', })); }}function ornamentBar(key){ const map = {hizb:'۞', star8:'✦ ✧ ✦', floral:'❧ ❧ ❧', classic:'﴾ ﴿'}; return map[key] || map.hizb;}function renderAdhkar(){ const list = document.getElementById('adhkarList'); if(!ADHKAR.length){ list.innerHTML = `<div class="empty-state"> <div class="ee-icon">📿</div> <p><strong>${t('emptyAdhkar')}</strong><br>${t('emptyAdhkarDesc')}</p> </div>`; return; } list.innerHTML = ADHKAR.map(a=>` <div class="adhkar-card"> <div class="orn-line">${ornamentBar(a.ornament)}</div> <p class="adhkar-text">${a.text||''}</p> ${a.source ? `<div class="adhkar-source">— ${a.source}</div>` : ''} <div class="orn-line bottom">${ornamentBar(a.ornament)}</div> </div> `).join('');}
/* ---------------- تقييمات الكتب (نجوم) ---------------- */async function loadRatings(){ if(!CONFIGURED){ RATINGS = []; return; } const { data, error } = await supabaseClient.from('book_ratings').select('book_id, rating'); if(error){ console.error(error); RATINGS = []; } else { RATINGS = data || []; }}function ratingStatsFor(bookId){ const rows = RATINGS.filter(r=>String(r.book_id)===String(bookId)); if(!rows.length) return { avg:0, count:0 }; const sum = rows.reduce((s,r)=>s+r.rating, 0); return { avg: sum/rows.length, count: rows.length };}async function rateBook(id, value){ if(state.isGuest){ showToast(t('needAccountMsg')); return; } if(!CONFIGURED || !state.user) return; state.myRatings[id] = value; await supabaseClient.from('book_ratings').upsert({ user_id: state.user.id, book_id: id, rating: value }, { onConflict:'user_id,book_id' }); await loadRatings(); openBookModal(id);}
/* ---------------- التعليقات على الكتاب (جدول book_comments) ---------------- */async function loadComments(bookId){ if(!CONFIGURED){ COMMENTS = []; return; } const { data, error } = await supabaseClient .from('book_comments') .select('*') .eq('book_id', bookId) .order('created_at', { ascending:false }); COMMENTS = error ? [] : (data || []);}function commentsListHtml(){ if(!COMMENTS.length) return `<p class="drawer-empty">${t('noComments')}</p>`; return COMMENTS.map(c=>` <div class="comment-item"> <div class="comment-head"> <strong>${escapeHtml(c.user_name || '')}</strong> ${(state.user && !state.isGuest && c.user_id===state.user.id) ? `<button class="mini-del" onclick="deleteComment('${c.id}','${c.book_id}')">✕ ${t('deleteBtn')}</button>` : ''} </div> <p>${escapeHtml(c.text)}</p> </div>`).join('');}async function addComment(bookId){ if(state.isGuest){ showToast(t('needAccountMsg')); return; } const input = document.getElementById('commentInput'); if(!input) return; const text = input.value.trim(); if(!text || !CONFIGURED || !state.user) return; await supabaseClient.from('book_comments').insert({ book_id: bookId, user_id: state.user.id, user_name: state.user.name, text }); input.value = ''; await loadComments(bookId); const list = document.getElementById('commentsList'); if(list) list.innerHTML = commentsListHtml();}async function deleteComment(commentId, bookId){ if(!CONFIGURED) return; await supabaseClient.from('book_comments').delete().eq('id', commentId); await loadComments(bookId); const list = document.getElementById('commentsList'); if(list) list.innerHTML = commentsListHtml();}
/* ---------------- تأشيرات المستخدم على الكتاب (جدول book_highlights) ---------------- */async function loadHighlights(bookId){ if(!CONFIGURED || !state.user || state.isGuest){ HIGHLIGHTS = []; return; } const { data, error } = await supabaseClient .from('book_highlights') .select('*') .eq('book_id', bookId) .eq('user_id', state.user.id) .order('created_at', { ascending:false }); HIGHLIGHTS = error ? [] : (data || []);}function highlightsListHtml(){ if(!HIGHLIGHTS.length) return `<p class="drawer-empty">${t('noHighlights')}</p>`; return HIGHLIGHTS.map(h=>` <div class="highlight-item"> <p>"${escapeHtml(h.text)}"</p> <button class="mini-del" onclick="deleteHighlight('${h.id}','${h.book_id}')">✕ ${t('deleteBtn')}</button> </div>`).join('');}async function addHighlight(bookId){ if(state.isGuest){ showToast(t('needAccountMsg')); return; } const input = document.getElementById('highlightInput'); if(!input) return; const text = input.value.trim(); if(!text || !CONFIGURED || !state.user) return; await supabaseClient.from('book_highlights').insert({ book_id: bookId, user_id: state.user.id, text }); input.value = ''; await loadHighlights(bookId); const list = document.getElementById('highlightsList'); if(list) list.innerHTML = highlightsListHtml();}async function deleteHighlight(id, bookId){ if(!CONFIGURED) return; await supabaseClient.from('book_highlights').delete().eq('id', id); await loadHighlights(bookId); const list = document.getElementById('highlightsList'); if(list) list.innerHTML = highlightsListHtml();}
/* ---------------- احتفال 🎉 عند إنهاء قراءة كتاب ---------------- */function burstConfetti(){ const colors = ['#0F5C4E','#B9902E','#7B2D26','#4C6B8A','#D4AF37']; const container = document.createElement('div'); container.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:200;overflow:hidden;'; document.body.appendChild(container); for(let i=0;i<60;i++){ const piece = document.createElement('span'); const size = 6 + Math.random()*6; piece.style.cssText = ` position:absolute; top:-20px; left:${Math.random()*100}%; width:${size}px; height:${size*0.4}px; background:${colors[Math.floor(Math.random()*colors.length)]}; opacity:${0.8+Math.random()*0.2}; transform:rotate(${Math.random()*360}deg); animation: confetti-fall ${1.6+Math.random()*1.4}s ease-in ${Math.random()*0.3}s forwards; `; container.appendChild(piece); } setTimeout(()=> container.remove(), 3200);}
/* ---------------- تحميل مفضلة/سجل/علامات المستخدم من قاعدة البيانات ---------------- */async function loadUserData(){ if(!CONFIGURED || !state.user || !state.user.id) return; const uid = state.user.id; const [{ data: favs }, { data: hist }, { data: bms }, { data: myRates }] = await Promise.all([ supabaseClient.from('favorites').select('book_id').eq('user_id', uid), supabaseClient.from('reading_history').select('book_id').eq('user_id', uid), supabaseClient.from('bookmarks').select('book_id, page').eq('user_id', uid), supabaseClient.from('book_ratings').select('book_id, rating').eq('user_id', uid), ]); state.favorites = new Set((favs||[]).map(r=>r.book_id)); state.history = new Set((hist||[]).map(r=>r.book_id)); state.bookmarks = {}; (bms||[]).forEach(r=>{ state.bookmarks[r.book_id] = r.page; }); state.myRatings = {}; (myRates||[]).forEach(r=>{ state.myRatings[r.book_id] = r.rating; });}
/* ---------------- Theme & Language ---------------- */function setTheme(theme){ state.theme = theme; document.documentElement.setAttribute('data-theme', theme);}function toggleLang(){ state.lang = state.lang === 'ar' ? 'en' : 'ar'; document.documentElement.lang = state.lang; document.documentElement.dir = state.lang === 'ar' ? 'rtl' : 'ltr'; document.documentElement.setAttribute('data-lang', state.lang); document.getElementById('langBtn').textContent = state.lang === 'ar' ? 'EN' : 'AR'; renderAll();}function applyStaticTranslations(){ document.querySelectorAll('[data-t]').forEach(el=>{ el.textContent = t(el.getAttribute('data-t')); }); document.querySelectorAll('[data-t-ph]').forEach(el=>{ el.setAttribute('placeholder', t(el.getAttribute('data-t-ph'))); });}
/* ---------------- Tabs ---------------- */function switchTab(tab){ state.activeTab = tab; document.getElementById('homeTab').hidden = tab !== 'home'; document.getElementById('searchTab').hidden = tab !== 'search'; document.getElementById('adhkarTab').hidden = tab !== 'adhkar'; document.getElementById('navHome').classList.toggle('active', tab==='home'); document.getElementById('navSearch').classList.toggle('active', tab==='search'); document.getElementById('navAdhkar').classList.toggle('active', tab==='adhkar'); if(tab==='search') renderSearch(); if(tab==='adhkar') renderAdhkar();}
/* ---------------- Home ---------------- */function shuffleHome(){ const shuffled = [...BOOKS].sort(()=>Math.random()-0.5); state.homeShuffled = shuffled.slice(0,8); renderHomeGrid();}function renderHomeGrid(){ const grid = document.getElementById('homeGrid'); if(!state.homeShuffled.length){ grid.innerHTML = emptyStateHtml(); return; } grid.innerHTML = state.homeShuffled.map(bookCardHtml).join('');}function emptyStateHtml(){ return `<div class="empty-state"> <div class="ee-icon">📭</div> <p><strong>${t('emptyLibrary')}</strong><br>${t('emptyLibraryDesc')}</p> </div>`;}
/* ---------------- Search ---------------- */function renderCategoryChips(){ const chips = CATEGORIES.map(c=>{ const active = state.selectedCategory === c.key; return `<button class="chip ${active?'active':''}" onclick="selectCategory('${c.key}')">${state.lang==='ar'?c.ar:c.en}</button>`; }).join(''); const allChip = `<button class="chip ${state.selectedCategory===null?'active':''}" onclick="selectCategory(null)">${state.lang==='ar'?'الكل':'All'}</button>`; document.getElementById('categoryChips').innerHTML = allChip + chips;}function selectCategory(key){ state.selectedCategory = key; renderCategoryChips(); renderSearch();}function renderSearch(){ const query = (document.getElementById('searchInput')?.value || '').trim().toLowerCase(); let results = BOOKS.filter(b=>{ const matchesCat = !state.selectedCategory || b.cat === state.selectedCategory; const matchesQuery = !query || (b.title.ar||'').toLowerCase().includes(query) || (b.title.en||'').toLowerCase().includes(query) || (b.author.ar||'').toLowerCase().includes(query) || (b.author.en||'').toLowerCase().includes(query); return matchesCat && matchesQuery; }); const grid = document.getElementById('searchGrid'); if(!BOOKS.length){ grid.innerHTML = emptyStateHtml(); return; } grid.innerHTML = results.length ? results.map(bookCardHtml).join('') : `<p class="drawer-empty" style="grid-column:1/-1;">${t('noResults')}</p>`;}
/* ---------------- Book cards & modal ---------------- */function bookCardHtml(b){ const info = catInfo(b.cat); const isFav = state.favorites.has(b.id); return `<div class="book-card" style="--cat-color:${b.color||info.color}" onclick="openBookModal('${b.id}')"> ${isFav ? '<span class="fav-mark">⭐</span>' : ''} <span class="book-tag">${state.lang==='ar'?info.ar:info.en}</span> <div class="book-title">${b.title[state.lang]}</div> <div class="book-author">${t('by')} ${b.author[state.lang]}</div> </div>`;}async function openBookModal(id){ const b = BOOKS.find(x=>String(x.id)===String(id)); if(!b) return;
await Promise.all([loadComments(b.id), loadHighlights(b.id)]);
const info = catInfo(b.cat); const isFav = state.favorites.has(b.id); const isRead = state.history.has(b.id); const myRating = state.myRatings[b.id] || 0; const { avg, count } = ratingStatsFor(b.id); const starsHtml = [1,2,3,4,5].map(n=> `<span class="star ${n<=myRating?'filled':''}" onclick="rateBook('${b.id}', ${n})">★</span>` ).join('');
document.getElementById('bookModal').innerHTML = ` <button class="modal-close" onclick="closeModal()">✕</button> <div class="modal-cover" style="background:${b.color||info.color}">📕</div> <h3 class="display">${b.title[state.lang]}</h3> <p class="modal-author">${t('by')} ${b.author[state.lang]} · ${state.lang==='ar'?info.ar:info.en}</p> <p class="modal-desc">${b.desc[state.lang]||''}</p> <div class="rating-row">${starsHtml}<span class="rating-summary">${count ? avg.toFixed(1)+' ('+count+')' : ''}</span></div> <div class="modal-actions"> <button class="btn primary" onclick="readBook('${b.id}')">${t('readBtn')}</button> <button class="btn ${isFav?'primary':''}" onclick="toggleFav('${b.id}')">${isFav?t('removeFav'):t('addFav')}</button> <button class="btn ${isRead?'primary':''}" onclick="toggleRead('${b.id}')">${isRead?t('markedRead'):t('markRead')}</button> ${state.isGuest ? `<p class="muted-line" style="margin:2px 0 0;">${t('needAccountMsg')}</p>` : ''} </div>
<div class="modal-section"> <h4>${t('highlightsLabel')}</h4> ${state.isGuest ? `<p class="muted-line" style="margin:0 0 10px;">${t('needAccountMsg')}</p>` : ` <div class="add-highlight-row"> <textarea id="highlightInput" placeholder="${t('highlightPlaceholder')}"></textarea> <button class="btn" onclick="addHighlight('${b.id}')">${t('saveHighlightBtn')}</button> </div> `} <div id="highlightsList">${highlightsListHtml()}</div> </div>
<div class="modal-section"> <h4>${t('commentsLabel')}</h4> ${state.isGuest ? '' : ` <div class="add-comment-row"> <textarea id="commentInput" placeholder="${t('commentPlaceholder')}"></textarea> <button class="btn" onclick="addComment('${b.id}')">${t('postCommentBtn')}</button> </div> `} <div id="commentsList">${commentsListHtml()}</div> </div> `; document.getElementById('modalOverlay').hidden = false;}function closeModal(){ document.getElementById('modalOverlay').hidden = true; }function closeModalOnOverlay(e){ if(e.target.id==='modalOverlay') closeModal(); }
async function toggleFav(id){ if(state.isGuest){ showToast(t('needAccountMsg')); return; } const has = state.favorites.has(id); if(has){ state.favorites.delete(id); } else { state.favorites.add(id); } openBookModal(id); renderHomeGrid(); renderSearch(); renderDrawerList(); if(!CONFIGURED || !state.user) return; if(has){ await supabaseClient.from('favorites').delete().eq('user_id', state.user.id).eq('book_id', id); } else { await supabaseClient.from('favorites').insert({ user_id: state.user.id, book_id: id }); }}async function toggleRead(id){ if(state.isGuest){ showToast(t('needAccountMsg')); return; } const has = state.history.has(id); if(has){ state.history.delete(id); } else { state.history.add(id); burstConfetti(); } openBookModal(id); renderDrawerList(); if(!CONFIGURED || !state.user) return; if(has){ await supabaseClient.from('reading_history').delete().eq('user_id', state.user.id).eq('book_id', id); } else { await supabaseClient.from('reading_history').insert({ user_id: state.user.id, book_id: id }); }}
/* ---------------- فتح ملف الكتاب (PDF) ---------------- */function readBook(id){ const book = BOOKS.find(b=>String(b.id)===String(id)); if(!book) return; if(!book.pdfUrl){ showToast(t('noPdfMsg')); return; } if(CONFIGURED){ supabaseClient.rpc('increment_book_views', { p_book_id: id }).then(()=>{}); } if(!state.history.has(id)){ toggleRead(id); } window.open(book.pdfUrl, '_blank');}function showToast(msg){ const el = document.getElementById('toast'); el.textContent = msg; el.classList.add('show'); clearTimeout(window._toastTimer); window._toastTimer = setTimeout(()=> el.classList.remove('show'), 1800);}
/* ---------------- Drawer (profile) ---------------- */function openDrawer(){ document.getElementById('drawerOverlay').hidden = false; document.getElementById('profileDrawer').hidden = false; document.getElementById('drawerAvatar').textContent = state.user.initial; document.getElementById('drawerName').textContent = state.user.name; document.getElementById('drawerSub').textContent = state.user.sub; document.getElementById('avatarBtn').textContent = state.user.initial; renderDrawerList();}function closeDrawer(){ document.getElementById('drawerOverlay').hidden = true; document.getElementById('profileDrawer').hidden = true;}function switchDrawerTab(tab){ state.drawerTab = tab; document.getElementById('tabFav').classList.toggle('active', tab==='fav'); document.getElementById('tabHist').classList.toggle('active', tab==='hist'); renderDrawerList();}function renderDrawerList(){ const container = document.getElementById('drawerListContainer'); const ids = state.drawerTab === 'fav' ? [...state.favorites] : [...state.history]; if(!ids.length){ container.innerHTML = `<div class="drawer-empty">${state.drawerTab==='fav'?t('emptyFav'):t('emptyHist')}</div>`; return; } container.innerHTML = ids.map(id=>{ const b = BOOKS.find(x=>String(x.id)===String(id)); if(!b) return ''; return `<div class="drawer-list-item"><span>${b.title[state.lang]}</span><span style="color:var(--muted)">${b.author[state.lang]}</span></div>`; }).join('');}
/* ---------------- Simple edge-swipe to open drawer ---------------- */let touchStartX = null;document.addEventListener('touchstart', e=>{ if(!state.loggedIn) return; touchStartX = e.touches[0].clientX;});document.addEventListener('touchend', e=>{ if(!state.loggedIn || touchStartX===null) return; const endX = e.changedTouches[0].clientX; const dx = endX - touchStartX; const edge = document.documentElement.dir==='rtl' ? window.innerWidth - touchStartX < 30 && dx < -60 : touchStartX < 30 && dx > 60; if(edge) openDrawer(); touchStartX = null;});
/* ---------------- Full render ---------------- */function renderAll(){ applyStaticTranslations(); renderHomeGrid(); renderCategoryChips(); renderSearch(); if(!document.getElementById('adhkarTab').hidden) renderAdhkar(); if(!document.getElementById('profileDrawer').hidden) openDrawer();}</script></body></html>index.html+1152-344