Spaces:
Running
Running
Update index.html
Browse files2 unmodified lines3456678910111213141516171819201221221516232425262720282930232431323334354 unmodified lines4041424344454647484950515253545556573858596041426162636445466566676848496970717273747576777879808182838485868756578889909192939495969798991001011021031041051061 unmodified line10810911068691111121131141154 unmodified lines120121122801231241251262 unmodified lines1291301318990911321331341356 unmodified lines1421431441451461471481491501511521539 unmodified lines16316416511912012116616716812 unmodified lines1811821831401841851861871881891461901911921939 unmodified lines20320420516220620720820939 unmodified lines2492502512522532542552562572582132592602612622172182192202212222232242252262272282292632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133142 unmodified lines31731831923832032132232313 unmodified lines3373383392582593403413423433442 unmodified lines34734834926826935035135235327235435527427527627735635735826 unmodified lines38538638731038838939042 unmodified lines43343443535943643743843944044144244344444544644744844945045145245345445545645736136245845946046146246336736836937037137237337437537637737837938038138238338438538638738838939039139239339446446546646746846947039940040147147247347447547640347747840547940748048148248341148448548648748841648949049149249349449549649749841942042149950050150250350442350550642550742750850951051143151251351451551643651751851952052152252352452552652752852944253053153244553353453553653744945053853954045345445545645745845946054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960046260160246446546646746860360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363447047163563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970035 unmodified lines7367377387397407417427435167447457467477487497507517527537545217557567577585 unmodified lines7647657665335345355365375385395405415425437677687697707715495507727737747757767777787797802 unmodified lines7837847855627867877887891 unmodified line79179279357079479579657257379779879980057680180280357980480558158258380680780880981081181281381458959081581681781881982082182282382482582682759359482882983083183283383483583683783883984059884184284384460284584684784818 unmodified lines8678688696278708718728733 unmodified lines8778788798808818826396408838848856426438868878888894 unmodified lines8948958966548978988999003 unmodified lines90490590666490790890991091191291367191491591691791891992092192292336 unmodified lines9609619627169639649659669672 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>مكتبة الوَرّاق | Al-Warraq Library</title><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 (قاعدة بيانات حقيقية + تسجيل دخول حقيقي - مجاني) 1) أنشئي مشروعًا مجانيًا على supabase.com 2) الصقي Project URL و anon public key بالأسفل 3) نفّذي كود SQL الموجود في ملف SETUP.sql المرفق لإنشاء الجداول============================================================= --><script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.js"></script>
<style> :root{ --radius: 14px; --shelf: #8a5a35; } html[data-theme="paper"]{ --bg:#FAF7F1; --bg-elevated:#FFFFFF; --text:#2A2620; --muted:#7a7266; --accent:#7B2D26; --accent-soft:#F1E1DA; --border:#E4DCC8; --shadow: 0 10px 30px rgba(60,40,20,0.08); --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-soft:#e6cf9e; --border:#DEC98F; --shadow: 0 10px 30px rgba(80,55,20,0.14); --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:#12141C; --bg-elevated:#1B1E2B; --text:#E9E4D6; --muted:#9b95a6; --accent:#D4AF37; --accent-soft:#2a2717; --border:#2A2D3D; --shadow: 0 10px 30px rgba(0,0,0,0.4); --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;}4 unmodified lines
#app{min-height:100vh; display:flex; flex-direction:column;}
/* ---------- signature: illuminated-manuscript ribbon ---------- */ .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;}
/* ---------- Login screen ---------- */ #loginScreen{ min-height:100vh; display:flex; align-items:center; justify-content:center; padding:24px; background: radial-gradient(circle at 30% 20%, var(--accent-soft), var(--bg) 60%); background: radial-gradient(circle at 30% 15%, var(--accent-soft), var(--bg) 62%); } .login-card{ width:100%; max-width:380px; background:var(--bg-elevated); border:1px solid var(--border); border-radius: 20px; padding:36px 28px; box-shadow:var(--shadow); text-align:center; 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:56px; height:56px; margin:0 auto 18px; border-radius:50%; background:var(--accent); display:flex; align-items:center; justify-content:center; color:var(--bg-elevated); font-size:26px; 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-card h1{font-size:24px; margin:0 0 6px;} .login-card p.sub{color:var(--muted); font-size:14px; margin:0 0 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:var(--accent); color:var(--bg-elevated); border-color:var(--accent); font-weight:600;} .btn.primary:hover{filter:brightness(1.05);} .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; }
/* ---------- Top bar ---------- */ .topbar{1 unmodified line 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:34px; height:34px; border-radius:9px; background:var(--accent); color:var(--bg-elevated); display:flex; align-items:center; justify-content:center; font-size:16px;} .brand-name{font-size:18px; font-weight:700;} .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);4 unmodified lines padding:6px 10px; font-size:12px; font-family:inherit; cursor:pointer; } .avatar-btn{ width:38px; height:38px; border-radius:50%; background:var(--accent); color:var(--bg-elevated); border:none; 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; }
2 unmodified lines
.section-head{display:flex; align-items:baseline; justify-content:space-between; margin-bottom:6px;} .section-head h2{margin:0; font-size:20px;} .shelf-strip{height:6px; border-radius:4px; margin:6px 0 18px; background: linear-gradient(90deg, var(--accent) 0%, var(--accent-soft) 100%); opacity:.8;} .muted-line{color:var(--muted); font-size:13px; margin:0 0 16px;} .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{6 unmodified lines .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;}
9 unmodified lines color:var(--text); font-size:13px; cursor:pointer; font-family:inherit; } .chip.active{background:var(--accent); color:var(--bg-elevated); border-color:var(--accent);} .add-cat-row{display:flex; gap:8px; margin-bottom:20px;} .add-cat-row input{flex:1; padding:8px 12px; border-radius:20px; border:1px dashed var(--border); background:var(--bg-elevated); color:var(--text); font-family:inherit; font-size:13px;} .add-cat-row button{border:none; background:var(--accent); color:var(--bg-elevated); border-radius:20px; padding:8px 16px; cursor:pointer; font-size:13px; font-family:inherit;}
/* ---------- Bottom nav ---------- */ .bottom-nav{12 unmodified lines .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; transition:transform .28s ease; 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:var(--accent); color:var(--bg-elevated); display:flex; align-items:center; justify-content:center; font-weight:700; font-size:18px;} .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;}9 unmodified lines /* ---------- Modal ---------- */ .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);} .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;}39 unmodified lines
::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 SCREEN --> <!-- LOGIN / SIGNUP SCREEN --> <div id="loginScreen"> <div class="login-card"> <div class="login-emblem">📖</div> <h1 class="display" data-t="appName">مكتبة الوَرّاق</h1> <p class="sub" data-t="loginSubtitle">مكتبتك العربية للقراءة والاكتشاف</p> <button class="btn primary" onclick="loginAs('google')"> <span>G</span><span data-t="continueGoogle">المتابعة عبر Google</span> </button> <button class="btn" onclick="loginAs('apple')"> <span></span><span data-t="continueApple">المتابعة عبر Apple</span> </button> <button class="btn" onclick="loginAs('email')"> <span>✉️</span><span data-t="continueEmail">المتابعة بالبريد الإلكتروني</span> </button> <div class="divider-text" data-t="or">أو</div> <button class="guest-link" onclick="loginAs('guest')" data-t="continueGuest">المتابعة كضيف</button> <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>
2 unmodified lines <header class="topbar"> <div class="brand"> <div class="brand-mark">📚</div> <div class="brand-name display" data-t="appName">مكتبة الوَرّاق</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)">13 unmodified lines <h2 class="display" data-t="homeTitle">اختيارات لك اليوم</h2> <button class="shuffle-btn" onclick="shuffleHome()" data-t="shuffleBtn">🔀 تبديل</button> </div> <div class="shelf-strip"></div> <p class="muted-line" data-t="homeSub">كتب مختارة عشوائيًا من رفوف المكتبة في كل مرة تفتح فيها الصفحة</p> <div class="ribbon thin"></div> <p class="muted-line" data-t="homeSub">كتب مختارة من رفوف المكتبة في كل مرة تفتح فيها الصفحة</p> <div class="grid" id="homeGrid"></div> </section>
2 unmodified lines <div class="section-head"> <h2 class="display" data-t="searchTitle">البحث في المكتبة</h2> </div> <div class="shelf-strip"></div> <div class="search-box"> <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">التصنيفات</p> <p class="muted-line" data-t="categoriesLabel" style="margin-top:0;">التصنيفات</p> <div class="chips" id="categoryChips"></div> <div class="add-cat-row"> <input type="text" id="newCategoryInput" data-t-ph="addCategoryPlaceholder" placeholder="أضف تصنيفًا جديدًا..."> <button onclick="addCategory()" data-t="addCategoryBtn">إضافة</button> </div> <div class="grid" id="searchGrid"></div> </section> </main>26 unmodified lines
<div class="drawer-section"> <h4 data-t="settingsLabel">الإعدادات</h4> <p class="muted-line" style="margin-bottom:8px;" data-t="langLabel">اللغة</p> <button class="btn" onclick="toggleLang()"><span data-t="switchLangBtn">التبديل إلى English</span></button> </div>
42 unmodified lines</div>
<script>/* ---------------- Data ---------------- *//* ========================================================================= إعدادات الاتصال بـ Supabase — عدّلي القيمتين التاليتين بعد إنشاء مشروعك ========================================================================= */const SUPABASE_URL = 'YOUR_SUPABASE_PROJECT_URL'; // مثال: https://xxxxx.supabase.coconst SUPABASE_ANON_KEY = 'YOUR_SUPABASE_ANON_KEY'; // من Settings → API → anon public
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:'#C9A227'}, {key:'religion', ar:'دين', en:'Religion', color:'#3A5A54'}, {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 customCategories = []; // {key, ar, en, color}
const BOOKS = [ {id:1, cat:'literature', title:{ar:'الأيام', en:'The Days'}, author:{ar:'طه حسين', en:'Taha Hussein'}, desc:{ar:'سيرة ذاتية مؤثرة تروي مسيرة الكاتب منذ طفولته في الريف المصري حتى تفوقه العلمي رغم فقدانه البصر.', en:'A moving memoir tracing the author\'s journey from a rural Egyptian childhood to academic achievement despite losing his sight.'}}, {id:2, cat:'literature', title:{ar:'البخلاء', en:'The Misers'}, author:{ar:'الجاحظ', en:'Al-Jahiz'}, desc:{ar:'مجموعة حكايات ساخرة تصور نماذج من البخل في المجتمع العباسي بأسلوب أدبي رفيع.', en:'A witty collection of tales satirizing miserliness in Abbasid society.'}}, {id:3, cat:'literature', title:{ar:'كليلة ودمنة', en:'Kalila wa Dimna'}, author:{ar:'ابن المقفع', en:'Ibn al-Muqaffa'}, desc:{ar:'حكايات على ألسنة الحيوانات تحمل حكمًا سياسية وأخلاقية عميقة.', en:'Animal fables carrying deep political and moral wisdom.'}}, {id:4, cat:'literature', title:{ar:'ألف ليلة وليلة', en:'One Thousand and One Nights'}, author:{ar:'مؤلف مجهول', en:'Anonymous'}, desc:{ar:'الأثر السردي الأشهر في التراث العربي، حكايات شهرزاد التي لا تنتهي.', en:'The most famous narrative work in Arabic heritage, Scheherazade\'s endless tales.'}}, {id:5, cat:'literature', title:{ar:'ذاكرة الجسد', en:'Memory in the Flesh'}, author:{ar:'أحلام مستغانمي', en:'Ahlam Mosteghanemi'}, desc:{ar:'رواية تمزج الحب بالتاريخ الجزائري في لغة شعرية آسرة.', en:'A novel blending love and Algerian history in captivating poetic prose.'}}, {id:6, cat:'literature', title:{ar:'ديوان المتنبي', en:'Diwan of Al-Mutanabbi'}, author:{ar:'أبو الطيب المتنبي', en:'Al-Mutanabbi'}, desc:{ar:'ديوان شعري يعد من أعظم ما أنتجه الشعر العربي في الفخر والحكمة.', en:'A poetry collection considered among the greatest in Arabic verse.'}},
{id:7, cat:'religion', title:{ar:'رياض الصالحين', en:'Riyad as-Salihin'}, author:{ar:'الإمام النووي', en:'Imam an-Nawawi'}, desc:{ar:'مجموعة أحاديث نبوية مختارة في الآداب والأخلاق.', en:'A curated collection of prophetic sayings on ethics and conduct.'}}, {id:8, cat:'religion', title:{ar:'إحياء علوم الدين', en:'Revival of the Religious Sciences'}, author:{ar:'أبو حامد الغزالي', en:'Al-Ghazali'}, desc:{ar:'موسوعة فكرية وروحية تتناول العبادات والمعاملات وتزكية النفس.', en:'An intellectual and spiritual encyclopedia on worship and self-purification.'}}, {id:9, cat:'religion', title:{ar:'في ظلال القرآن', en:'In the Shade of the Qur\'an'}, author:{ar:'سيد قطب', en:'Sayyid Qutb'}, desc:{ar:'تفسير أدبي معاصر يربط النص القرآني بالواقع الاجتماعي.', en:'A contemporary literary exegesis connecting the Quranic text with social reality.'}}, {id:10, cat:'religion', title:{ar:'الرسالة', en:'Al-Risala'}, author:{ar:'الإمام الشافعي', en:'Imam ash-Shafi\'i'}, desc:{ar:'أول مصنف منهجي في أصول الفقه الإسلامي.', en:'The first systematic treatise on the principles of Islamic jurisprudence.'}},
{id:11, cat:'history', title:{ar:'مقدمة ابن خلدون', en:'The Muqaddimah'}, author:{ar:'ابن خلدون', en:'Ibn Khaldun'}, desc:{ar:'تأسيس علمي مبكر لعلم الاجتماع من خلال دراسة قيام الدول وسقوطها.', en:'An early scientific foundation for sociology through the study of the rise and fall of states.'}}, {id:12, cat:'history', title:{ar:'تاريخ الطبري', en:'History of al-Tabari'}, author:{ar:'محمد بن جرير الطبري', en:'Al-Tabari'}, desc:{ar:'سجل تاريخي شامل للأمم والملوك منذ الخليقة.', en:'A comprehensive historical record of nations and kings since creation.'}}, {id:13, cat:'history', title:{ar:'مروج الذهب', en:'The Meadows of Gold'}, author:{ar:'المسعودي', en:'Al-Mas\'udi'}, desc:{ar:'موسوعة تاريخية وجغرافية تجمع أخبار الأمم والحضارات.', en:'A historical and geographical encyclopedia gathering accounts of nations and civilizations.'}}, {id:14, cat:'history', title:{ar:'قصة الحضارة', en:'The Story of Civilization'}, author:{ar:'ويل ديورانت', en:'Will Durant'}, desc:{ar:'مسح شامل لتاريخ الحضارات الإنسانية عبر العصور.', en:'A sweeping survey of human civilizations across the ages.'}},
{id:15, cat:'spelling', title:{ar:'قواعد الإملاء العربي', en:'Rules of Arabic Spelling'}, author:{ar:'مجموعة مؤلفين', en:'Various Authors'}, desc:{ar:'دليل ميسّر لقواعد رسم الهمزات والألف اللينة وعلامات الترقيم.', en:'An accessible guide to hamza rules, the soft alif, and punctuation.'}}, {id:16, cat:'spelling', title:{ar:'الإملاء الميسّر', en:'Simplified Spelling'}, author:{ar:'محمد أسعد النادري', en:'Muhammad As\'ad al-Nadiri'}, desc:{ar:'كتاب تعليمي يبسّط قواعد الكتابة الصحيحة للمبتدئين والمتقدمين.', en:'An instructional book simplifying correct writing rules for learners.'}}, {id:17, cat:'spelling', title:{ar:'دليل الكاتب في الإملاء', en:'The Writer\'s Spelling Guide'}, author:{ar:'عبد العليم إبراهيم', en:'Abdulalim Ibrahim'}, desc:{ar:'مرجع عملي لتفادي الأخطاء الإملائية الشائعة في الكتابة العربية.', en:'A practical reference for avoiding common spelling errors in Arabic writing.'}},
{id:18, cat:'morphology', title:{ar:'شذا العرف في فن الصرف', en:'Shatha al-Urf fi Fann al-Sarf'}, author:{ar:'أحمد الحملاوي', en:'Ahmad al-Hamalawi'}, desc:{ar:'مرجع كلاسيكي شامل في علم الصرف وأوزان الأفعال والأسماء.', en:'A classic comprehensive reference on Arabic morphology and word patterns.'}}, {id:19, cat:'morphology', title:{ar:'الممتع في التصريف', en:'Al-Mumti\' fi al-Tasrif'}, author:{ar:'ابن عصفور', en:'Ibn Usfur'}, desc:{ar:'دراسة معمّقة في أوزان الصرف وتحولات الكلمة العربية.', en:'An in-depth study of morphological patterns and word transformations.'}}, {id:20, cat:'morphology', title:{ar:'التطبيق الصرفي', en:'Applied Morphology'}, author:{ar:'عبده الراجحي', en:'Abdo Al-Rajihi'}, desc:{ar:'كتاب تطبيقي يقرّب قواعد الصرف للطلاب عبر أمثلة عملية.', en:'A practical workbook bringing morphology rules closer to students through examples.'}},];
/* ---------------- الكتب — تُجلب حصرًا من قاعدة البيانات، لا يوجد بيانات وهمية ---------------- */let BOOKS = [];
/* ---------------- Translations ---------------- */const I18N = { ar:{ appName:'مكتبة الوَرّاق', loginSubtitle:'مكتبتك العربية للقراءة والاكتشاف', continueGoogle:'المتابعة عبر Google', continueApple:'المتابعة عبر Apple', continueEmail:'المتابعة بالبريد الإلكتروني', or:'أو', continueGuest:'المتابعة كضيف', appName:'مكتبة إمام المتقين', loginSubtitle:'مكتبتك العربية للقراءة والاكتشاف', loginTab:'تسجيل الدخول', signupTab:'حساب جديد', emailLabel:'البريد الإلكتروني', passwordLabel:'كلمة المرور', nameLabel:'الاسم', loginBtn:'تسجيل الدخول', signupBtn:'إنشاء حساب', forgotPassword:'نسيت كلمة المرور؟', continueGoogle:'المتابعة عبر Google', or:'أو', continueGuest:'تصفح كضيف بدون حساب', themePaper:'فاتح', themeSepia:'ورقي', themeNight:'داكن', homeTitle:'اختيارات لك اليوم', shuffleBtn:'🔀 تبديل', homeSub:'كتب مختارة عشوائيًا من رفوف المكتبة في كل مرة تفتح فيها الصفحة', homeTitle:'اختيارات لك اليوم', shuffleBtn:'🔀 تبديل', homeSub:'كتب مختارة من رفوف المكتبة في كل مرة تفتح فيها الصفحة', searchTitle:'البحث في المكتبة', searchPlaceholder:'ابحث عن كتاب أو مؤلف...', categoriesLabel:'التصنيفات', addCategoryPlaceholder:'أضف تصنيفًا جديدًا...', addCategoryBtn:'إضافة', navHome:'الرئيسية', navSearch:'البحث', favoritesTab:'المفضلة', historyTab:'سجل القراءة', settingsLabel:'الإعدادات', langLabel:'اللغة', favoritesTab:'المفضلة', historyTab:'سجل القراءة', settingsLabel:'الإعدادات', switchLangBtn:'التبديل إلى English', logoutBtn:'تسجيل الخروج', by:'تأليف', addFav:'➕ أضف إلى المفضلة', removeFav:'✓ في المفضلة', markRead:'📖 وضع علامة مقروء', markedRead:'✓ تمت قراءته', emptyFav:'لا توجد كتب في المفضلة بعد. أضف كتابًا من المكتبة!', emptyHist:'لم تُسجَّل قراءة أي كتاب بعد.', noResults:'لا توجد نتائج مطابقة', guestName:'ضيف', guestSub:'حساب مؤقت — لن يُحفظ التقدم', googleSub:'مرتبط بحساب Google', noResults:'لا توجد نتائج مطابقة', guestName:'ضيف', guestSub:'وضع الضيف — لن تُحفظ مفضلتك أو سجل قراءتك', readBtn:'📖 قراءة الكتاب', tocLabel:'الفهرس', pagesLabel:'الصفحات', saveBookmarkBtn:'حفظ علامة', goToBookmarkBtn:'الانتقال للعلامة', tocTitle:'فهرس الكتاب', pageWord:'صفحة', jumpPagePrompt:'انتقل إلى صفحة رقم', bookmarkSavedMsg:'تم حفظ العلامة عند هذه الصفحة', bookmarkJumpMsg:'تم الانتقال إلى العلامة المحفوظة', noBookmarkMsg:'لا توجد علامة محفوظة لهذا الكتاب', resumedMsg:'أُكمل القراءة من حيث توقفت', placeholderNote:'(نص تجريبي لأغراض العرض فقط)', placeholderNote:'(سيظهر هنا محتوى الكتاب الفعلي بمجرد إضافته في قاعدة البيانات)', emptyLibrary:'المكتبة فارغة حاليًا', emptyLibraryDesc:'أضيفي كتبًا من لوحة تحكم قاعدة البيانات لتظهر هنا فورًا لجميع المستخدمين.', notConnected:'لم يتم الاتصال بقاعدة البيانات بعد', notConnectedDesc:'أضيفي بيانات Supabase أعلى ملف الكود لتفعيل الحسابات والكتب.', loading:'جارِ التحميل...', errInvalidCreds:'البريد الإلكتروني أو كلمة المرور غير صحيحة', errEmailTaken:'هذا البريد مستخدم بالفعل', errGeneric:'حدث خطأ، حاولي مرة أخرى', errWeakPass:'كلمة المرور يجب أن تكون 6 أحرف على الأقل', checkEmailMsg:'تم إرسال رابط تأكيد إلى بريدك الإلكتروني', resetSentMsg:'تم إرسال رابط استعادة كلمة المرور إلى بريدك', needAccountMsg:'سجّلي دخولك لحفظ المفضلة وسجل القراءة', }, en:{ appName:'Al-Warraq Library', loginSubtitle:'Your Arabic library for reading and discovery', continueGoogle:'Continue with Google', continueApple:'Continue with Apple', continueEmail:'Continue with email', or:'or', continueGuest:'Continue as guest', 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 random selection from the library shelves, refreshed each visit', 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', addCategoryPlaceholder:'Add a new category...', addCategoryBtn:'Add', navHome:'Home', navSearch:'Search', favoritesTab:'Favorites', historyTab:'Reading history', settingsLabel:'Settings', langLabel:'Language', 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:'Temporary account — progress won\'t be saved', googleSub:'Linked to Google account', noResults:'No matching results', guestName:'Guest', guestSub:'Guest mode — favorites and history won\'t be saved', readBtn:'📖 Read book', tocLabel:'Index', pagesLabel:'Pages', saveBookmarkBtn:'Save bookmark', goToBookmarkBtn:'Go to bookmark', tocTitle:'Table of contents', pageWord:'page', jumpPagePrompt:'Jump to page number', bookmarkSavedMsg:'Bookmark saved at this page', bookmarkJumpMsg:'Jumped to your saved bookmark', noBookmarkMsg:'No bookmark saved for this book yet', resumedMsg:'Resumed from where you left off', placeholderNote:'(Placeholder text for demo purposes only)', placeholderNote:'(Full book content will appear here once added to the database)', emptyLibrary:'The library is empty right now', emptyLibraryDesc:'Add books from the database 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', }};
/* ---------------- State ---------------- */let state = { lang:'ar', theme:'paper', loggedIn:false, user:null, lang:'ar', theme:'paper', loggedIn:false, isGuest:false, user:null, favorites:new Set(), history:new Set(), activeTab:'home', drawerTab:'fav', selectedCategory:null, homeShuffled:[], homeShuffled:[], booksLoaded:false, readerBookId:null, currentPage:1, bookmarks:{},};let authMode = 'login';
function allCategories(){ return [...CATEGORIES, ...customCategories]; }function catInfo(key){ return allCategories().find(c=>c.key===key) || {ar:key, en:key, color:'#7B2D26'}; }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; }
/* ---------------- Auth ---------------- */function loginAs(method){ if(method==='guest'){ state.user = {name:t('guestName'), sub:t('guestSub'), initial:'ض'}; } else if(method==='google'){ state.user = {name:'سارة العبدالله', sub:t('googleSub'), initial:'س'}; } else if(method==='apple'){ state.user = {name:'سارة العبدالله', sub:'Apple ID', initial:'س'};/* ---------------- 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 { state.user = {name:'سارة العبدالله', sub:'user@example.com', initial:'س'}; showAuthMsg(t('checkEmailMsg'), 'ok'); } state.loggedIn = true; document.getElementById('loginScreen').hidden = true; document.getElementById('mainApp').hidden = false; shuffleHome(); renderAll(); 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();}function logout(){ state.loggedIn = false; state.user = null;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; loadBooks().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, content: { ar:row.content_ar, en:row.content_en }, totalPages: row.total_pages, })); } state.booksLoaded = true;}
/* ---------------- تحميل مفضلة/سجل/علامات المستخدم من قاعدة البيانات ---------------- */async function loadUserData(){ if(!CONFIGURED || !state.user || !state.user.id) return; const uid = state.user.id; const [{ data: favs }, { data: hist }, { data: bms }] = 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), ]); 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; });}
/* ---------------- Theme & Language ---------------- */35 unmodified lines renderHomeGrid();}function renderHomeGrid(){ const grid = document.getElementById('homeGrid'); if(!state.homeShuffled.length){ grid.innerHTML = emptyStateHtml(); return; } document.getElementById('homeGrid').innerHTML = state.homeShuffled.map(bookCardHtml).join(''); 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 = allCategories().map(c=>{ 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('');5 unmodified lines renderCategoryChips(); renderSearch();}function addCategory(){ const input = document.getElementById('newCategoryInput'); const name = input.value.trim(); if(!name) return; const key = 'custom-' + Date.now(); const palette = ['#5B7B45','#4C6B8A','#8C5A2B','#6B4C6B','#3A5A54']; const color = palette[customCategories.length % palette.length]; customCategories.push({key, ar:name, en:name, color}); input.value=''; renderCategoryChips();}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); (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>`;}2 unmodified linesfunction bookCardHtml(b){ const info = catInfo(b.cat); const isFav = state.favorites.has(b.id); return `<div class="book-card" style="--cat-color:${info.color}" onclick="openBookModal(${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>1 unmodified line </div>`;}function openBookModal(id){ const b = BOOKS.find(x=>x.id===id); const b = BOOKS.find(x=>String(x.id)===String(id)); if(!b) return; const info = catInfo(b.cat); const isFav = state.favorites.has(id); const isRead = state.history.has(id); const isFav = state.favorites.has(b.id); const isRead = state.history.has(b.id); document.getElementById('bookModal').innerHTML = ` <button class="modal-close" onclick="closeModal()">✕</button> <div class="modal-cover" style="background:${info.color}">📕</div> <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> <p class="modal-desc">${b.desc[state.lang]||''}</p> <div class="modal-actions"> <button class="btn primary" onclick="openReader(${id})">${t('readBtn')}</button> <button class="btn ${isFav?'primary':''}" onclick="toggleFav(${id})">${isFav?t('removeFav'):t('addFav')}</button> <button class="btn ${isRead?'primary':''}" onclick="toggleRead(${id})">${isRead?t('markedRead'):t('markRead')}</button> <button class="btn primary" onclick="openReader('${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>`; document.getElementById('modalOverlay').hidden = false;}function closeModal(){ document.getElementById('modalOverlay').hidden = true; }function closeModalOnOverlay(e){ if(e.target.id==='modalOverlay') closeModal(); }function toggleFav(id){ state.favorites.has(id) ? state.favorites.delete(id) : state.favorites.add(id);
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 }); }}function toggleRead(id){ state.history.has(id) ? state.history.delete(id) : state.history.add(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); } 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 }); }}
/* ---------------- Reader (table of contents, pages, bookmarks) ---------------- *//* ---------------- Reader (فهرس، صفحات، علامات) ---------------- */const tocCache = {};function generateToc(book){ if(tocCache[book.id]) return tocCache[book.id]; const totalPages = 60 + ((book.id * 37) % 140); // deterministic per-book page count const totalPages = book.totalPages || 60; const chapterCount = 5; const chapters = []; for(let i=0;i<chapterCount;i++){18 unmodified lines closeToc();}function renderReader(){ const book = BOOKS.find(b=>b.id===state.readerBookId); const book = BOOKS.find(b=>String(b.id)===String(state.readerBookId)); if(!book) return; const {totalPages, chapters} = generateToc(book); if(state.currentPage > totalPages) state.currentPage = totalPages;3 unmodified lines document.getElementById('readerBookTitle').textContent = book.title[state.lang]; document.getElementById('readerChapter').textContent = currentChapter[state.lang]; document.getElementById('readerPageNum').textContent = `${state.currentPage} / ${totalPages}`; const realContent = book.content && book.content[state.lang]; document.getElementById('readerPageContent').innerHTML = ` <div class="rp-chapter">${currentChapter[state.lang]}</div> <p class="rp-text">${book.desc[state.lang]} ${book.desc[state.lang]}</p> <p class="rp-text" style="color:var(--muted); font-size:12.5px;">${t('placeholderNote')}</p>`; <p class="rp-text">${realContent || (book.desc[state.lang]||'')}</p> ${realContent ? '' : `<p class="rp-text" style="color:var(--muted); font-size:12.5px;">${t('placeholderNote')}</p>`}`; if(state.currentPage === totalPages && !state.history.has(book.id)){ state.history.add(book.id); renderDrawerList(); toggleRead(book.id); } if(!document.getElementById('tocOverlay').hidden) renderToc();}4 unmodified linesfunction closeToc(){ document.getElementById('tocOverlay').hidden = true; }function closeTocOnOverlay(e){ if(e.target.id==='tocOverlay') closeToc(); }function renderToc(){ const book = BOOKS.find(b=>b.id===state.readerBookId); const book = BOOKS.find(b=>String(b.id)===String(state.readerBookId)); if(!book) return; const {chapters} = generateToc(book); document.getElementById('tocList').innerHTML = chapters.map(c=>3 unmodified lines ).join('');}function jumpToPagePrompt(){ const book = BOOKS.find(b=>b.id===state.readerBookId); const book = BOOKS.find(b=>String(b.id)===String(state.readerBookId)); const {totalPages} = generateToc(book); const val = prompt(`${t('jumpPagePrompt')} (1-${totalPages})`, state.currentPage); if(val===null) return; const n = parseInt(val,10); if(!isNaN(n)) goToPage(n);}function saveBookmark(){async function saveBookmark(){ state.bookmarks[state.readerBookId] = state.currentPage; showToast(t('bookmarkSavedMsg')); if(state.isGuest || !CONFIGURED || !state.user) return; await supabaseClient.from('bookmarks').upsert({ user_id: state.user.id, book_id: state.readerBookId, page: state.currentPage }, { onConflict:'user_id,book_id' });}function goToBookmark(){ const p = state.bookmarks[state.readerBookId];36 unmodified lines return; } container.innerHTML = ids.map(id=>{ const b = BOOKS.find(x=>x.id===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('');}index.html+407-159