/* ============================================================
   MAISON ATLAS — admin dashboard app
   ============================================================ */

const svcLabel = (lang, id) => T(lang, 'svc_' + id + '_t');
const vehLabel = (lang, id) => id ? T(lang, 'veh_' + id + '_t') : T(lang, 'ad_unassigned');
const STATUSES = ['pending', 'confirmed', 'progress', 'done', 'refused'];
const adminText = (lang, key) => ({
  fr: {
    content: 'Contenu', services: 'Services', events: 'Evenements', news: 'Actualites', users: 'Utilisateurs', add: 'Ajouter', save: 'Sauvegarder', remove: 'Supprimer', duplicate: 'Dupliquer', edit: 'Modifier', cancel: 'Annuler', saved: 'Sauvegarde', invalid: 'JSON invalide', config: 'Coordonnees', whatsapp: 'WhatsApp', phone: 'Telephone', email: 'Email', address: 'Adresse', platformUsers: 'Utilisateurs plateforme', passwordHint: 'Mot de passe optionnel, jamais affiche apres sauvegarde.'
  },
  en: {
    content: 'Content', services: 'Services', events: 'Events', news: 'News', users: 'Users', add: 'Add', save: 'Save', remove: 'Delete', duplicate: 'Duplicate', edit: 'Edit', cancel: 'Cancel', saved: 'Saved', invalid: 'Invalid JSON', config: 'Contact details', whatsapp: 'WhatsApp', phone: 'Phone', email: 'Email', address: 'Address', platformUsers: 'Platform users', passwordHint: 'Optional password, never shown after save.'
  },
  ar: {
    content: 'المحتوى', services: 'الخدمات', events: 'الفعاليات', news: 'الأخبار', users: 'المستخدمون', add: 'إضافة', save: 'حفظ', remove: 'حذف', duplicate: 'نسخ', edit: 'تعديل', cancel: 'إلغاء', saved: 'تم الحفظ', invalid: 'JSON غير صالح', config: 'بيانات التواصل', whatsapp: 'واتساب', phone: 'الهاتف', email: 'البريد', address: 'العنوان', platformUsers: 'مستخدمو المنصة', passwordHint: 'كلمة المرور اختيارية ولا تظهر بعد الحفظ.'
  },
}[lang] || {})[key] || key;

/* ---------------- Sidebar ---------------- */
function Sidebar({ lang, setLang, view, setView, counts, onClose }) {
  const items = [
    { id: 'overview', ic: 'grid', label: 'ad_nav_overview' },
    { id: 'requests', ic: 'list', label: 'ad_nav_requests', count: counts.pending },
    { id: 'config', ic: 'phone', labelText: adminText(lang, 'config') },
    { id: 'services', ic: 'grid', labelText: adminText(lang, 'services') },
    { id: 'events', ic: 'cal', labelText: adminText(lang, 'events') },
    { id: 'news', ic: 'chat', labelText: adminText(lang, 'news') },
    { id: 'fleet', ic: 'car', label: 'ad_nav_fleet' },
    { id: 'drivers', ic: 'users', label: 'ad_nav_drivers' },
    { id: 'users', ic: 'user', labelText: adminText(lang, 'users') },
    { id: 'content', ic: 'chat', labelText: adminText(lang, 'content') },
  ];
  return (
    <aside className="admin-side">
      <div className="side-brand">
        <Logo lang={lang} href="/" />
      </div>
      <nav className="side-nav">
        {items.map(it => (
          <button key={it.id} className={'side-link' + (view === it.id ? ' active' : '')}
            onClick={() => { setView(it.id); onClose && onClose(); }}>
            <span className="side-ic"><Ic name={it.ic} size={19} /></span>
            <span>{it.labelText || T(lang, it.label)}</span>
            {it.count ? <span className="side-count">{it.count}</span> : null}
          </button>
        ))}
      </nav>
      <div className="side-foot">
        <LangSwitch lang={lang} setLang={setLang} />
        <a className="btn btn-dark btn-sm" href="/"><Ic name="globe" size={15} />{T(lang, 'ad_site')}</a>
      </div>
    </aside>
  );
}

/* ---------------- Stat cards ---------------- */
function StatCards({ lang, requests }) {
  const by = (s) => requests.filter(r => r.status === s).length;
  const revenue = requests.filter(r => r.quote && r.status !== 'refused').reduce((a, r) => a + r.quote, 0);
  const cards = [
    { lbl: 'ad_stat_pending', val: by('pending'), color: 'var(--st-pending)' },
    { lbl: 'ad_stat_confirmed', val: by('confirmed'), color: 'var(--st-confirmed)' },
    { lbl: 'ad_stat_progress', val: by('progress'), color: 'var(--st-progress)' },
    { lbl: 'ad_stat_done', val: by('done'), color: 'var(--st-done)' },
    { lbl: 'ad_stat_revenue', val: window.ATLAS.fmtMoney(revenue, lang, 'MAD'), color: 'var(--accent)', big: true },
  ];
  return (
    <div className="stat-cards">
      {cards.map((c, i) => (
        <div className="stat-card" key={i}>
          <div className="sc-top">
            <span className="sc-lbl">{T(lang, c.lbl)}</span>
            <span className="sc-dot" style={{ background: c.color }}></span>
          </div>
          <div className="sc-num" style={c.big ? { fontSize: '1.6rem', color: c.color } : null}>{c.val}</div>
        </div>
      ))}
    </div>
  );
}

