const {useEffect,useMemo,useRef,useState}=React;
const API='/api';
const BUILD=window.BRONZE_BUILD||{version:'dev',buildId:'local',publishedAt:new Date().toISOString(),environment:'Production',database:'bronze-academy-db'};
const buildDate=()=>new Date(BUILD.publishedAt).toLocaleString('en-GB',{dateStyle:'medium',timeStyle:'short'});
const PATHS=[
 {value:'bronze_basics',label:'أساسيات Bronze',icon:'📘'},
 {value:'shopify_pos',label:'نظام Shopify POS',icon:'🛍️'},
 {value:'lenses',label:'العدسات',icon:'👁️'},
 {value:'perfumes',label:'العطور',icon:'✨'},
 {value:'makeup',label:'المكياج',icon:'💄'},
 {value:'skincare',label:'العناية بالبشرة',icon:'🧴'},
 {value:'inventory_warehouse',label:'المخزون والمخزن',icon:'📦'},
 {value:'orders_delivery',label:'الطلبات والتوصيل',icon:'🚚'},
 {value:'daily_scenarios',label:'ماذا أفعل إذا...؟',icon:'🚨'},
 {value:'sales_staff_training',label:'Sales Staff Training + Performance',icon:'🎓'}
];
const AUDIENCES=[['all','الكل'],['sales','المبيعات'],['warehouse_office','المخزن / المكتب'],['management','الإدارة']];
const TYPES=[['reading','📖 قراءة'],['video','🎥 فيديو'],['quiz','📝 اختبار'],['practical','🎯 عملي'],['sop','🚨 إجراء تشغيلي']];
const pathInfo=v=>PATHS.find(x=>x.value===v)||PATHS[0];
const fmtDate=v=>v?new Date(v).toLocaleDateString('en-GB'):'—';
const cacheKey=id=>`bronze_dashboard_${id}`;
function readCache(id){try{return JSON.parse(localStorage.getItem(cacheKey(id))||'null')}catch{return null}}
function writeCache(id,data){try{localStorage.setItem(cacheKey(id),JSON.stringify({...data,_cachedAt:Date.now()}))}catch{}}

