// ==========================================
// DXA Admin · Page components
// ==========================================

// ---------- DASHBOARD ----------
const DashboardPage = ({ content, submissions, log, onNav }) => {
  const newCount = submissions.filter(s => s.status==='new').length;
  const pubInfo = PUB_STATUS[content.publishStatus];
  return (
    <div>
      <div className="page-head">
        <h2>نظرة عامة</h2>
        <p>ملخّص حالة الموقع وأحدث النشاطات.</p>
      </div>

      <div className="kpi-grid">
        <div className="kpi">
          <div className="kpi-icon">{I.eye}</div>
          <div className="kpi-label">الزيارات · 30 يوم</div>
          <div className="kpi-val">12,438</div>
          <div className="kpi-trend up">↑ 18% عن الشهر السابق</div>
        </div>
        <div className="kpi">
          <div className="kpi-icon">{I.inbox}</div>
          <div className="kpi-label">طلبات جديدة</div>
          <div className="kpi-val">{newCount}</div>
          <div className="kpi-trend up">↑ 2 منذ الأمس</div>
        </div>
        <div className="kpi">
          <div className="kpi-icon">{I.portfolio}</div>
          <div className="kpi-label">عناصر Portfolio</div>
          <div className="kpi-val">{content.portfolio.length}</div>
          <div className="kpi-trend" style={{color:'var(--ink-3)'}}>{content.portfolio.filter(p=>p.featured).length} مميّز</div>
        </div>
        <div className="kpi">
          <div className="kpi-icon">{I.clients}</div>
          <div className="kpi-label">العملاء</div>
          <div className="kpi-val">{content.clients.length}</div>
          <div className="kpi-trend" style={{color:'var(--ink-3)'}}>{content.services.length} خدمات نشطة</div>
        </div>
      </div>

      <div className="dash-grid">
        <div className="card">
          <div className="card-head">
            <div>
              <h3>أحدث طلبات عروض الأسعار</h3>
              <div className="sub">{newCount} طلب جديد بحاجة لمراجعة</div>
            </div>
            <button className="btn btn-ghost" onClick={() => onNav('submissions')}>عرض الكل {I.external}</button>
          </div>
          <table className="tbl">
            <thead><tr><th>الاسم</th><th>الجهة</th><th>الخدمة</th><th>الحالة</th><th></th></tr></thead>
            <tbody>
              {submissions.slice(0,5).map(s => (
                <tr key={s.id}>
                  <td className="name">{s.name}</td>
                  <td>{s.org}</td>
                  <td>{s.service}</td>
                  <td><Pill tone={SUB_STATUS[s.status].tone}>{SUB_STATUS[s.status].label}</Pill></td>
                  <td style={{textAlign:'left'}}>
                    <button className="ibtn">{I.reply}</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card">
          <div className="card-head">
            <h3>حالة الموقع</h3>
          </div>
          <div style={{display:'flex',alignItems:'center',gap:14,marginBottom:18}}>
            <div style={{width:46,height:46,borderRadius:10,background:'var(--green-soft)',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--green)'}}>
              {I.check}
            </div>
            <div>
              <div style={{fontSize:14,fontWeight:600}}>الموقع <Pill tone={pubInfo.tone}>{pubInfo.label}</Pill></div>
              <div style={{fontSize:12,color:'var(--ink-3)',marginTop:3}}>آخر نشر: 09 مايو · 14:30</div>
            </div>
          </div>
          <div style={{display:'flex',flexDirection:'column',gap:8,fontSize:13}}>
            {[
              ['اللغات', 'العربية + الإنجليزية'],
              ['آخر نسخة احتياطية', 'اليوم · 04:00'],
              ['SSL', '✓ مفعّل'],
              ['الأداء', '94 / 100'],
            ].map(([k,v]) => (
              <div key={k} style={{display:'flex',justifyContent:'space-between',padding:'8px 0',borderBottom:'1px dashed var(--line)'}}>
                <span style={{color:'var(--ink-3)'}}>{k}</span>
                <span style={{fontWeight:500}}>{v}</span>
              </div>
            ))}
          </div>

          <div style={{marginTop:20}}>
            <div style={{fontSize:12,color:'var(--ink-2)',fontWeight:600,letterSpacing:'.04em',textTransform:'uppercase',marginBottom:10}}>اختصارات سريعة</div>
            <div style={{display:'flex',flexDirection:'column',gap:6}}>
              <button className="btn btn-soft" style={{justifyContent:'flex-start'}} onClick={()=>onNav('portfolio')}>{I.plus} إضافة عمل للـ Portfolio</button>
              <button className="btn btn-soft" style={{justifyContent:'flex-start'}} onClick={()=>onNav('clients')}>{I.plus} إضافة عميل جديد</button>
              <button className="btn btn-soft" style={{justifyContent:'flex-start'}} onClick={()=>onNav('hero')}>{I.edit} تحرير الـ Hero</button>
            </div>
          </div>
        </div>
      </div>

      <div style={{marginTop:18}}>
        <div className="card">
          <div className="card-head">
            <h3>آخر التعديلات</h3>
            <button className="btn btn-ghost" onClick={()=>onNav('history')}>السجل الكامل {I.external}</button>
          </div>
          <div className="timeline">
            {log.slice(0,5).map(l => (
              <div className="tl-item" key={l.id}>
                <div>{l.what}</div>
                <div className="tl-when">{l.when} · بواسطة {l.who}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- Split editor wrapper ----------
const SplitEditor = ({ title, sub, anchor, children, content }) => {
  const previewRef = useRef(null);
  const [device, setDevice] = useState('desktop');
  useEffect(() => {
    // refresh preview iframe by appending hash on content change
    if (previewRef.current) {
      previewRef.current.src = `home.html#${anchor}`;
    }
  }, [anchor, content]);
  return (
    <div>
      <div className="page-head" style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end'}}>
        <div>
          <h2>{title}</h2>
          <p>{sub}</p>
        </div>
      </div>
      <div className="split">
        <div className="editor-pane">{children}</div>
        <div className="preview-pane">
          <div className="preview-bar">
            <div style={{display:'flex',alignItems:'center',gap:10}}>
              <div className="pdots"><span/><span/><span/></div>
              <div className="purl">home.html#{anchor}</div>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:6}}>
              <span style={{fontSize:11,color:'var(--ink-3)'}}>معاينة مباشرة</span>
              <a href={`home.html#${anchor}`} target="_blank" className="ibtn" title="فتح في تبويب جديد">{I.external}</a>
            </div>
          </div>
          <div className="preview-frame">
            <iframe ref={previewRef} src={`home.html#${anchor}`} title="preview"/>
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- HERO editor ----------
const HeroPage = ({ content, update }) => {
  const h = content.hero;
  const set = (k,v) => update(c => ({ ...c, hero: { ...c.hero, [k]:v } }));
  return (
    <SplitEditor
      title="قسم Hero"
      sub="الواجهة الرئيسية للموقع — العنوان الكبير والوصف والـ CTA."
      anchor="home"
      content={content}
    >
      <div className="card">
        <div className="card-head"><h3>النصوص</h3></div>
        <Bilingual labelAr="نص الـ Eyebrow" labelEn="Eyebrow text" valueAr={h.eyebrowAr} valueEn={h.eyebrowEn} onChangeAr={v=>set('eyebrowAr',v)} onChangeEn={v=>set('eyebrowEn',v)} />
        <Bilingual labelAr="العنوان الرئيسي" labelEn="Main title" valueAr={h.titleAr} valueEn={h.titleEn} onChangeAr={v=>set('titleAr',v)} onChangeEn={v=>set('titleEn',v)} multiline rows={2} />
        <Bilingual labelAr="الكلمة المميّزة (باللون الذهبي)" labelEn="Accent word" valueAr={h.accentWordAr} valueEn={h.accentWordEn} onChangeAr={v=>set('accentWordAr',v)} onChangeEn={v=>set('accentWordEn',v)} />
        <Bilingual labelAr="الوصف" labelEn="Description" valueAr={h.subAr} valueEn={h.subEn} onChangeAr={v=>set('subAr',v)} onChangeEn={v=>set('subEn',v)} multiline rows={3} />
      </div>

      <div className="card">
        <div className="card-head"><h3>أزرار الـ Call to Action</h3></div>
        <Bilingual labelAr="الزر الأساسي" labelEn="Primary button" valueAr={h.primaryCtaAr} valueEn={h.primaryCtaEn} onChangeAr={v=>set('primaryCtaAr',v)} onChangeEn={v=>set('primaryCtaEn',v)} />
        <Bilingual labelAr="الزر الثانوي" labelEn="Secondary button" valueAr={h.secondaryCtaAr} valueEn={h.secondaryCtaEn} onChangeAr={v=>set('secondaryCtaAr',v)} onChangeEn={v=>set('secondaryCtaEn',v)} />
      </div>

      <div className="card">
        <div className="card-head">
          <h3>صورة الـ Hero</h3>
          <span style={{fontSize:11,color:'var(--ink-3)'}}>موصى به: 1600 × 2000 px</span>
        </div>
        <MediaSlot
          kind="photo"
          aspect="4 / 5"
          value={h.image}
          onChange={v=>set('image',v)}
          hint="JPG · PNG · WebP بجودة كاملة"
        />
      </div>
    </SplitEditor>
  );
};

// ---------- ABOUT ----------
const AboutPage = ({ content, update }) => {
  const a = content.about;
  const set = (k,v) => update(c => ({ ...c, about: { ...c.about, [k]:v } }));
  const setPillar = (id, k, v) => update(c => ({ ...c, about:{ ...c.about, pillars: c.about.pillars.map(p => p.id===id ? {...p,[k]:v} : p)}}));
  const addPillar = () => update(c => ({ ...c, about:{ ...c.about, pillars:[...c.about.pillars, {id:'p'+Date.now(), titleAr:'ركيزة جديدة', titleEn:'New pillar', descAr:'', descEn:''}] }}));
  const delPillar = (id) => update(c => ({ ...c, about:{ ...c.about, pillars: c.about.pillars.filter(p=>p.id!==id) }}));

  return (
    <SplitEditor
      title="قسم عنّا"
      sub="نبذة عن الاستوديو + الركائز الأساسية + الاقتباس."
      anchor="about"
      content={content}
    >
      <div className="card">
        <div className="card-head"><h3>الرأس</h3></div>
        <Bilingual labelAr="Eyebrow" labelEn="Eyebrow" valueAr={a.eyebrowAr} valueEn={a.eyebrowEn} onChangeAr={v=>set('eyebrowAr',v)} onChangeEn={v=>set('eyebrowEn',v)} />
        <Bilingual labelAr="العنوان" labelEn="Title" valueAr={a.titleAr} valueEn={a.titleEn} onChangeAr={v=>set('titleAr',v)} onChangeEn={v=>set('titleEn',v)} multiline rows={2}/>
        <Bilingual labelAr="النص الأساسي" labelEn="Body text" valueAr={a.bodyAr} valueEn={a.bodyEn} onChangeAr={v=>set('bodyAr',v)} onChangeEn={v=>set('bodyEn',v)} multiline rows={4}/>
        <Bilingual labelAr="الاقتباس" labelEn="Quote" valueAr={a.quoteAr} valueEn={a.quoteEn} onChangeAr={v=>set('quoteAr',v)} onChangeEn={v=>set('quoteEn',v)} multiline rows={2}/>
      </div>

      <div className="card">
        <div className="card-head">
          <h3>الركائز ({a.pillars.length})</h3>
          <button className="btn btn-soft" onClick={addPillar}>{I.plus} ركيزة</button>
        </div>
        {a.pillars.map((p,i) => (
          <div key={p.id} style={{padding:'14px 0',borderTop:i?'1px dashed var(--line)':'none'}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10}}>
              <div style={{display:'flex',alignItems:'center',gap:8}}>
                <span style={{color:'var(--ink-3)',cursor:'grab'}}>{I.drag}</span>
                <span className="serif" style={{color:'var(--accent)',fontSize:14}}>0{i+1}</span>
                <span style={{fontSize:13,fontWeight:600}}>{p.titleAr}</span>
              </div>
              <button className="ibtn danger" onClick={()=>delPillar(p.id)}>{I.trash}</button>
            </div>
            <Bilingual labelAr="عنوان" labelEn="Title" valueAr={p.titleAr} valueEn={p.titleEn} onChangeAr={v=>setPillar(p.id,'titleAr',v)} onChangeEn={v=>setPillar(p.id,'titleEn',v)} />
            <Bilingual labelAr="وصف" labelEn="Description" valueAr={p.descAr} valueEn={p.descEn} onChangeAr={v=>setPillar(p.id,'descAr',v)} onChangeEn={v=>setPillar(p.id,'descEn',v)} multiline rows={2}/>
          </div>
        ))}
      </div>

      <div className="card">
        <div className="card-head"><h3>صورة القسم</h3></div>
        <MediaSlot kind="photo" aspect="4 / 5" value={a.image} onChange={v=>set('image',v)}/>
      </div>
    </SplitEditor>
  );
};

// ---------- SERVICES ----------
const ServicesPage = ({ content, update }) => {
  const items = content.services;
  const set = (id,k,v) => update(c => ({ ...c, services: c.services.map(s => s.id===id?{...s,[k]:v}:s) }));
  const add = () => update(c => ({ ...c, services:[...c.services, {id:'s'+Date.now(), num:String(c.services.length+1).padStart(2,'0'), titleAr:'خدمة جديدة', titleEn:'New service', descAr:'', descEn:'', delivery:'', formatAr:''}] }));
  const del = (id) => update(c => ({ ...c, services: c.services.filter(s=>s.id!==id) }));
  return (
    <SplitEditor
      title="الخدمات"
      sub={`${items.length} خدمات معروضة في الموقع.`}
      anchor="services"
      content={content}
    >
      <div style={{display:'flex',justifyContent:'flex-end',marginBottom:6}}>
        <button className="btn btn-primary" onClick={add}>{I.plus} إضافة خدمة</button>
      </div>
      {items.map((s,i) => (
        <div className="card" key={s.id}>
          <div className="card-head">
            <div style={{display:'flex',alignItems:'center',gap:10}}>
              <span style={{color:'var(--ink-3)',cursor:'grab'}}>{I.drag}</span>
              <span className="serif" style={{color:'var(--accent)',fontSize:18,fontWeight:500}}>{s.num}</span>
              <h3 style={{margin:0}}>{s.titleAr}</h3>
            </div>
            <div style={{display:'flex',gap:6}}>
              <button className="ibtn">{I.edit}</button>
              <button className="ibtn danger" onClick={()=>del(s.id)}>{I.trash}</button>
            </div>
          </div>
          <Bilingual labelAr="اسم الخدمة" labelEn="Service name" valueAr={s.titleAr} valueEn={s.titleEn} onChangeAr={v=>set(s.id,'titleAr',v)} onChangeEn={v=>set(s.id,'titleEn',v)} />
          <Bilingual labelAr="الوصف" labelEn="Description" valueAr={s.descAr} valueEn={s.descEn} onChangeAr={v=>set(s.id,'descAr',v)} onChangeEn={v=>set(s.id,'descEn',v)} multiline rows={3}/>
          <div className="field-row">
            <Field label="مدة التسليم"><input className="input" value={s.delivery} onChange={e=>set(s.id,'delivery',e.target.value)}/></Field>
            <Field label="التفاصيل التقنية"><input className="input" value={s.formatAr} onChange={e=>set(s.id,'formatAr',e.target.value)}/></Field>
          </div>
        </div>
      ))}
    </SplitEditor>
  );
};

// ---------- STATS ----------
const StatsPage = ({ content, update }) => {
  const items = content.stats;
  const set = (id,k,v) => update(c => ({ ...c, stats: c.stats.map(s => s.id===id?{...s,[k]:v}:s) }));
  const add = () => update(c => ({ ...c, stats:[...c.stats, {id:'st'+Date.now(), value:'0', labelAr:'إحصائية', labelEn:'Stat'}] }));
  const del = (id) => update(c => ({ ...c, stats: c.stats.filter(s=>s.id!==id) }));
  return (
    <SplitEditor
      title="أرقام وإنجازات"
      sub="الأرقام البارزة التي تعكس خبرة الاستوديو."
      anchor="stats"
      content={content}
    >
      <div className="card">
        <div className="card-head">
          <h3>الأرقام ({items.length})</h3>
          <button className="btn btn-soft" onClick={add}>{I.plus} رقم جديد</button>
        </div>
        {items.map((s,i) => (
          <div key={s.id} style={{padding:'14px 0',borderTop:i?'1px dashed var(--line)':'none',display:'grid',gridTemplateColumns:'120px 1fr 1fr auto',gap:14,alignItems:'end'}}>
            <Field label="الرقم"><input className="input mono" style={{textAlign:'center',fontSize:18,fontWeight:600}} value={s.value} onChange={e=>set(s.id,'value',e.target.value)}/></Field>
            <Field label="التسمية (AR)"><input className="input" value={s.labelAr} onChange={e=>set(s.id,'labelAr',e.target.value)}/></Field>
            <Field label="Label (EN)"><input className="input en" value={s.labelEn} onChange={e=>set(s.id,'labelEn',e.target.value)}/></Field>
            <div style={{paddingBottom:8}}><button className="ibtn danger" onClick={()=>del(s.id)}>{I.trash}</button></div>
          </div>
        ))}
      </div>
    </SplitEditor>
  );
};

// ---------- PORTFOLIO ----------
const PortfolioPage = ({ content, update }) => {
  const items = content.portfolio;
  const [filter, setFilter] = useState('all');
  const filtered = filter==='all' ? items : filter==='featured' ? items.filter(p=>p.featured) : items.filter(p=>p.type===filter);
  const set = (id,k,v) => update(c => ({ ...c, portfolio: c.portfolio.map(p => p.id===id?{...p,[k]:v}:p) }));
  const add = (type) => update(c => ({ ...c, portfolio:[...c.portfolio, {id:'pf'+Date.now(), type, titleAr:type==='video'?'فيديو جديد':'صورة جديدة', titleEn:type==='video'?'New video':'New photo', categoryAr:'', categoryEn:'', year:'2026', size:'sq', featured:false}] }));
  const del = (id) => update(c => ({ ...c, portfolio: c.portfolio.filter(p=>p.id!==id) }));
  return (
    <SplitEditor
      title="Portfolio · أعمالنا"
      sub={`${items.length} عمل · ${items.filter(p=>p.type==='photo').length} صور · ${items.filter(p=>p.type==='video').length} فيديو`}
      anchor="work"
      content={content}
    >
      <div className="card">
        <div className="card-head">
          <div style={{display:'flex',gap:6}}>
            {[['all','الكل',items.length],['photo','صور',items.filter(p=>p.type==='photo').length],['video','فيديو',items.filter(p=>p.type==='video').length],['featured','مميّزة',items.filter(p=>p.featured).length]].map(([k,l,n])=>(
              <button key={k} className={`btn ${filter===k?'btn-primary':'btn-ghost'}`} onClick={()=>setFilter(k)}>{l} <span style={{opacity:.6,fontSize:11}}>{n}</span></button>
            ))}
          </div>
          <div style={{display:'flex',gap:6}}>
            <button className="btn btn-soft" onClick={()=>add('photo')}>{I.image} صورة</button>
            <button className="btn btn-soft" onClick={()=>add('video')}>{I.video} فيديو</button>
          </div>
        </div>

        <div style={{display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:14}}>
          {filtered.map(p => (
            <div key={p.id} style={{border:'1px solid var(--line)',borderRadius:8,padding:12,background:'var(--bg)'}}>
              <MediaSlot kind={p.type} value={p.media} onChange={v=>set(p.id,'media',v)}/>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginTop:10,marginBottom:8}}>
                <div style={{display:'flex',alignItems:'center',gap:6}}>
                  <Pill tone={p.type==='video'?'blue':'muted'}>{p.type==='video'?'فيديو':'صورة'}</Pill>
                  <span style={{fontSize:11,color:'var(--ink-3)'}}>{p.year}</span>
                </div>
                <div style={{display:'flex',alignItems:'center',gap:8}}>
                  <button className={`ibtn ${p.featured?'':''}`} title="مميّز" onClick={()=>set(p.id,'featured',!p.featured)} style={{color:p.featured?'var(--accent)':'var(--ink-3)'}}>{I.star}</button>
                  <button className="ibtn danger" onClick={()=>del(p.id)}>{I.trash}</button>
                </div>
              </div>
              <input className="input" style={{fontSize:13,padding:'7px 10px',marginBottom:6}} value={p.titleAr} onChange={e=>set(p.id,'titleAr',e.target.value)} placeholder="عنوان (AR)"/>
              <input className="input en" style={{fontSize:12,padding:'7px 10px',marginBottom:6}} value={p.titleEn} onChange={e=>set(p.id,'titleEn',e.target.value)} placeholder="Title (EN)"/>
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 80px',gap:6}}>
                <input className="input" style={{fontSize:12,padding:'6px 8px'}} value={p.categoryAr} onChange={e=>set(p.id,'categoryAr',e.target.value)} placeholder="فئة AR"/>
                <input className="input en" style={{fontSize:12,padding:'6px 8px'}} value={p.categoryEn} onChange={e=>set(p.id,'categoryEn',e.target.value)} placeholder="Category EN"/>
                <select className="select" style={{fontSize:12,padding:'6px 8px'}} value={p.size} onChange={e=>set(p.id,'size',e.target.value)}>
                  <option value="sq">مربّع</option><option value="tall">طولي</option><option value="wide">عريض</option><option value="md">وسط</option><option value="lg">كبير</option>
                </select>
              </div>
            </div>
          ))}
        </div>

        {filtered.length===0 && (
          <EmptyState icon={I.portfolio} title="لا توجد عناصر" hint="ابدأ بإضافة صورة أو فيديو جديد." action={<button className="btn btn-primary" onClick={()=>add('photo')}>{I.plus} إضافة عمل</button>}/>
        )}
      </div>
    </SplitEditor>
  );
};

// ---------- CLIENTS ----------
const ClientsPage = ({ content, update }) => {
  const items = content.clients;
  const set = (id,k,v) => update(c => ({ ...c, clients: c.clients.map(x => x.id===id?{...x,[k]:v}:x) }));
  const add = () => update(c => ({ ...c, clients:[...c.clients, {id:'c'+Date.now(), nameAr:'عميل جديد', nameEn:'New client', typeAr:'جهة', typeEn:'Entity'}] }));
  const del = (id) => update(c => ({ ...c, clients: c.clients.filter(x=>x.id!==id) }));
  return (
    <SplitEditor
      title="العملاء"
      sub={`${items.length} جهة معروضة في قسم العملاء.`}
      anchor="clients"
      content={content}
    >
      <div className="card">
        <div className="card-head">
          <h3>الجهات ({items.length})</h3>
          <button className="btn btn-primary" onClick={add}>{I.plus} إضافة جهة</button>
        </div>
        <table className="tbl">
          <thead><tr><th></th><th>الاسم (AR)</th><th>Name (EN)</th><th>التصنيف</th><th>الشعار</th><th></th></tr></thead>
          <tbody>
            {items.map(c => (
              <tr key={c.id}>
                <td style={{width:28,color:'var(--ink-3)',cursor:'grab'}}>{I.drag}</td>
                <td><input className="input" style={{padding:'6px 9px',fontSize:13}} value={c.nameAr} onChange={e=>set(c.id,'nameAr',e.target.value)}/></td>
                <td><input className="input en" style={{padding:'6px 9px',fontSize:12}} value={c.nameEn} onChange={e=>set(c.id,'nameEn',e.target.value)}/></td>
                <td style={{maxWidth:140}}>
                  <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:4}}>
                    <input className="input" style={{padding:'6px 8px',fontSize:12}} value={c.typeAr} onChange={e=>set(c.id,'typeAr',e.target.value)}/>
                    <input className="input en" style={{padding:'6px 8px',fontSize:12}} value={c.typeEn} onChange={e=>set(c.id,'typeEn',e.target.value)}/>
                  </div>
                </td>
                <td style={{width:120}}>
                  {c.logo ? (
                    <div style={{display:'flex',alignItems:'center',gap:6}}>
                      <img src={c.logo.src} style={{width:40,height:40,objectFit:'contain',background:'#fff',border:'1px solid var(--line)',borderRadius:4,padding:3}}/>
                      <button className="ibtn danger" onClick={()=>set(c.id,'logo',null)}>{I.x}</button>
                    </div>
                  ) : (
                    <label className="btn btn-soft" style={{padding:'5px 10px',fontSize:12,cursor:'pointer'}}>
                      {I.upload} رفع
                      <input type="file" accept="image/*" style={{display:'none'}} onChange={async e=>{const f=e.target.files[0]; if(f){const meta=await probeMedia(f); set(c.id,'logo',meta);}}}/>
                    </label>
                  )}
                </td>
                <td><button className="ibtn danger" onClick={()=>del(c.id)}>{I.trash}</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </SplitEditor>
  );
};

// ---------- CONTACT ----------
const ContactPage = ({ content, update }) => {
  const a = content.contact;
  const set = (k,v) => update(c => ({ ...c, contact: { ...c.contact, [k]:v } }));
  return (
    <SplitEditor title="نموذج التواصل" sub="بيانات التواصل ونصوص قسم طلب عرض السعر." anchor="contact" content={content}>
      <div className="card">
        <div className="card-head"><h3>نصوص القسم</h3></div>
        <Bilingual labelAr="العنوان" labelEn="Title" valueAr={a.titleAr} valueEn={a.titleEn} onChangeAr={v=>set('titleAr',v)} onChangeEn={v=>set('titleEn',v)} multiline rows={2}/>
        <Bilingual labelAr="النص" labelEn="Body" valueAr={a.bodyAr} valueEn={a.bodyEn} onChangeAr={v=>set('bodyAr',v)} onChangeEn={v=>set('bodyEn',v)} multiline rows={3}/>
      </div>
      <div className="card">
        <div className="card-head"><h3>بيانات التواصل</h3></div>
        <Field label="البريد الإلكتروني"><input className="input en" value={a.email} onChange={e=>set('email',e.target.value)}/></Field>
        <Field label="الهاتف"><input className="input en" value={a.phone} onChange={e=>set('phone',e.target.value)}/></Field>
        <Bilingual labelAr="الموقع" labelEn="Location" valueAr={a.locationAr} valueEn={a.locationEn} onChangeAr={v=>set('locationAr',v)} onChangeEn={v=>set('locationEn',v)}/>
        <Bilingual labelAr="ساعات العمل" labelEn="Hours" valueAr={a.hoursAr} valueEn={a.hoursEn} onChangeAr={v=>set('hoursAr',v)} onChangeEn={v=>set('hoursEn',v)}/>
      </div>
      <div className="card">
        <div className="card-head"><h3>خيارات نوع الخدمة في النموذج</h3></div>
        <div className="tag-input">
          {a.serviceOptions.map((s,i)=>(<span key={i} className="tag">{s} <span className="x" onClick={()=>set('serviceOptions', a.serviceOptions.filter((_,j)=>j!==i))}>×</span></span>))}
          <input className="input" style={{flex:1,minWidth:120,border:'none',padding:'4px 6px',background:'transparent'}} placeholder="أضف خياراً ثم Enter" onKeyDown={e=>{if(e.key==='Enter'&&e.target.value){set('serviceOptions',[...a.serviceOptions,e.target.value]);e.target.value=''}}}/>
        </div>
      </div>
    </SplitEditor>
  );
};

// ---------- FOOTER ----------
const FooterPage = ({ content, update }) => {
  const f = content.footer;
  const set = (k,v) => update(c => ({ ...c, footer: { ...c.footer, [k]:v } }));
  const setSocial = (id,k,v) => update(c => ({ ...c, footer:{ ...c.footer, socials: c.footer.socials.map(s=>s.id===id?{...s,[k]:v}:s) }}));
  const addSocial = () => update(c => ({ ...c, footer:{ ...c.footer, socials:[...c.footer.socials, {id:'sc'+Date.now(), name:'منصة', url:''}] }}));
  const delSocial = (id) => update(c => ({ ...c, footer:{ ...c.footer, socials: c.footer.socials.filter(s=>s.id!==id) }}));
  return (
    <SplitEditor title="Footer" sub="الجزء السفلي للموقع — التيغلاين وحقوق النشر وروابط التواصل الاجتماعي." anchor="contact" content={content}>
      <div className="card">
        <div className="card-head"><h3>النصوص</h3></div>
        <Bilingual labelAr="التيغلاين" labelEn="Tagline" valueAr={f.taglineAr} valueEn={f.taglineEn} onChangeAr={v=>set('taglineAr',v)} onChangeEn={v=>set('taglineEn',v)} multiline rows={2}/>
        <Bilingual labelAr="حقوق النشر" labelEn="Copyright" valueAr={f.copyrightAr} valueEn={f.copyrightEn} onChangeAr={v=>set('copyrightAr',v)} onChangeEn={v=>set('copyrightEn',v)}/>
      </div>
      <div className="card">
        <div className="card-head">
          <h3>وسائل التواصل ({f.socials.length})</h3>
          <button className="btn btn-soft" onClick={addSocial}>{I.plus} منصة</button>
        </div>
        {f.socials.map((s,i)=>(
          <div key={s.id} style={{display:'grid',gridTemplateColumns:'140px 1fr auto',gap:10,alignItems:'end',padding:'10px 0',borderTop:i?'1px dashed var(--line)':'none'}}>
            <Field label="المنصة"><input className="input" value={s.name} onChange={e=>setSocial(s.id,'name',e.target.value)}/></Field>
            <Field label="الرابط"><input className="input en" value={s.url} onChange={e=>setSocial(s.id,'url',e.target.value)} placeholder="https://"/></Field>
            <div style={{paddingBottom:8}}><button className="ibtn danger" onClick={()=>delSocial(s.id)}>{I.trash}</button></div>
          </div>
        ))}
      </div>
    </SplitEditor>
  );
};

// ---------- SUBMISSIONS ----------
const SubmissionsPage = ({ submissions, setSubmissions }) => {
  const [filter, setFilter] = useState('all');
  const [selected, setSelected] = useState(null);
  const counts = {
    all: submissions.length,
    new: submissions.filter(s=>s.status==='new').length,
    replied: submissions.filter(s=>s.status==='replied').length,
    converted: submissions.filter(s=>s.status==='converted').length,
    archived: submissions.filter(s=>s.status==='archived').length,
  };
  const list = filter==='all' ? submissions : submissions.filter(s=>s.status===filter);
  const update = (id, patch) => setSubmissions(s => s.map(x => x.id===id?{...x,...patch}:x));
  const sel = selected && submissions.find(s=>s.id===selected);

  return (
    <div>
      <div className="page-head" style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end'}}>
        <div>
          <h2>طلبات عروض الأسعار</h2>
          <p>{counts.new} طلب جديد بحاجة لمراجعة · {submissions.length} إجمالي</p>
        </div>
        <button className="btn btn-ghost">{I.upload} تصدير CSV</button>
      </div>

      <div style={{display:'grid',gridTemplateColumns: sel?'1fr 380px':'1fr',gap:18}}>
        <div className="card" style={{padding:0,overflow:'hidden'}}>
          <div style={{display:'flex',gap:0,borderBottom:'1px solid var(--line)',background:'var(--paper-2)'}}>
            {[['all','الكل'],['new','جديد'],['replied','تم الرد'],['converted','محوّل'],['archived','مؤرشف']].map(([k,l])=>(
              <button key={k} onClick={()=>setFilter(k)} style={{padding:'12px 18px',fontSize:13,fontWeight:500,color:filter===k?'var(--ink)':'var(--ink-3)',borderBottom:filter===k?'2px solid var(--accent)':'2px solid transparent'}}>
                {l} <span style={{color:'var(--ink-3)',fontSize:11,marginInlineStart:4}}>{counts[k]}</span>
              </button>
            ))}
          </div>
          <table className="tbl">
            <thead><tr><th></th><th>الاسم والجهة</th><th>الخدمة</th><th>تاريخ الفعالية</th><th>الحالة</th><th>وصل</th></tr></thead>
            <tbody>
              {list.map(s => (
                <tr key={s.id} onClick={()=>setSelected(s.id)} style={{cursor:'pointer',background:selected===s.id?'var(--bg)':''}}>
                  <td style={{width:32}}>
                    <button className="ibtn" style={{border:'none',color:s.starred?'var(--accent)':'var(--ink-3)'}} onClick={e=>{e.stopPropagation();update(s.id,{starred:!s.starred})}}>{I.star}</button>
                  </td>
                  <td>
                    <div className="name">{s.name}</div>
                    <div style={{fontSize:12,color:'var(--ink-3)'}}>{s.org}</div>
                  </td>
                  <td>{s.service}</td>
                  <td className="mono" style={{fontSize:12}}>{s.date}</td>
                  <td><Pill tone={SUB_STATUS[s.status].tone}>{SUB_STATUS[s.status].label}</Pill></td>
                  <td style={{fontSize:11,color:'var(--ink-3)'}} className="mono">{s.createdAt}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {list.length===0 && <EmptyState icon={I.inbox} title="لا توجد طلبات" hint="ستظهر هنا حين يصلك طلب جديد عبر نموذج الموقع."/>}
        </div>

        {sel && (
          <div className="card" style={{position:'sticky',top:84,height:'fit-content'}}>
            <div className="card-head">
              <h3>{sel.name}</h3>
              <button className="ibtn" onClick={()=>setSelected(null)}>{I.x}</button>
            </div>
            <div style={{display:'flex',gap:8,marginBottom:14}}>
              <Pill tone={SUB_STATUS[sel.status].tone}>{SUB_STATUS[sel.status].label}</Pill>
              {sel.starred && <Pill tone="amber">★ مميّز</Pill>}
            </div>
            {[
              ['الجهة', sel.org],
              ['البريد', sel.email],
              ['الهاتف', sel.phone],
              ['الخدمة', sel.service],
              ['تاريخ الفعالية', sel.date],
              ['وصل في', sel.createdAt],
            ].map(([k,v])=>(
              <div key={k} style={{padding:'10px 0',borderBottom:'1px dashed var(--line)',display:'flex',justifyContent:'space-between',gap:10}}>
                <span style={{color:'var(--ink-3)',fontSize:12}}>{k}</span>
                <span style={{fontSize:13,fontWeight:500,textAlign:'left'}} className={k==='البريد'||k==='الهاتف'?'mono':''}>{v}</span>
              </div>
            ))}
            <div style={{margin:'14px 0'}}>
              <div style={{color:'var(--ink-3)',fontSize:12,marginBottom:6}}>التفاصيل</div>
              <div style={{background:'var(--bg)',border:'1px solid var(--line)',padding:12,borderRadius:6,fontSize:13,lineHeight:1.6}}>{sel.details}</div>
            </div>
            <div style={{display:'flex',flexDirection:'column',gap:8}}>
              <button className="btn btn-primary">{I.reply} الرد عبر البريد</button>
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
                <button className="btn btn-soft" onClick={()=>update(sel.id,{status:'converted'})}>{I.check} تحويل لطلب</button>
                <button className="btn btn-soft" onClick={()=>update(sel.id,{status:'archived'})}>أرشفة</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// ---------- SETTINGS (meta + SEO + publish) ----------
const SettingsPage = ({ content, update, setSavedRecently }) => {
  const m = content.meta;
  const setMeta = (k,v) => update(c => ({ ...c, meta: { ...c.meta, [k]:v } }));
  const setPub = (s) => update(c => ({ ...c, publishStatus:s }));
  return (
    <div>
      <div className="page-head">
        <h2>الإعدادات العامة</h2>
        <p>اللوجو، الـ SEO، وحالة النشر.</p>
      </div>
      <div style={{display:'grid',gridTemplateColumns:'1fr 380px',gap:18}}>
        <div style={{display:'flex',flexDirection:'column',gap:16}}>
          <div className="card">
            <div className="card-head"><h3>هوية الموقع</h3></div>
            <Field label="اسم الموقع"><input className="input" value={m.siteName} onChange={e=>setMeta('siteName',e.target.value)}/></Field>
            <Field label="الرابط (URL)"><input className="input en" value={m.siteUrl} onChange={e=>setMeta('siteUrl',e.target.value)}/></Field>
            <div className="field-row">
              <Field label="نص اللوجو"><input className="input en" value={m.logoText} onChange={e=>setMeta('logoText',e.target.value)}/></Field>
              <Field label="الأيقونة (Favicon)"><button className="btn btn-soft" style={{width:'100%',justifyContent:'center'}}>{I.upload} رفع .ico / .png</button></Field>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3>SEO · محركات البحث</h3></div>
            <Bilingual labelAr="عنوان الصفحة (Title)" labelEn="Page title" valueAr={m.seoTitleAr} valueEn={m.seoTitleEn} onChangeAr={v=>setMeta('seoTitleAr',v)} onChangeEn={v=>setMeta('seoTitleEn',v)} />
            <Bilingual labelAr="الوصف (Description)" labelEn="Description" valueAr={m.seoDescAr} valueEn={m.seoDescEn} onChangeAr={v=>setMeta('seoDescAr',v)} onChangeEn={v=>setMeta('seoDescEn',v)} multiline rows={3}/>
            <Field label="صورة المشاركة (Open Graph · 1200×630)">
              <MediaSlot kind="photo" aspect="1200 / 630" value={m.ogImage} onChange={v=>setMeta('ogImage',v)}/>
            </Field>
          </div>
        </div>

        <div style={{display:'flex',flexDirection:'column',gap:16}}>
          <div className="card">
            <div className="card-head"><h3>حالة النشر</h3></div>
            <div style={{display:'flex',flexDirection:'column',gap:8}}>
              {Object.entries(PUB_STATUS).map(([k,v]) => (
                <label key={k} style={{display:'flex',alignItems:'center',gap:10,padding:'10px 12px',border:'1px solid var(--line-2)',borderRadius:7,cursor:'pointer',background:content.publishStatus===k?'var(--bg)':''}}>
                  <input type="radio" checked={content.publishStatus===k} onChange={()=>setPub(k)} style={{margin:0,accentColor:'var(--accent)'}}/>
                  <Pill tone={v.tone}>{v.label}</Pill>
                  <span style={{fontSize:12,color:'var(--ink-3)',marginInlineStart:'auto'}}>{k==='published'?'مرئي للعموم':k==='draft'?'مخفي':'في تاريخ محدد'}</span>
                </label>
              ))}
            </div>
            {content.publishStatus==='scheduled' && (
              <div style={{marginTop:12}}>
                <Field label="تاريخ النشر">
                  <input className="input en" type="datetime-local" value={content.scheduledAt} onChange={e=>update(c=>({...c,scheduledAt:e.target.value}))}/>
                </Field>
              </div>
            )}
            <button className="btn btn-accent" style={{width:'100%',justifyContent:'center',marginTop:12}} onClick={()=>setSavedRecently(true)}>{I.check} نشر التغييرات الآن</button>
          </div>

          <div className="card">
            <div className="card-head"><h3>روابط</h3></div>
            <div style={{display:'flex',flexDirection:'column',gap:8}}>
              <a className="btn btn-ghost" style={{justifyContent:'space-between'}} href="home.html" target="_blank">عرض الموقع المباشر {I.external}</a>
              <a className="btn btn-ghost" style={{justifyContent:'space-between'}} href="index.html" target="_blank">النظام المالي {I.external}</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- THEME ----------
const ThemePage = ({ content, update }) => {
  const t = content.theme;
  const set = (k,v) => update(c => ({ ...c, theme: { ...c.theme, [k]:v } }));
  return (
    <div>
      <div className="page-head"><h2>المظهر</h2><p>الألوان، الخطوط، وحدّة الزوايا.</p></div>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:18}}>
        <div className="card">
          <div className="card-head"><h3>قوالب جاهزة</h3></div>
          <div className="preset-grid">
            {THEME_PRESETS.map(p => (
              <div key={p.id} className={cls('preset', t.preset===p.id && 'active')} onClick={()=>set('preset',p.id)}>
                <div className="swatches">{p.colors.map((c,i)=><div key={i} className="sw" style={{background:c}}/>)}</div>
                <div className="pname">{p.name}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-head"><h3>ألوان مخصّصة</h3></div>
          {[['الحبر الرئيسي','primary','#1a1814'],['اللون المميّز (Accent)','accent','#b8893b'],['الخلفية','bg','#f5f2ec'],['الورق','paper','#fbfaf6']].map(([l,k,d])=>(
            <div key={k} style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'10px 0',borderBottom:'1px dashed var(--line)'}}>
              <span style={{fontSize:13,fontWeight:500}}>{l}</span>
              <div style={{display:'flex',alignItems:'center',gap:8}}>
                <input className="input mono" style={{width:110,padding:'6px 9px',fontSize:12}} value={t[k]||d} onChange={e=>set(k,e.target.value)}/>
                <input type="color" value={t[k]||d} onChange={e=>set(k,e.target.value)} style={{width:32,height:32,border:'1px solid var(--line-2)',borderRadius:6,padding:0,background:'none',cursor:'pointer'}}/>
              </div>
            </div>
          ))}
        </div>

        <div className="card">
          <div className="card-head"><h3>الخطوط</h3></div>
          <Field label="خط العناوين">
            <select className="select" value={t.headingFont} onChange={e=>set('headingFont',e.target.value)}>
              <option>IBM Plex Sans Arabic</option><option>Cormorant Garamond</option><option>Tajawal</option><option>Almarai</option><option>Cairo</option>
            </select>
          </Field>
          <Field label="خط النصوص">
            <select className="select" value={t.bodyFont} onChange={e=>set('bodyFont',e.target.value)}>
              <option>IBM Plex Sans Arabic</option><option>Tajawal</option><option>Almarai</option><option>Cairo</option>
            </select>
          </Field>
          <div style={{padding:16,background:'var(--bg)',borderRadius:8,marginTop:8}}>
            <div style={{fontFamily:t.headingFont,fontSize:24,fontWeight:600,marginBottom:6}}>نوثّق اللحظات بإحساس سينمائي</div>
            <div style={{fontFamily:t.bodyFont,fontSize:13,color:'var(--ink-2)',lineHeight:1.6}}>استوديو إماراتي متخصص في توثيق الفعاليات الرسمية والمؤتمرات والمعارض.</div>
          </div>
        </div>

        <div className="card">
          <div className="card-head"><h3>الشكل</h3></div>
          <Field label={`حدّة الزوايا (${t.radius}px)`}>
            <input type="range" min="0" max="20" value={t.radius} onChange={e=>set('radius',+e.target.value)} style={{width:'100%',accentColor:'var(--accent)'}}/>
          </Field>
          <div style={{display:'flex',gap:10,marginTop:14}}>
            {[0,4,8,14,20].map(r=>(
              <div key={r} style={{width:62,height:62,background:'var(--accent)',borderRadius:r,opacity:t.radius===r?1:.45,cursor:'pointer'}} onClick={()=>set('radius',r)}/>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- HISTORY ----------
const HistoryPage = ({ log }) => (
  <div>
    <div className="page-head"><h2>سجل التعديلات</h2><p>كل تغيير يتم على الموقع — قابل للاسترجاع.</p></div>
    <div className="card">
      <div className="timeline">
        {log.map(l => (
          <div className="tl-item" key={l.id} style={{paddingBottom:24}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:14}}>
              <div>
                <div style={{fontSize:14,marginBottom:3}}>{l.what}</div>
                <div className="tl-when">{l.when} · بواسطة {l.who}</div>
              </div>
              <button className="btn btn-ghost" style={{padding:'6px 12px',fontSize:12}}>{I.backup} استرجاع</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ---------- BACKUPS ----------
const BackupsPage = ({ backups }) => (
  <div>
    <div className="page-head" style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end'}}>
      <div><h2>النسخ الاحتياطية</h2><p>{backups.length} نسخة محفوظة · النسخ التلقائي يومياً 04:00</p></div>
      <button className="btn btn-primary">{I.backup} إنشاء نسخة الآن</button>
    </div>
    <div className="card" style={{padding:0,overflow:'hidden'}}>
      <table className="tbl">
        <thead><tr><th>التاريخ</th><th>النوع</th><th>الحجم</th><th>الحالة</th><th></th></tr></thead>
        <tbody>
          {backups.map(b => (
            <tr key={b.id}>
              <td className="name mono" style={{fontSize:12}}>{b.when}</td>
              <td>{b.type}</td>
              <td className="mono" style={{fontSize:12,color:'var(--ink-3)'}}>{b.size}</td>
              <td>{b.current ? <Pill tone="green">الحالية</Pill> : <Pill tone="muted">محفوظة</Pill>}</td>
              <td style={{textAlign:'left'}}>
                <button className="btn btn-ghost" style={{padding:'6px 12px',fontSize:12}}>تنزيل</button>
                {!b.current && <button className="btn btn-soft" style={{padding:'6px 12px',fontSize:12,marginInlineStart:6}}>استرجاع</button>}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

// Expose
Object.assign(window, {
  DashboardPage, HeroPage, AboutPage, ServicesPage, StatsPage, PortfolioPage,
  ClientsPage, ContactPage, FooterPage, SubmissionsPage, SettingsPage,
  ThemePage, HistoryPage, BackupsPage
});