/* ---------------- Request list item ---------------- */
function ReqItem({ lang, r, active, onClick }) {
  return (
    <button className={'req-item' + (active ? ' active' : '')} onClick={onClick}>
      {r.unreadByAgency && <span className="new-tag">{T(lang, 'ad_new')}</span>}
      <div className="ri-top">
        <div>
          <div className="ri-name">{r.name}</div>
          <div className="ri-svc">{svcLabel(lang, r.service)}</div>
        </div>
        <StatusBadge status={r.status} lang={lang} />
      </div>
      <div className="ri-route"><Ic name="pin" size={14} />{r.pickup} → {r.dropoff}</div>
      <div className="ri-meta">
        <span><Ic name="cal" size={13} /> {window.ATLAS.fmtDate(r.date, lang)} · {r.time}</span>
        <span className="ri-id">{r.id}</span>
      </div>
    </button>
  );
}

/* ---------------- Requests view ---------------- */
function RequestsView({ lang, requests, selId, setSelId, search }) {
  const [filter, setFilter] = useState('all');
  const filters = [{ id: 'all' }].concat(STATUSES.map(s => ({ id: s })));
  let list = requests;
  if (search) {
    const q = search.toLowerCase();
    list = list.filter(r => (r.name + r.id + r.pickup + r.dropoff).toLowerCase().includes(q));
  }
  const filtered = filter === 'all' ? list : list.filter(r => r.status === filter);
  const sel = requests.find(r => r.id === selId);

  return (
    <div className="req-layout">
      <div className="req-list-wrap">
        <div className="filter-tabs">
          {filters.map(f => {
            const n = f.id === 'all' ? list.length : list.filter(r => r.status === f.id).length;
            return (
              <button key={f.id} className={'filter-tab' + (filter === f.id ? ' active' : '')} onClick={() => setFilter(f.id)}>
                {f.id === 'all' ? T(lang, 'ad_filter_all') : T(lang, 'st_' + f.id)}
                <span className="ft-n">{n}</span>
              </button>
            );
          })}
        </div>
        <div className="req-list">
          {filtered.length === 0 && (
            <div style={{ textAlign: 'center', padding: '50px 20px', color: 'var(--faint)' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: '1.3rem', marginBottom: 8 }}>{T(lang, 'ad_empty')}</div>
              <div style={{ fontSize: '0.88rem' }}>{T(lang, 'ad_empty_sub')}</div>
            </div>
          )}
          {filtered.map(r => (
            <ReqItem key={r.id} lang={lang} r={r} active={r.id === selId} onClick={() => setSelId(r.id)} />
          ))}
        </div>
      </div>

      {sel
        ? <RequestDetail lang={lang} r={sel} requests={requests} />
        : (
          <div className="detail">
            <div className="detail-empty">
              <div>
                <div className="de-ic"><Ic name="list" size={28} /></div>
                <h3>{T(lang, 'ad_select_prompt')}</h3>
                <p className="faint" style={{ marginTop: 6 }}>{T(lang, 'ad_select_sub')}</p>
              </div>
            </div>
          </div>
        )}
    </div>
  );
}