function Login({onLogin}){const cached=(()=>{try{return JSON.parse(localStorage.getItem('bronze_employees')||'[]')}catch{return[]}})();const [employees,setEmployees]=useState(cached),[employeeId,setEmployeeId]=useState(String(cached?.[0]?.id||'')),[pin,setPin]=useState(''),[error,setError]=useState(''),[loggingIn,setLoggingIn]=useState(false);useEffect(()=>{fetch(API+'/employees',{cache:'no-store'}).then(r=>r.json()).then(d=>{const list=d.employees||[];setEmployees(list);localStorage.setItem('bronze_employees',JSON.stringify(list));setEmployeeId(v=>v||String(list?.[0]?.id||''))}).catch(()=>{if(!cached.length)setError('تعذر تحميل الموظفات.')})},[]);async function submit(e){e.preventDefault();if(loggingIn)return;setError('');setLoggingIn(true);try{const r=await fetch(API+'/login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({employeeId:Number(employeeId),pin})});const d=await r.json();if(!r.ok){setError(d.error||'رمز الدخول غير صحيح.');return}localStorage.setItem('bronze_session',JSON.stringify(d.employee));onLogin(d.employee)}catch{setError('تعذر الاتصال. حاولي مرة أخرى.')}finally{setLoggingIn(false)}}return <main className="login-shell"><section className="brand"><div className="logo">B</div><h1>Bronze Academy</h1><p>نتعلم. نتطور. ننجح.</p></section><form className="card" onSubmit={submit}><label>الحساب</label><select value={employeeId} onChange={e=>setEmployeeId(e.target.value)} disabled={loggingIn}>{employees.map(x=><option key={x.id} value={x.id}>{x.name} — {x.role_ar}</option>)}</select><label>رمز الدخول</label><input inputMode="numeric" value={pin} onChange={e=>setPin(e.target.value.replace(/\D/g,''))} placeholder="أدخلي رمز الدخول" disabled={loggingIn}/>{error&&<div className="error">{error}</div>}<button disabled={loggingIn||!employeeId||!pin}>{loggingIn?'جارٍ الدخول…':'دخول'}</button></form><small>Bronze Academy <bdi>{BUILD.version}</bdi><br/><span>Build <bdi>{BUILD.buildId}</bdi> · {buildDate()}</span></small></main>}

function Lesson({employee,lesson,onDone,onComplete,preview=false}){
 const slides=lesson.slides?.length?lesson.slides:[{title:lesson.title_ar,body:''}];
 const [i,setI]=useState(0),[finishing,setFinishing]=useState(false);
 const touch=React.useRef({x:0,y:0});
 const s=slides[i]||{};
 const next=()=>setI(v=>Math.min(slides.length-1,v+1));
 const prev=()=>setI(v=>Math.max(0,v-1));
 async function complete(){if(preview||finishing)return;setFinishing(true);try{await fetch(API+'/progress',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({employeeId:employee.id,lessonId:lesson.id,completed:true})});onComplete?.()}finally{setFinishing(false)}}
 function tap(e){if(e.target.closest('a,button'))return;const r=e.currentTarget.getBoundingClientRect();const x=e.clientX-r.left;if(x<r.width*.42)next();else if(x>r.width*.58)prev()}
 function touchStart(e){const t=e.touches[0];touch.current={x:t.clientX,y:t.clientY}}
 function touchEnd(e){const t=e.changedTouches[0];const dx=t.clientX-touch.current.x,dy=t.clientY-touch.current.y;if(Math.abs(dx)>55&&Math.abs(dx)>Math.abs(dy)){dx<0?next():prev()}}
 return <main className="story-shell" dir="rtl" onClick={tap} onTouchStart={touchStart} onTouchEnd={touchEnd}>{preview&&<div className="preview-banner"><strong>👁️ معاينة فقط</strong><span>هذه التغييرات لم تُحفظ أو تُنشر بعد</span></div>}
  <div className="story-progress">{slides.map((_,n)=><i key={n} className={n<=i?'active':''}/>)}</div>
  <header className="story-head"><button className="story-close" onClick={onDone}>×</button><div><strong>{lesson.title_ar}</strong><small>البطاقة {i+1} من {slides.length}</small></div></header>
  <section className="story-slide">
   {s.image&&<img className="story-image" src={s.image} alt=""/>}
   {s.video&&<a className="story-video" href={s.video} target="_blank" rel="noreferrer">▶ فتح الفيديو</a>}
   {(s.title||s.body)&&<div className="story-copy"><div className="lesson-badges"><span>آخر تحديث حقيقي: {fmtDate(lesson.content_updated_at||lesson.updated_at)}</span></div>{s.title&&<h2>{s.title}</h2>}{s.body&&<p>{s.body}</p>}</div>}
  </section>
  <div className="tap-hint"><span>اضغطي يسار الشاشة للتالي</span><span>اضغطي يمين الشاشة للسابق</span></div>
  {!preview&&i===slides.length-1&&<button className="story-complete" onClick={complete} disabled={finishing}>{finishing?'جارٍ الحفظ…':'✓ إكمال الدرس'}</button>}
 </main>
}
function Dashboard({employee,onLogout}){
 const initialCache=readCache(employee.id);
 const [data,setData]=useState(initialCache),[refreshing,setRefreshing]=useState(!initialCache),[open,setOpen]=useState(null),[viewPath,setViewPath]=useState(null),[q,setQ]=useState('');
 async function load({silent=false}={}){if(!silent&&!data)setRefreshing(true);try{const r=await fetch(`${API}/dashboard?employeeId=${employee.id}`,{cache:'no-store'});if(!r.ok)throw new Error('dashboard');const fresh=await r.json();setData(fresh);writeCache(employee.id,fresh)}catch(e){if(!data)console.error(e)}finally{setRefreshing(false)}}
 useEffect(()=>{load({silent:Boolean(initialCache)})},[employee.id]);
 if(open)return <Lesson employee={employee} lesson={open} onDone={()=>setOpen(null)} onComplete={()=>{setOpen(null);load({silent:true})}}/>;
 const lessons=data?.lessons||[];
 const searchResults=q?lessons.filter(l=>`${l.title_ar} ${l.slides?.map(s=>`${s.title||''} ${s.body||''}`).join(' ')}`.toLowerCase().includes(q.toLowerCase())):[];
 const next=lessons.find(x=>!x.completed);
 if(viewPath){const p=pathInfo(viewPath),items=lessons.filter(l=>l.path===viewPath);return <main className="app-shell path-page" dir="rtl"><header className="path-page-head"><button className="back-btn" onClick={()=>setViewPath(null)}>← المسارات</button><div><span className="path-icon">{p.icon}</span><h1>{p.label}</h1><p>{items.length} درس منشور</p></div></header><div className="lesson-list">{items.length?items.map((l,n)=><button className="lesson-row" key={l.id} onClick={()=>setOpen(l)}><div className="lesson-number">{n+1}</div><div className="lesson-text"><strong><bdi>{l.title_ar}</bdi></strong><span>{l.duration_minutes} دقيقة · تحديث {fmtDate(l.content_updated_at)}</span></div><div className={l.completed?'done':'start'}>{l.completed?'✓':'ابدئي'}</div></button>):<div className="empty-state">لا توجد دروس منشورة في هذا المسار حتى الآن.</div>}</div></main>}
 return <main className="app-shell" dir="rtl">
   <header className="hero"><div><div className="eyebrow">أهلًا بكِ</div><h1>{employee.name}</h1><p>{employee.branch_ar}</p></div><button className="ghost" onClick={onLogout}>خروج</button></header>
   <section className="progress-card"><div><span>تقدمك</span><strong>{data?.completionPercent||0}%</strong>{refreshing&&<small className="sync-note">جارٍ التحديث…</small>}</div><div className="bar"><i style={{width:`${data?.completionPercent||0}%`}}/></div></section>
   {next&&<section className="continue-card"><div><small>أكملي من حيث توقفتِ</small><strong>{next.title_ar}</strong></div><button onClick={()=>setOpen(next)}>متابعة</button></section>}
   <input className="search" value={q} onChange={e=>setQ(e.target.value)} placeholder="ابحثي عن درس أو إجراء..."/>
   {q?<section className="selected-path"><h2>نتائج البحث</h2><div className="lesson-list">{searchResults.map(l=><button className="lesson-row" key={l.id} onClick={()=>setOpen(l)}><div className="lesson-icon">{pathInfo(l.path).icon}</div><div className="lesson-text"><strong>{l.title_ar}</strong><span>{pathInfo(l.path).label}</span></div><div className="start">افتحي</div></button>)}</div></section>:<section className="paths-section"><h2>المسارات الرئيسية</h2><div className="path-grid">{PATHS.map(p=>{const n=lessons.filter(l=>l.path===p.value).length;return <button key={p.value} className="path-card" onClick={()=>setViewPath(p.value)}><span className="path-icon">{p.icon}</span><strong><bdi>{p.label}</bdi></strong><small>{data?n+' درس':'…'}</small><em>اضغطي لفتح الدروس</em></button>})}</div></section>}
 </main>
}
function AdminLogin({onLogin}){const [pin,setPin]=useState(''),[error,setError]=useState('');async function submit(e){e.preventDefault();const r=await fetch(API+'/admin/login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({pin})});const d=await r.json();if(!r.ok)return setError(d.error||'رمز الإدارة غير صحيح.');localStorage.setItem('bronze_admin_session',JSON.stringify(d.admin));onLogin(d.admin)}return <main className="login-shell"><section className="brand"><div className="logo">B</div><h1>Bronze Academy</h1><p>لوحة الإدارة</p></section><form className="card" onSubmit={submit}><label>رمز الإدارة</label><input inputMode="numeric" value={pin} onChange={e=>setPin(e.target.value.replace(/\D/g,''))}/>{error&&<div className="error">{error}</div>}<button>دخول الإدارة</button></form></main>}

function AdminPanel({onLogout}){
 const [tab,setTab]=useState('lessons'),[lessons,setLessons]=useState([]),[employees,setEmployees]=useState([]),[editing,setEditing]=useState(null),[message,setMessage]=useState(''),[saving,setSaving]=useState(false),[slides,setSlides]=useState([{title:'',body:'',image:'',video:''}]),[filterPath,setFilterPath]=useState('all'),[filterStatus,setFilterStatus]=useState('all'),[sort,setSort]=useState('newest'),[previewLesson,setPreviewLesson]=useState(null); const formRef=useRef(null);
 async function load(){const [lr,er]=await Promise.all([fetch(API+'/admin/lessons'),fetch(API+'/admin/employees')]);const [ld,ed]=await Promise.all([lr.json(),er.json()]);setLessons(ld.lessons||[]);setEmployees(ed.employees||[])}useEffect(()=>{load()},[]);
 function reset(){setEditing(null);setSlides([{title:'',body:'',image:'',video:''}])}
 function edit(l){setEditing(l);setSlides(l.slides?.length?l.slides:[{title:'',body:'',image:'',video:''}]);scrollTo({top:0,behavior:'smooth'})}
 function updateSlide(i,k,v){setSlides(s=>s.map((x,n)=>n===i?{...x,[k]:v}:x))}
 function openPreview(){const form=formRef.current;if(!form)return;const f=new FormData(form);const title=String(f.get('title_ar')||'').trim();if(!title){setMessage('اكتبي اسم الدرس أولًا حتى تظهر المعاينة.');return}setMessage('');setPreviewLesson({id:editing?.id||'preview',title_ar:title,duration_minutes:Number(f.get('duration_minutes')||2),path:f.get('path')||'bronze_basics',audience:f.get('audience')||'all',type:editing?.type||'reading',status:f.get('status')||'draft',slides,content_updated_at:editing?.content_updated_at||new Date().toISOString()})}
 async function saveLesson(e){e.preventDefault();setSaving(true);const f=new FormData(e.currentTarget);const payload={id:editing?.id,title_ar:f.get('title_ar'),duration_minutes:Number(f.get('duration_minutes')||2),path:f.get('path'),audience:f.get('audience'),type:editing?.type||'reading',status:f.get('status'),slides};const r=await fetch(API+'/admin/lessons',{method:editing?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();setSaving(false);if(!r.ok)return setMessage(d.error||'تعذر الحفظ');setMessage(d.contentChanged?'تم تحديث محتوى الدرس وتاريخ التحديث بنجاح ✅':editing?'تم حفظ التغيير دون تغيير تاريخ المحتوى ✅':'تمت إضافة الدرس كمسودة ✅');reset();await load()}
 async function removeLesson(id){if(!confirm('حذف الدرس؟'))return;await fetch(`${API}/admin/lessons?id=${id}`,{method:'DELETE'});await load()}
 async function saveEmployee(e){e.preventDefault();setSaving(true);const f=new FormData(e.currentTarget);const r=await fetch(API+'/admin/employees',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:f.get('name'),role_ar:f.get('role_ar'),branch_ar:f.get('branch_ar'),pin:f.get('pin'),active:true})});setSaving(false);if(r.ok){e.currentTarget.reset();setMessage('تمت إضافة الموظفة بنجاح ✅');await load()}}
 if(previewLesson)return <Lesson employee={null} lesson={previewLesson} preview onDone={()=>setPreviewLesson(null)}/>;
 const visible=lessons.filter(l=>(filterPath==='all'||l.path===filterPath)&&(filterStatus==='all'||l.status===filterStatus)).sort((a,b)=>{const av=new Date(a.content_updated_at||0),bv=new Date(b.content_updated_at||0);return sort==='oldest'?av-bv:bv-av});
 return <main className="admin-shell"><header className="admin-head"><div><small>لوحة الإدارة</small><h1>Bronze Academy</h1></div><button className="ghost" onClick={onLogout}>خروج</button></header><nav className="admin-tabs"><button className={tab==='lessons'?'active':''} onClick={()=>setTab('lessons')}>الدروس</button><button className={tab==='paths'?'active':''} onClick={()=>setTab('paths')}>المسارات</button><button className={tab==='employees'?'active':''} onClick={()=>setTab('employees')}>الموظفات</button><button className={tab==='system'?'active':''} onClick={()=>setTab('system')}>معلومات النظام</button></nav>{message&&<div className="save-message success-msg">{message}</div>}
 {tab==='paths'&&<section><h2>المسارات الحالية</h2><div className="path-grid">{PATHS.map(p=><div className="path-card static" key={p.value}><span className="path-icon">{p.icon}</span><strong>{p.label}</strong><small>{lessons.filter(l=>l.path===p.value).length} درس</small></div>)}</div></section>}
 {tab==='lessons'&&<section className="admin-grid"><form ref={formRef} className="card admin-form" onSubmit={saveLesson} key={editing?.id||'new'}><h2>{editing?'تعديل الدرس':'إضافة درس جديد'}</h2><p className="form-note">الدروس الجديدة تُحفظ كمسودة افتراضيًا، ثم تنشرينها عندما تصبح جاهزة.</p><label>اسم الدرس</label><input name="title_ar" defaultValue={editing?.title_ar||''} required/><label>المسار</label><select name="path" defaultValue={editing?.path||'bronze_basics'}>{PATHS.map(p=><option key={p.value} value={p.value}>{p.label}</option>)}</select><label>الحالة</label><select name="status" defaultValue={editing?.status||'draft'}><option value="draft">🟡 مسودة</option><option value="published">🟢 منشور</option><option value="hidden">🔒 مخفي</option></select><label>موجّه إلى</label><select name="audience" defaultValue={editing?.audience||'all'}>{AUDIENCES.map(x=><option key={x[0]} value={x[0]}>{x[1]}</option>)}</select><label>المدة بالدقائق</label><input name="duration_minutes" type="number" min="1" defaultValue={editing?.duration_minutes||2}/>{editing&&<div className="date-audit"><div><small>آخر تعديل حقيقي للمحتوى</small><strong>{fmtDate(editing.content_updated_at)}</strong></div><div><small>آخر نشر</small><strong>{editing.published_at?fmtDate(editing.published_at):'لم يُنشر بعد'}</strong></div></div>}{slides.map((s,i)=><section className="slide-editor" key={i}><div className="slide-editor-head"><h3>البطاقة {i+1}</h3>{slides.length>1&&<button type="button" className="remove-slide" onClick={()=>setSlides(v=>v.filter((_,n)=>n!==i))}>حذف</button>}</div><label>العنوان</label><input value={s.title||''} onChange={e=>updateSlide(i,'title',e.target.value)}/><label>المحتوى</label><textarea value={s.body||''} onChange={e=>updateSlide(i,'body',e.target.value)}/><div className="media-block"><div className="media-head"><strong>صورة البطاقة</strong>{s.image&&<button type="button" className="text-danger" onClick={()=>updateSlide(i,'image','')}>حذف الصورة</button>}</div>{s.image?<div className="media-preview image-preview"><img src={s.image} alt="معاينة صورة البطاقة"/><a href={s.image} target="_blank" rel="noreferrer">فتح بالحجم الكامل</a></div>:<div className="media-empty">لا توجد صورة حاليًا</div>}<label className="upload-btn">{s.image?'تغيير الصورة':'اختيار صورة'}<input type="file" accept="image/*" onChange={e=>{const f=e.target.files?.[0];if(!f)return;if(f.size>8*1024*1024){alert('حجم الصورة يجب ألا يتجاوز 8 MB');e.target.value='';return}const r=new FileReader();r.onload=()=>updateSlide(i,'image',String(r.result||''));r.readAsDataURL(f)}}/></label><details className="advanced-media"><summary>رابط صورة متقدم</summary><input dir="ltr" value={s.image?.startsWith('data:')?'':(s.image||'')} placeholder="https://... أو assets/image.png" onChange={e=>updateSlide(i,'image',e.target.value)}/></details></div><div className="media-block"><div className="media-head"><strong>فيديو البطاقة</strong>{s.video&&<button type="button" className="text-danger" onClick={()=>updateSlide(i,'video','')}>حذف الفيديو</button>}</div>{s.video?<div className="media-preview video-preview"><video src={s.video} controls playsInline preload="metadata"/><a href={s.video} target="_blank" rel="noreferrer">فتح الفيديو</a></div>:<div className="media-empty">لا يوجد فيديو حاليًا</div>}<label className="upload-btn">{s.video?'تغيير الفيديو':'اختيار فيديو'}<input type="file" accept="video/*" onChange={e=>{const f=e.target.files?.[0];if(!f)return;if(f.size>25*1024*1024){alert('حجم الفيديو يجب ألا يتجاوز 25 MB. للفيديوهات الأكبر استخدمي رابطًا.');e.target.value='';return}const r=new FileReader();r.onload=()=>updateSlide(i,'video',String(r.result||''));r.readAsDataURL(f)}}/></label><details className="advanced-media"><summary>رابط فيديو متقدم</summary><input dir="ltr" value={s.video?.startsWith('data:')?'':(s.video||'')} placeholder="https://..." onChange={e=>updateSlide(i,'video',e.target.value)}/></details></div><div className="card-live-preview"><small>معاينة البطاقة كما ستظهر للموظفة</small>{s.image&&<img src={s.image} alt=""/>}{s.video&&<video src={s.video} controls playsInline preload="metadata"/>}<h4>{s.title||'عنوان البطاقة'}</h4><p>{s.body||'سيظهر محتوى البطاقة هنا.'}</p></div></section>)}<button type="button" className="secondary" onClick={()=>setSlides(v=>[...v,{title:'',body:'',image:'',video:''}])}>+ إضافة بطاقة</button><button type="button" className="preview-action" onClick={openPreview}>👁️ معاينة الدرس قبل الحفظ</button><button disabled={saving}>{saving?'جارٍ الحفظ…':editing?'حفظ التعديل':'إضافة كمسودة'}</button>{editing&&<button type="button" className="secondary" onClick={reset}>إلغاء</button>}</form><div><div className="list-head admin-filter-head"><h2>الدروس</h2><select value={filterPath} onChange={e=>setFilterPath(e.target.value)}><option value="all">كل المسارات</option>{PATHS.map(p=><option key={p.value} value={p.value}>{p.label}</option>)}</select><select value={filterStatus} onChange={e=>setFilterStatus(e.target.value)}><option value="all">كل الحالات</option><option value="draft">المسودات</option><option value="published">المنشورة</option><option value="hidden">المخفية</option></select><select value={sort} onChange={e=>setSort(e.target.value)}><option value="newest">الأحدث تعديلًا</option><option value="oldest">الأقدم تعديلًا</option></select></div>{visible.map(l=><div className="admin-row" key={l.id}><div><strong>{l.title_ar}</strong><span>{pathInfo(l.path).label} · {l.status==='published'?'منشور':l.status==='draft'?'مسودة':'مخفي'}</span><small className="audit-line">تحديث المحتوى: {fmtDate(l.content_updated_at)} · آخر نشر: {l.published_at?fmtDate(l.published_at):'لم يُنشر'}</small></div><div className="admin-actions"><button className="small-btn preview-small" onClick={()=>setPreviewLesson(l)}>معاينة</button><button className="small-btn" onClick={()=>edit(l)}>تعديل</button><button className="small-btn danger" onClick={()=>removeLesson(l.id)}>حذف</button></div></div>)}</div></section>}
 {tab==='employees'&&<section className="admin-grid"><form className="card admin-form" onSubmit={saveEmployee}><h2>إضافة موظفة</h2><label>الاسم</label><input name="name" required/><label>الوظيفة</label><input name="role_ar" defaultValue="موظفة مبيعات" required/><label>الفرع</label><input name="branch_ar" defaultValue="بوشر" required/><label>PIN</label><input name="pin" inputMode="numeric" required/><button disabled={saving}>{saving?'جارٍ الحفظ…':'إضافة الموظفة'}</button></form><div><h2>الموظفات</h2>{employees.map(e=><div className="admin-row" key={e.id}><div><strong>{e.name}</strong><span>{e.role_ar} · {e.branch_ar}</span></div></div>)}</div></section>}
 {tab==='system'&&<section className="card system-card"><h2>معلومات النظام</h2><dl className="system-info"><div><dt>Version</dt><dd><bdi>{BUILD.version}</bdi></dd></div><div><dt>Build ID</dt><dd><bdi>{BUILD.buildId}</bdi></dd></div><div><dt>Published</dt><dd><bdi>{buildDate()}</bdi></dd></div><div><dt>Environment</dt><dd><bdi>{BUILD.environment}</bdi></dd></div><div><dt>Database</dt><dd><bdi>{BUILD.database}</bdi></dd></div></dl></section>}</main>
}
function App(){const [mode,setMode]=useState(()=>location.hash==='#admin'?'admin':'employee'),[employee,setEmployee]=useState(()=>{try{return JSON.parse(localStorage.getItem('bronze_session'))}catch{return null}}),[admin,setAdmin]=useState(()=>{try{return JSON.parse(localStorage.getItem('bronze_admin_session'))}catch{return null}});useEffect(()=>{const h=()=>setMode(location.hash==='#admin'?'admin':'employee');addEventListener('hashchange',h);return()=>removeEventListener('hashchange',h)},[]);if(mode==='admin'){if(!admin)return <AdminLogin onLogin={setAdmin}/>;return <AdminPanel onLogout={()=>{localStorage.removeItem('bronze_admin_session');setAdmin(null)}}/>}if(!employee)return <><Login onLogin={setEmployee}/><button className="admin-entry" onClick={()=>location.hash='admin'}>الإدارة</button></>;return <Dashboard employee={employee} onLogout={()=>{localStorage.removeItem('bronze_session');setEmployee(null)}}/>}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