/* ---------------- Request detail ---------------- */
function RequestDetail({ lang, r, requests }) {
  const [quoteDraft, setQuoteDraft] = useState(r.quote || '');
  const [msg, setMsg] = useState('');
  const [payBusy, setPayBusy] = useState(false);
  const threadRef = useRef(null);

  useEffect(() => { setQuoteDraft(r.quote || ''); }, [r.id]);
  useEffect(() => { if (r.unreadByAgency) window.ATLAS.updateRequest(r.id, { unreadByAgency: false }); }, [r.id]);
  useEffect(() => { if (threadRef.current) threadRef.current.scrollTop = threadRef.current.scrollHeight; }, [r.messages.length, r.id]);

  const upd = (patch) => window.ATLAS.updateRequest(r.id, patch);

  const busyVehicles = new Set(requests.filter(x => x.id !== r.id && ['confirmed', 'progress'].includes(x.status) && x.vehicle).map(x => x.vehicle));
  const busyDrivers = new Set(requests.filter(x => x.id !== r.id && ['confirmed', 'progress'].includes(x.status) && x.driver).map(x => x.driver));

  const sendQuote = () => { if (quoteDraft) upd({ quote: Number(quoteDraft) }); };
  const payLabel = (key) => ({
    fr: { title: 'Paiement', none: 'Aucun paiement encore.', paid: 'Paye', pending: 'En attente', failed: 'Echoue', cash: 'agence', card: 'carte', transfer: 'virement', markPaid: 'Marquer paye', markPending: 'Remettre en attente' },
    en: { title: 'Payment', none: 'No payment yet.', paid: 'Paid', pending: 'Pending', failed: 'Failed', cash: 'agency', card: 'card', transfer: 'transfer', markPaid: 'Mark paid', markPending: 'Set pending' },
    ar: { title: 'الدفع', none: 'لا يوجد دفع بعد.', paid: 'مدفوع', pending: 'في الانتظار', failed: 'فشل', cash: 'وكالة', card: 'بطاقة', transfer: 'تحويل', markPaid: 'تأكيد الدفع', markPending: 'إرجاع للانتظار' },
  }[lang] || {})[key] || key;
  const setPayment = (status) => {
    setPayBusy(true);
    window.ATLAS.api.updatePayment(r.id, status)
      .then(() => setPayBusy(false))
      .catch(() => setPayBusy(false));
  };
  const send = () => {
    if (!msg.trim()) return;
    window.ATLAS.addMessage(r.id, 'agency', msg.trim());
    setMsg('');
  };

  return (
    <div className="detail">
      <div className="detail-head">
        <div>
          <div className="dh-id">{r.id}</div>
          <div className="dh-name display">{r.name}</div>
          <div className="dh-svc">{svcLabel(lang, r.service)}</div>
        </div>
        <StatusBadge status={r.status} lang={lang} />
      </div>

      <div className="detail-grid">
        <div className="info-cell">
          <div className="ic-lbl"><Ic name="pin" size={13} />{T(lang, 'ad_trip')}</div>
          <div className="ic-val">{r.pickup}<br /><small>↓</small><br />{r.dropoff}</div>
        </div>
        <div className="info-cell">
          <div className="ic-lbl"><Ic name="cal" size={13} />{T(lang, 'ad_col_when')}</div>
          <div className="ic-val">{window.ATLAS.fmtDate(r.date, lang)}<br /><small>{r.time}</small></div>
        </div>
        <div className="info-cell">
          <div className="ic-lbl"><Ic name="users" size={13} />{T(lang, 'ad_passengers')}</div>
          <div className="ic-val">{r.passengers}{r.billing ? <span> · <span style={{ color: 'var(--accent)' }}>{T(lang, 'bill_label')}: {T(lang, 'bill_' + r.billing)}</span></span> : null}</div>
        </div>
        <div className="info-cell">
          <div className="ic-lbl"><Ic name="user" size={13} />{T(lang, 'ad_client_info')}</div>
          <div className="ic-val">{r.phone}<br /><small>{r.email || '—'}</small></div>
        </div>
        {r.notes ? (
          <div className="info-cell" style={{ gridColumn: '1 / -1' }}>
            <div className="ic-lbl"><Ic name="chat" size={13} />Notes</div>
            <div className="ic-val">{r.notes}</div>
          </div>
        ) : null}
      </div>

      {/* Actions */}
      <div className="detail-sec">
        <h4>{T(lang, 'ad_actions')}</h4>
        <div className="action-row">
          <button className="btn btn-primary btn-sm" onClick={() => upd({ status: 'confirmed' })}><Ic name="check" size={15} />{T(lang, 'ad_accept')}</button>
          <button className="btn btn-ghost btn-sm" onClick={() => upd({ status: 'refused' })}><Ic name="x" size={15} />{T(lang, 'ad_refuse')}</button>
        </div>
        <div className="assign-grid">
          <div className="field">
            <label>{T(lang, 'ad_assign_vehicle')}</label>
            <select className="select" value={r.vehicle || ''} onChange={e => upd({ vehicle: e.target.value || null })}>
              <option value="">{T(lang, 'ad_none')}</option>
              {window.ATLAS.vehicles.map(v => (
                <option key={v.id} value={v.id}>{vehLabel(lang, v.id)}{busyVehicles.has(v.id) ? ' · ' + T(lang, 'ad_busy') : ''}</option>
              ))}
            </select>
          </div>
          <div className="field">
            <label>{T(lang, 'ad_assign_driver')}</label>
            <select className="select" value={r.driver || ''} onChange={e => upd({ driver: e.target.value || null })}>
              <option value="">{T(lang, 'ad_none')}</option>
              {window.ATLAS.drivers.map(d => (
                <option key={d.id} value={d.id}>{d.name}{busyDrivers.has(d.id) ? ' · ' + T(lang, 'ad_busy') : ''}</option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Quote */}
      <div className="detail-sec">
        <h4>{T(lang, 'ad_quote')}</h4>
        {r.quote ? (
          <div className="quote-display" style={{ marginBottom: 12 }}>
            <span className="qd-lbl">{T(lang, 'ad_quote_label')}</span>
            <span className="qd-amt display">{window.ATLAS.fmtMoney(r.quote, lang, 'MAD')}</span>
          </div>
        ) : null}
        {r.quoteAccepted ? (
          <div className="quote-signed">
            <div className="badge confirmed" style={{ marginBottom: 10 }}><span className="dot"></span>{T(lang, 'q_accepted')}</div>
            <div className="sig-proof">
              <img src={r.signature} alt="signature" />
              <div className="sig-meta">
                <div>{T(lang, 'q_signed_by')} <strong>{r.signerName}</strong></div>
                <div className="faint">{T(lang, 'q_accepted_on')} {window.ATLAS.fmtDate(new Date(r.acceptedAt).toISOString().slice(0,10), lang)}</div>
              </div>
            </div>
          </div>
        ) : (
          <div className="quote-row">
            <div className="field">
              <input className="input" type="number" placeholder={T(lang, 'ad_quote_ph')} value={quoteDraft} onChange={e => setQuoteDraft(e.target.value)} />
            </div>
            <button className="btn btn-dark btn-sm" onClick={sendQuote}><Ic name="money" size={15} />{T(lang, 'ad_send_quote')}</button>
          </div>
        )}
      </div>

      {/* Payment */}
      <div className="detail-sec">
        <h4>{payLabel('title')}</h4>
        {r.payment ? (
          <div className="admin-payment-card">
            <div>
              <div className="pay-ref">{r.payment.id}</div>
              <div className="faint">{payLabel(r.payment.method)} · {window.ATLAS.fmtMoney(r.payment.amount, lang, 'MAD')}</div>
            </div>
            <span className={'badge ' + (r.payment.status === 'paid' ? 'confirmed' : r.payment.status === 'failed' ? 'refused' : 'pending')}><span className="dot"></span>{payLabel(r.payment.status)}</span>
          </div>
        ) : <div className="faint">{payLabel('none')}</div>}
        <div className="action-row" style={{ marginTop: 12, marginBottom: 0 }}>
          <button className="btn btn-primary btn-sm" onClick={() => setPayment('paid')} disabled={payBusy}><Ic name="check" size={15} />{payLabel('markPaid')}</button>
          <button className="btn btn-ghost btn-sm" onClick={() => setPayment('pending')} disabled={payBusy}>{payLabel('markPending')}</button>
        </div>
      </div>

      {/* Status */}
      <div className="detail-sec">
        <h4>{T(lang, 'ad_set_status')}</h4>
        <div className="status-pills">
          {STATUSES.map(s => (
            <button key={s} className={'status-pill' + (r.status === s ? ' on' : '')} onClick={() => upd({ status: s })}>{T(lang, 'st_' + s)}</button>
          ))}
        </div>
      </div>

      {/* Chat */}
      <div className="detail-sec" style={{ borderBottom: 'none' }}>
        <h4>{T(lang, 'ad_chat')}</h4>
        <div className="chat-thread" ref={threadRef}>
          {(r.messages || []).map((m, i) => (
            <div key={i} className={'msg ' + m.from}>
              {m.text}
              <div className="msg-meta">{T(lang, 'sender_' + m.from)} · {window.ATLAS.timeAgo(m.at, lang)}</div>
            </div>
          ))}
        </div>
        <div className="chat-input">
          <input className="input" placeholder={T(lang, 'ad_chat_ph')} value={msg}
            onChange={e => setMsg(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') send(); }} />
          <button className="btn btn-primary btn-sm" onClick={send}><Ic name="send" size={15} /></button>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Overview ---------------- */
function Overview({ lang, requests, setView, setSelId }) {
  const recent = requests.slice(0, 6);
  const open = (id) => { setSelId(id); setView('requests'); };
  return (
    <div>
      <StatCards lang={lang} requests={requests} />
      <div className="overview-grid">
        <div className="panel">
          <h3>{T(lang, 'ad_requests_title')}</h3>
          {recent.map(r => (
            <div className="mini-req" key={r.id} onClick={() => open(r.id)}>
              <StatusBadge status={r.status} lang={lang} />
              <div className="grow">
                <div className="mr-name">{r.name} <span className="faint" style={{ fontWeight: 400 }}>· {svcLabel(lang, r.service)}</span></div>
                <div className="mr-sub">{r.pickup} → {r.dropoff}</div>
              </div>
              <div className="ri-id faint">{window.ATLAS.fmtDate(r.date, lang)}</div>
            </div>
          ))}
        </div>
        <div className="panel">
          <h3>{T(lang, 'ad_drivers_title')}</h3>
          {window.ATLAS.drivers.slice(0, 4).map(d => (
            <div className="mini-req" key={d.id}>
              <div className="driver-av" style={{ width: 40, height: 40, fontSize: '1.05rem' }}>{d.name[0]}</div>
              <div className="grow">
                <div className="mr-name">{d.name}</div>
                <div className="mr-sub">{d.zone} · <span className="rating"><Ic name="star" size={12} />{d.rating}</span></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------------- Fleet (admin) ---------------- */
function FleetAdmin({ lang, requests }) {
  const busy = new Set(requests.filter(r => ['confirmed', 'progress'].includes(r.status) && r.vehicle).map(r => r.vehicle));
  const maint = new Set(['bus']);
  return (
    <div className="admin-fleet-grid">
      {window.ATLAS.vehicles.map(v => {
        const state = maint.has(v.id) ? 'maint' : busy.has(v.id) ? 'busy' : 'available';
        return (
          <div className="afleet-card" key={v.id}>
            <div className="veh-photo"><VehicleSlot vehId={v.id} lang={lang} height={150} radius={0} /></div>
            <div className="af-body">
              <h3>{vehLabel(lang, v.id)}</h3>
              <div className="af-meta">{v.seats} {T(lang, 'fleet_seats')} · {window.ATLAS.fmtMoney(v.priceDay, lang, 'MAD')}{T(lang, 'fleet_perday')}</div>
              <div className="af-foot">
                <span className={'avail ' + state}><span className="dot" style={{ background: 'currentColor' }}></span>{T(lang, 'ad_' + state)}</span>
                <span className="veh-class" style={{ position: 'static' }}>{v.cls}</span>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ---------------- Drivers (admin) ---------------- */
function DriversAdmin({ lang }) {
  return (
    <div className="drivers-grid">
      {window.ATLAS.drivers.map(d => (
        <div className="driver-card" key={d.id}>
          <div className="driver-av">{d.name.split(' ').map(w => w[0]).slice(0, 2).join('')}</div>
          <div className="grow">
            <h3>{d.name}</h3>
            <div className="dr-zone"><Ic name="pin" size={13} /> {d.zone}</div>
            <div className="dr-stats">
              <span className="rating"><Ic name="star" size={13} />{d.rating}</span>
              <span>{d.trips} {T(lang, 'ad_trips')}</span>
            </div>
            <div className="dr-langs">
              {d.langs.map(l => (
                <span className="lang-chip flag-chip" key={l}>
                  {window.Flag ? <Flag code={l} size={18} /> : null}{l}
                </span>
              ))}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------------- Generic collection CRUD ---------------- */
function itemTitle(key, item, lang) {
  if (!item) return '';
  if (item.name) return item.name;
  if (item.t) return window.ATLAS.pick(item.t, lang);
  if (item.id && key === 'vehicles') return vehLabel(lang, item.id);
  if (item.id && key === 'services') return svcLabel(lang, item.id);
  return item.id || 'item';
}

function blankItem(key) {
  const n = Date.now().toString(36).slice(-5);
  if (key === 'services') return { id: 'service-' + n, icon: '✦', t: { fr: 'Nouveau service', en: 'New service', ar: 'خدمة جديدة' }, d: { fr: 'Description du service.', en: 'Service description.', ar: 'وصف الخدمة.' } };
  if (key === 'vehicles') return { id: 'vehicle-' + n, seats: 4, bags: 4, cls: 'standard', priceDay: 900, priceKm: 9, t: { fr: 'Nouveau vehicule', en: 'New vehicle', ar: 'مركبة جديدة' }, d: { fr: 'Modele ou similaire', en: 'Model or similar', ar: 'نموذج أو مشابه' } };
  if (key === 'drivers') return { id: 'd-' + n, name: 'Nouveau chauffeur', langs: ['FR', 'AR'], rating: 4.8, trips: 0, zone: 'Marrakech' };
  if (key === 'events') return { id: 'ev-' + n, date: new Date().toISOString().slice(0, 10), city: 'Marrakech', img: 'ev-marathon', t: { fr: 'Nouvel evenement', en: 'New event', ar: 'فعالية جديدة' }, d: { fr: 'Description evenement.', en: 'Event description.', ar: 'وصف الفعالية.' } };
  if (key === 'news') return { id: 'nw-' + n, date: new Date().toISOString().slice(0, 10), img: 'nw-app', tag: { fr: 'Info', en: 'Info', ar: 'خبر' }, t: { fr: 'Nouvelle actualite', en: 'New article', ar: 'خبر جديد' }, d: { fr: 'Description actualite.', en: 'Article description.', ar: 'وصف الخبر.' } };
  return { id: 'item-' + n };
}

function CollectionAdmin({ lang, contentKey }) {
  const [items, setItems] = useState(() => JSON.parse(JSON.stringify(window.ATLAS[contentKey] || [])));
  const [selected, setSelected] = useState(0);
  const [draft, setDraft] = useState('');
  const [msg, setMsg] = useState('');

  useEffect(() => {
    const next = JSON.parse(JSON.stringify(window.ATLAS[contentKey] || []));
    setItems(next); setSelected(0); setDraft(JSON.stringify(next[0] || blankItem(contentKey), null, 2)); setMsg('');
  }, [contentKey]);
  useEffect(() => { setDraft(JSON.stringify(items[selected] || blankItem(contentKey), null, 2)); }, [selected]);

  const persist = (next) => {
    setItems(next);
    window.ATLAS.api.saveContent(contentKey, next)
      .then(() => { window.ATLAS[contentKey] = next; setMsg(adminText(lang, 'saved')); })
      .catch(() => setMsg('Erreur sauvegarde'));
  };
  const saveOne = () => {
    let value;
    try { value = JSON.parse(draft); } catch (e) { setMsg(adminText(lang, 'invalid')); return; }
    const next = items.slice();
    next[selected] = value;
    persist(next);
  };
  const add = () => {
    const next = items.concat([blankItem(contentKey)]);
    setItems(next); setSelected(next.length - 1); setDraft(JSON.stringify(next[next.length - 1], null, 2)); persist(next);
  };
  const duplicate = () => {
    const copy = JSON.parse(JSON.stringify(items[selected] || blankItem(contentKey)));
    copy.id = (copy.id || contentKey) + '-copy-' + Date.now().toString(36).slice(-4);
    const next = items.concat([copy]);
    setItems(next); setSelected(next.length - 1); setDraft(JSON.stringify(copy, null, 2)); persist(next);
  };
  const remove = () => {
    const next = items.filter((_, i) => i !== selected);
    const nextIndex = Math.max(0, selected - 1);
    setItems(next); setSelected(nextIndex); setDraft(JSON.stringify(next[nextIndex] || blankItem(contentKey), null, 2)); persist(next);
  };

  return (
    <div className="crud-layout">
      <div className="panel crud-list">
        <div className="crud-head"><h3>{adminText(lang, contentKey)}</h3><button className="btn btn-primary btn-sm" onClick={add}><Ic name="plus" size={14} />{adminText(lang, 'add')}</button></div>
        {items.map((item, i) => (
          <button key={(item.id || i) + '-' + i} className={'crud-item' + (selected === i ? ' on' : '')} onClick={() => setSelected(i)}>
            <span>{itemTitle(contentKey, item, lang)}</span><small>{item.id || i}</small>
          </button>
        ))}
      </div>
      <div className="panel crud-editor">
        <div className="content-editor-head">
          <div><h3>{itemTitle(contentKey, items[selected], lang)}</h3><p className="faint">{contentKey} · JSON structure</p></div>
          <div className="row gap-12">
            <button className="btn btn-ghost btn-sm" onClick={duplicate}>{adminText(lang, 'duplicate')}</button>
            <button className="btn btn-ghost btn-sm danger" onClick={remove}>{adminText(lang, 'remove')}</button>
          </div>
        </div>
        <textarea className="input json-editor" value={draft} onChange={e => setDraft(e.target.value)} />
        <div className="content-actions"><span className="faint">{msg || 'JSON valide requis.'}</span><button className="btn btn-primary" onClick={saveOne}><Ic name="check" size={15} />{adminText(lang, 'save')}</button></div>
      </div>
    </div>
  );
}

function ConfigAdmin({ lang }) {
  const [form, setForm] = useState(Object.assign({}, window.ATLAS.config));
  const [msg, setMsg] = useState('');
  const set = (k, v) => setForm(f => Object.assign({}, f, { [k]: v }));
  const save = () => window.ATLAS.api.saveContent('config', form).then(() => { window.ATLAS.config = form; setMsg(adminText(lang, 'saved')); }).catch(() => setMsg('Erreur'));
  return (
    <div className="panel config-admin">
      <h3>{adminText(lang, 'config')}</h3>
      <div className="form-grid" style={{ marginTop: 14 }}>
        {['phone', 'whatsapp', 'email', 'address'].map(k => <div className="field" key={k}><label>{adminText(lang, k) || k}</label><input className="input" value={form[k] || ''} onChange={e => set(k, e.target.value)} /></div>)}
      </div>
      <div className="content-actions"><span className="faint">{msg}</span><button className="btn btn-primary" onClick={save}><Ic name="check" size={15} />{adminText(lang, 'save')}</button></div>
    </div>
  );
}

function UsersAdmin({ lang }) {
  const blank = { name: '', email: '', phone: '', role: 'client', password: '' };
  const [users, setUsers] = useState([]);
  const [form, setForm] = useState(blank);
  const [msg, setMsg] = useState('');
  const load = () => window.ATLAS.api.fetchUsers().then(setUsers).catch(() => setMsg('Erreur utilisateurs'));
  useEffect(() => { load(); }, []);
  const set = (k, v) => setForm(f => Object.assign({}, f, { [k]: v }));
  const edit = (u) => setForm({ id: u.id, name: u.name || '', email: u.email || '', phone: u.phone || '', role: u.role || 'client', password: '' });
  const save = () => {
    const payload = Object.assign({}, form);
    if (!payload.password) delete payload.password;
    const op = payload.id ? window.ATLAS.api.updateUser(payload.id, payload) : window.ATLAS.api.createUser(payload);
    op.then(() => { setForm(blank); setMsg(adminText(lang, 'saved')); load(); }).catch(() => setMsg('Erreur sauvegarde'));
  };
  const remove = (id) => window.ATLAS.api.deleteUser(id).then(load).catch(() => setMsg('Erreur suppression'));
  return (
    <div className="crud-layout">
      <div className="panel"><h3>{adminText(lang, 'platformUsers')}</h3>{users.map(u => <div className="user-row" key={u.id}><button onClick={() => edit(u)}><strong>{u.name}</strong><span>{u.email}</span></button><span className="badge pending"><span className="dot"></span>{u.role}</span><button className="icon-danger" onClick={() => remove(u.id)}><Ic name="x" size={15} /></button></div>)}</div>
      <div className="panel"><h3>{form.id ? adminText(lang, 'edit') : adminText(lang, 'add')}</h3><div className="form-grid" style={{ marginTop: 14 }}>
        <div className="field"><label>Nom</label><input className="input" value={form.name} onChange={e => set('name', e.target.value)} /></div>
        <div className="field"><label>Email</label><input className="input" type="email" value={form.email} onChange={e => set('email', e.target.value)} /></div>
        <div className="field"><label>Telephone</label><input className="input" value={form.phone} onChange={e => set('phone', e.target.value)} /></div>
        <div className="field"><label>Role</label><select className="select" value={form.role} onChange={e => set('role', e.target.value)}><option value="client">client</option><option value="agent">agent</option><option value="admin">admin</option></select></div>
        <div className="field full"><label>Mot de passe</label><input className="input" type="password" value={form.password} onChange={e => set('password', e.target.value)} placeholder="••••••••" /><span className="faint" style={{ fontSize: '.78rem' }}>{adminText(lang, 'passwordHint')}</span></div>
      </div><div className="content-actions"><span className="faint">{msg}</span><div className="row gap-12"><button className="btn btn-ghost" onClick={() => setForm(blank)}>{adminText(lang, 'cancel')}</button><button className="btn btn-primary" onClick={save}><Ic name="check" size={15} />{adminText(lang, 'save')}</button></div></div></div>
    </div>
  );
}

/* ---------------- Admin login ---------------- */
function AdminLogin({ lang, onDone }) {
  const [username, setUsername] = useState('admin');
  const [password, setPassword] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const submit = () => {
    setBusy(true); setErr('');
    window.ATLAS.api.loginAdmin(username, password)
      .then(() => { setBusy(false); onDone(); })
      .catch(() => { setBusy(false); setErr(lang === 'ar' ? 'بيانات الدخول غير صحيحة' : 'Identifiants admin incorrects'); });
  };
  return (
    <div className="admin-shell" style={{ display: 'grid', placeItems: 'center', minHeight: '100vh', padding: 20 }}>
      <div className="panel" style={{ width: 'min(460px, 100%)' }}>
        <div className="side-brand" style={{ marginBottom: 22 }}><Logo lang={lang} href="/" /></div>
        <h1 className="display" style={{ marginBottom: 8 }}>{lang === 'ar' ? 'دخول الإدارة' : 'Dashboard admin sécurisé'}</h1>
        <p className="faint" style={{ marginBottom: 18 }}>{lang === 'ar' ? 'أدخل بيانات المدير للوصول إلى الطلبات والمحتوى.' : 'Connectez-vous pour gérer les demandes et le contenu dynamique.'}</p>
        <div className="field"><label>Login</label><input className="input" value={username} onChange={e => setUsername(e.target.value)} /></div>
        <div className="field" style={{ marginTop: 12 }}><label>Mot de passe</label><input className="input" type="password" value={password} onChange={e => setPassword(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') submit(); }} autoFocus /></div>
        {err && <div className="form-err" style={{ marginTop: 12 }}>{err}</div>}
        <button className="btn btn-primary" style={{ width: '100%', marginTop: 16 }} onClick={submit} disabled={busy}>{busy ? '...' : 'Entrer'}</button>
        <div className="faint" style={{ marginTop: 12, fontSize: '.82rem' }}>{lang === 'ar' ? 'بيانات الدخول تأتي من متغيرات البيئة.' : 'Les identifiants sont fournis par les variables d’environnement.'}</div>
      </div>
    </div>
  );
}

/* ---------------- Content editor ---------------- */
function ContentAdmin({ lang }) {
  const meta = {
    config: ['Coordonnees', 'telephone, email, adresse'],
    services: ['Services', 'cartes de prestations'],
    vehicles: ['Flotte', 'prix et capacites'],
    drivers: ['Chauffeurs', 'profils equipe'],
    cities: ['Villes', 'suggestions formulaire'],
    destinations: ['Destinations', 'section accueil'],
    events: ['Evenements', 'agenda public'],
    news: ['Actualites', 'articles accueil'],
    seo: ['SEO', 'titre et description'],
  };
  const keys = Object.keys(meta);
  const [key, setKey] = useState('config');
  const [draft, setDraft] = useState('');
  const [msg, setMsg] = useState('');
  useEffect(() => {
    const val = key === 'seo' ? (window.ATLAS.seo || {}) : window.ATLAS[key];
    setDraft(JSON.stringify(val, null, 2));
    setMsg('');
  }, [key]);
  const save = () => {
    setMsg('');
    let value;
    try { value = JSON.parse(draft); } catch (e) { setMsg('JSON invalide'); return; }
    window.ATLAS.api.saveContent(key, value)
      .then(() => setMsg('Contenu sauvegarde'))
      .catch(() => setMsg('Sauvegarde impossible'));
  };
  return (
    <div className="content-admin">
      <div className="panel content-menu">
        {keys.map(k => <button key={k} className={key === k ? 'on' : ''} onClick={() => setKey(k)}><span>{meta[k][0]}</span><small>{k}</small></button>)}
      </div>
      <div className="panel">
        <div className="content-editor-head">
          <div>
            <h3>{meta[key][0]}</h3>
            <p className="faint" style={{ marginTop: 4 }}>{meta[key][1]} · {lang === 'ar' ? 'محفوظ في SQLite محلياً' : 'sauvegarde locale SQLite'}</p>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => window.ATLAS.api.fetchContent().then(() => {
            const val = key === 'seo' ? (window.ATLAS.seo || {}) : window.ATLAS[key];
            setDraft(JSON.stringify(val, null, 2));
            setMsg('Recharge');
          })}>Recharger</button>
        </div>
        <textarea className="input json-editor" value={draft} onChange={e => setDraft(e.target.value)} />
        <div className="content-actions">
          <span className="faint">{msg || 'JSON valide requis avant sauvegarde.'}</span>
          <button className="btn btn-primary" onClick={save}><Ic name="check" size={15} />Sauvegarder</button>
        </div>
      </div>
    </div>
  );
}

/* ---------------- App ---------------- */
function AdminApp() {
  const [lang, setLang] = useLang();
  const [requests, setRequests] = useState(window.ATLAS.getRequests());
  const [view, setView] = useState('overview');
  const [selId, setSelId] = useState(null);
  const [search, setSearch] = useState('');
  const [sideOpen, setSideOpen] = useState(false);
  const [authed, setAuthed] = useState(window.ATLAS.api.isAdminAuthed());

  useEffect(() => {
    const refresh = () => setRequests(window.ATLAS.getRequests());
    const unsub = window.ATLAS.subscribe(refresh);
    return unsub;
  }, []);
  useEffect(() => {
    const h = () => setAuthed(window.ATLAS.api.isAdminAuthed());
    window.addEventListener('atlas:admin', h);
    return () => window.removeEventListener('atlas:admin', h);
  }, []);
  useEffect(() => {
    if (!authed) return;
    let alive = true;
    const refresh = () => window.ATLAS.api.fetchRequests(true).then(list => { if (alive) setRequests(list); }).catch(() => null);
    refresh();
    const timer = setInterval(refresh, 10000);
    return () => { alive = false; clearInterval(timer); };
  }, [authed]);

  if (!authed) return <AdminLogin lang={lang} onDone={() => setAuthed(true)} />;

  const counts = { pending: requests.filter(r => r.status === 'pending').length };
  const titleMap = { overview: T(lang, 'ad_nav_overview'), requests: T(lang, 'ad_requests_title'), fleet: T(lang, 'ad_fleet_title'), drivers: T(lang, 'ad_drivers_title'), config: adminText(lang, 'config'), services: adminText(lang, 'services'), events: adminText(lang, 'events'), news: adminText(lang, 'news'), users: adminText(lang, 'users'), content: adminText(lang, 'content') };

  return (
    <div className={'admin-shell' + (sideOpen ? ' side-open' : '')}>
      <div className="side-backdrop" onClick={() => setSideOpen(false)}></div>
      <Sidebar lang={lang} setLang={setLang} view={view} setView={setView} counts={counts} onClose={() => setSideOpen(false)} />
      <div className="admin-main">
        <div className="admin-top">
          <div className="row gap-16">
            <button className="side-toggle" onClick={() => setSideOpen(o => !o)}><Ic name="list" size={20} /></button>
            <h1 className="display">{titleMap[view]}</h1>
          </div>
          <div className="row gap-16">
            <div className="admin-search">
              <Ic name="search" size={16} />
              <input placeholder={T(lang, 'ad_search')} value={search} onChange={e => { setSearch(e.target.value); if (view !== 'requests') setView('requests'); }} />
            </div>
            <button className="btn btn-ghost btn-sm" onClick={() => { window.ATLAS.api.logoutAdmin(); setAuthed(false); }}><Ic name="x" size={15} />Logout</button>
          </div>
        </div>
        <div className="admin-body">
          {view === 'overview' && <Overview lang={lang} requests={requests} setView={setView} setSelId={setSelId} />}
          {view === 'requests' && <RequestsView lang={lang} requests={requests} selId={selId} setSelId={setSelId} search={search} />}
          {view === 'config' && <ConfigAdmin lang={lang} />}
          {view === 'services' && <CollectionAdmin lang={lang} contentKey="services" />}
          {view === 'events' && <CollectionAdmin lang={lang} contentKey="events" />}
          {view === 'news' && <CollectionAdmin lang={lang} contentKey="news" />}
          {view === 'fleet' && <CollectionAdmin lang={lang} contentKey="vehicles" />}
          {view === 'drivers' && <CollectionAdmin lang={lang} contentKey="drivers" />}
          {view === 'users' && <UsersAdmin lang={lang} />}
          {view === 'content' && <ContentAdmin lang={lang} />}
        </div>
      </div>
    </div>
  );
}

window.ATLAS.ready.then(() => ReactDOM.createRoot(document.getElementById('root')).render(<AdminApp />));
