/* ============================================================
   GoToMorocco — client multi-page app
   ============================================================ */

const ACCENTS = {
  sand:      { a: 'oklch(0.81 0.078 80)', d: 'oklch(0.72 0.092 72)', on: 'oklch(0.18 0.02 70)' },
  terracotta:{ a: 'oklch(0.68 0.12 46)',  d: 'oklch(0.60 0.13 42)',  on: 'oklch(0.98 0.01 70)' },
  olive:     { a: 'oklch(0.76 0.07 120)', d: 'oklch(0.68 0.08 122)', on: 'oklch(0.18 0.02 120)' },
};
function applyAccent(name) {
  const a = ACCENTS[name] || ACCENTS.sand;
  const r = document.documentElement.style;
  r.setProperty('--accent', a.a); r.setProperty('--accent-deep', a.d); r.setProperty('--on-accent', a.on);
}
function pickText(obj, lang, fallback) {
  return window.ATLAS.pick && obj ? (window.ATLAS.pick(obj, lang) || fallback) : fallback;
}
function serviceTitle(lang, s) { return pickText(s.t, lang, T(lang, 'svc_' + s.id + '_t')); }
function serviceDesc(lang, s) { return pickText(s.d, lang, T(lang, 'svc_' + s.id + '_d')); }
function vehicleTitle(lang, v) { return pickText(v.t, lang, T(lang, 'veh_' + v.id + '_t')); }
function vehicleDesc(lang, v) { return pickText(v.d, lang, T(lang, 'veh_' + v.id + '_d')); }

/* ---------------- router ---------------- */
function useRoute() {
  const parse = () => (window.location.hash.replace(/^#\/?/, '') || 'home').split('?')[0];
  const [route, setRoute] = useState(parse());
  useEffect(() => {
    const h = () => { setRoute(parse()); window.scrollTo(0, 0); };
    window.addEventListener('hashchange', h);
    return () => window.removeEventListener('hashchange', h);
  }, []);
  const navigate = (to) => { window.location.hash = '/' + to; };
  return [route, navigate];
}

/* ---------------- Header ---------------- */
function Header({ lang, setLang, route, navigate, user, onLogin }) {
  const [menu, setMenu] = useState(false);
  const [acct, setAcct] = useState(false);
  const links = [
    { id: 'home', label: 'nav_home' },
    { id: 'services', label: 'nav_services' },
    { id: 'fleet', label: 'nav_fleet' },
    { id: 'events', label: 'nav_events' },
    { id: 'news', label: 'nav_news' },
    { id: 'track', label: 'nav_track' },
  ];
  const go = (id) => { navigate(id); setMenu(false); };
  return (
    <header className="site-header">
      <div className="wrap">
        <Logo lang={lang} />

        <nav className="site-nav">
          {links.map(l => (
            <a key={l.id} href={'#/' + l.id} className={route === l.id ? 'active' : ''}>{T(lang, l.label)}</a>
          ))}
        </nav>

        <div className="header-actions">
          <a className="admin-link" href="/admin"><Ic name="grid" size={15} />{T(lang, 'nav_admin')}</a>
          <CurrencySwitch lang={lang} />
          <LangSwitch lang={lang} setLang={setLang} />
          {user ? (
            <div className="acct-menu">
              <button className="acct-btn" onClick={() => setAcct(a => !a)}>
                <span className="acct-av">{user.name.split(' ').map(w => w[0]).slice(0, 2).join('')}</span>
                <span className="acct-name">{user.name.split(' ')[0]}</span>
              </button>
              {acct && (
                <div className="acct-drop" onMouseLeave={() => setAcct(false)}>
                  <button onClick={() => { navigate('account'); setAcct(false); }}><Ic name="list" size={15} />{T(lang, 'ac_my_requests')}</button>
                  <button onClick={() => { window.ATLAS.logout(); setAcct(false); }}><Ic name="x" size={15} />{T(lang, 'ac_logout')}</button>
                </div>
              )}
            </div>
          ) : (
            <button className="btn btn-ghost btn-sm acct-login" onClick={() => onLogin('login')}><Ic name="user" size={15} />{T(lang, 'ac_login')}</button>
          )}
          <button className="btn btn-primary btn-sm book-btn" onClick={() => navigate('book')}>{T(lang, 'nav_book')}</button>
          <button className="nav-toggle" onClick={() => setMenu(m => !m)} aria-label="menu"><Ic name="list" size={20} /></button>
        </div>
      </div>

      {menu && (
        <div className="mobile-menu">
          {links.map(l => <a key={l.id} href={'#/' + l.id} onClick={() => setMenu(false)} className={route === l.id ? 'active' : ''}>{T(lang, l.label)}</a>)}
          <a href="#/book" onClick={() => setMenu(false)}>{T(lang, 'nav_book')}</a>
          {user
            ? <a href="#/account" onClick={() => setMenu(false)}>{T(lang, 'ac_my_requests')}</a>
            : <button onClick={() => { onLogin('login'); setMenu(false); }}>{T(lang, 'ac_login')}</button>}
          <a href="/admin">{T(lang, 'nav_admin')}</a>
        </div>
      )}
    </header>
  );
}

/* ---------------- Hero ---------------- */
function Hero({ lang, variant, navigate }) {
  const titleKey = variant === 'split' ? 'hero_title_b' : variant === 'minimal' ? 'hero_title_c' : 'hero_title_a';
  const stats = [
    { end: 14, suffix: '', lbl: T(lang, 'stat_years') }, { end: 40, suffix: '+', lbl: T(lang, 'stat_vehicles') },
    { end: 25, suffix: '', lbl: T(lang, 'stat_drivers') }, { end: 10, suffix: '', lbl: T(lang, 'stat_cities') },
  ];
  const content = (
    <div className="hero-content reveal">
      <span className="eyebrow">{T(lang, 'hero_eyebrow')}</span>
      <h1 className="hero-title display">{T(lang, titleKey)}</h1>
      <p className="hero-sub">{T(lang, 'hero_sub')}</p>
      <div className="hero-cta">
        <button className="btn btn-primary btn-lg" onClick={() => navigate('book')}>{T(lang, 'hero_cta1')}</button>
        <button className="btn btn-ghost btn-lg" onClick={() => navigate('fleet')}>{T(lang, 'hero_cta2')}</button>
      </div>
      <div className="hero-trust">
        <div className="trust-pill">
          <TripAdvisorMark small />
          <RatingBubbles value={window.ATLAS.taRating} size={13} />
          <span className="tp-score">{window.ATLAS.taRating}</span>
        </div>
        <span className="tp-txt">{window.ATLAS.taCount.toLocaleString(lang === 'ar' ? 'ar-MA' : 'fr-FR')} {T(lang, 'ta_reviews')} · {T(lang, 'ta_excellent')}</span>
      </div>
      <div className="hero-stats">
        {stats.map((s, i) => (
          <div className="stat" key={i}><div className="stat-num display"><CountUp end={s.end} suffix={s.suffix} /></div><div className="stat-lbl">{s.lbl}</div></div>
        ))}
      </div>
    </div>
  );
  if (variant === 'split') {
    return (
      <section className="hero split">
        <div className="wrap"><div className="hero-grid">
          <div className="hero-inner">{content}</div>
          <div className="hero-photo zellij-frame">
            <span className="zc tl"></span><span className="zc tr"></span><span className="zc bl"></span><span className="zc br"></span>
            {React.createElement('image-slot', { id: 'hero-split', src: window.ATLAS.photo('hero-split'), placeholder: 'Mercedes / désert', shape: 'rounded', radius: '24' })}
          </div>
        </div></div>
      </section>
    );
  }
  return (
    <section className={'hero ' + variant}>
      <div className="hero-bg">
        {React.createElement('image-slot', { id: 'hero-bg', src: window.ATLAS.photo('hero-bg'), placeholder: 'Photo héro · route / désert marocain', shape: 'rect' })}
      </div>
      <div className="hero-scrim"></div>
      <div className="zellij-ribbon left"></div>
      <div className="wrap"><div className="hero-inner">{content}</div></div>
    </section>
  );
}

/* ---------------- Services ---------------- */
function Services({ lang, navigate, goBook, compact }) {
  return (
    <section className="section zellij-bg" id="services">
      <div className="wrap">
        <div className="sec-head">
          <span className="eyebrow">{T(lang, 'svc_eyebrow')}</span>
          <h2 className="sec-title display">{T(lang, 'svc_title')}</h2>
          <p className="sec-sub">{T(lang, 'svc_sub')}</p>
        </div>
        <div className="svc-grid">
          {window.ATLAS.services.map(s => (
            <button className="svc-card" key={s.id} onClick={() => goBook(s.id, null)}>
              <div className="svc-icon">{s.icon}</div>
              <h3>{serviceTitle(lang, s)}</h3>
              <p>{serviceDesc(lang, s)}</p>
              <span className="svc-req">{T(lang, 'svc_request')} <Ic name="arrow" size={15} /></span>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Fleet ---------------- */
function Fleet({ lang, goBook }) {
  const [filter, setFilter] = useState('all');
  const cats = [
    { id: 'all' }, { id: 'small', match: ['berline', 'luxury'] },
    { id: 'group', match: ['van', 'minibus', 'bus'] }, { id: 'suv', match: ['suv'] },
  ];
  const catLabels = {
    fr: { all: 'Tous', small: 'Berlines & luxe', group: 'Groupes', suv: '4x4' },
    en: { all: 'All', small: 'Sedans & luxury', group: 'Groups', suv: '4x4' },
    ar: { all: 'الكل', small: 'سيدان وفاخرة', group: 'مجموعات', suv: 'دفع رباعي' },
  }[lang] || {};
  const list = window.ATLAS.vehicles.filter(v => {
    if (filter === 'all') return true;
    const c = cats.find(x => x.id === filter);
    return c && c.match && c.match.includes(v.id);
  });
  return (
    <section className="section" id="fleet">
      <div className="wrap">
        <div className="sec-head">
          <span className="eyebrow">{T(lang, 'fleet_eyebrow')}</span>
          <h2 className="sec-title display">{T(lang, 'fleet_title')}</h2>
          <p className="sec-sub">{T(lang, 'fleet_sub')}</p>
        </div>
        <div className="fleet-tabs">
          {cats.map(c => (
            <button key={c.id} className={'fleet-tab' + (filter === c.id ? ' active' : '')} onClick={() => setFilter(c.id)}>{catLabels[c.id]}</button>
          ))}
        </div>
        <div className="fleet-grid">
          {list.map(v => (
            <div className="veh-card" key={v.id}>
              <div className="veh-photo">
                <span className="veh-class">{v.cls}</span>
                <VehicleSlot vehId={v.id} lang={lang} height={190} />
              </div>
              <div className="veh-body">
                <h3>{vehicleTitle(lang, v)}</h3>
                <div className="veh-desc">{vehicleDesc(lang, v)}</div>
                <div className="veh-specs">
                  <span className="spec"><Ic name="users" size={16} />{v.seats} {T(lang, 'fleet_seats')}</span>
                  <span className="spec"><Ic name="bag" size={16} />{v.bags} {T(lang, 'fleet_bags')}</span>
                </div>
                <div className="veh-foot">
                  <div className="veh-price">
                    <span className="from">{T(lang, 'fleet_from')}</span>
                    <span className="amt">{window.ATLAS.fmtMoney(v.priceDay, lang)}</span>
                    <span className="per"> {T(lang, 'fleet_perday')}</span>
                  </div>
                  <button className="btn btn-dark btn-sm" onClick={() => goBook(null, v.id)}>{T(lang, 'fleet_select')}</button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Features strip ---------------- */
function Features({ lang }) {
  const items = [
    { ic: 'clock', t: 'feat_resp', d: 'feat_resp_d' },
    { ic: 'users', t: 'feat_drivers', d: 'feat_drivers_d' },
    { ic: 'check', t: 'feat_safe', d: 'feat_safe_d' },
  ];
  return (
    <section className="section" style={{ paddingTop: 64, paddingBottom: 0 }}>
      <div className="wrap">
        <div className="features">
          {items.map((f, i) => (
            <div className={'feature js-reveal d' + i} key={f.t}>
              <div className="f-ic"><Ic name={f.ic} size={22} /></div>
              <div><h4>{T(lang, f.t)}</h4><p>{T(lang, f.d)}</p></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Languages strip ---------------- */
function Languages({ lang }) {
  const codes = ['IT', 'ES', 'EN', 'FR', 'AR', 'DE'];
  const counts = {};
  window.ATLAS.drivers.forEach(d => d.langs.forEach(l => { counts[l] = (counts[l] || 0) + 1; }));
  return (
    <section className="section langs-section">
      <div className="wrap">
        <div className="langs-card js-reveal zellij-frame">
          <span className="zc tl"></span><span className="zc tr"></span><span className="zc bl"></span><span className="zc br"></span>
          <div className="langs-text">
            <span className="eyebrow">{T(lang, 'lang_eyebrow')}</span>
            <h2 className="sec-title display">{T(lang, 'lang_title')}</h2>
            <p className="sec-sub">{T(lang, 'lang_sub')}</p>
          </div>
          <div className="langs-flags">
            {codes.map((c, i) => (
              <div className={'lang-flag js-reveal d' + (i % 4)} key={c}>
                <Flag code={c} size={42} />
                <span className="lf-name">{LANG_NAMES[c][lang] || LANG_NAMES[c].fr}</span>
                {counts[c] ? <span className="lf-count">{counts[c]} {T(lang, 'lang_guides')}</span> : null}
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Destinations ---------------- */
function Destinations({ lang }) {
  return (
    <section className="section">
      <div className="wrap">
        <div className="sec-head js-reveal">
          <span className="eyebrow">{T(lang, 'dest_eyebrow')}</span>
          <h2 className="sec-title display">{T(lang, 'dest_title')}</h2>
        </div>
        <div className="dest-grid">
          {window.ATLAS.destinations.map((d, i) => (
            <div className={'dest-card js-reveal d' + (i % 4)} key={d.id}>
              {React.createElement('image-slot', { id: 'dest-' + d.id, src: window.ATLAS.photo('dest-' + d.id), placeholder: d[lang] || d.fr, shape: 'rect' })}
              <div className="dest-scrim"></div>
              <span className="dest-pin"><Ic name="pin" size={16} /></span>
              <span className="dest-name">{d[lang] || d.fr}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Reviews (TripAdvisor) ---------------- */
function Reviews({ lang }) {
  const reviews = window.ATLAS.getReviews(lang);
  return (
    <section className="section zellij-bg" id="reviews">
      <div className="wrap">
        <div className="reviews-head">
          <div className="sec-head js-reveal" style={{ margin: 0 }}>
            <span className="eyebrow">{T(lang, 'rv_eyebrow')}</span>
            <h2 className="sec-title display">{T(lang, 'rv_title')}</h2>
          </div>
          <div className="reviews-aggregate js-reveal d2">
            <div className="agg-score display">{window.ATLAS.taRating}</div>
            <div className="agg-meta">
              <TripAdvisorMark />
              <RatingBubbles value={window.ATLAS.taRating} size={15} />
              <span className="agg-count">{window.ATLAS.taCount.toLocaleString(lang === 'ar' ? 'ar-MA' : 'fr-FR')} {T(lang, 'ta_reviews')}</span>
              <span className="choice-badge"><Ic name="star" size={14} />{T(lang, 'ta_choice')}</span>
            </div>
          </div>
        </div>
        <div className="reviews-grid">
          {reviews.map((r, i) => (
            <div className={'review-card js-reveal d' + i} key={i}>
              <div className="rc-top">
                <div className="rc-av">{r.initials}</div>
                <div><div className="rc-name">{r.name}</div><div className="rc-place">{r.place}</div></div>
              </div>
              <RatingBubbles value={r.rating} size={14} />
              <p className="rc-text" style={{ marginTop: 12 }}>“{r.text}”</p>
              <div className="rc-foot">
                <span className="rc-when">{r.when}</span>
                <TripAdvisorMark small />
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- CTA band ---------------- */
function CTABand({ lang, navigate }) {
  const C = window.ATLAS.config;
  return (
    <section className="cta-band zellij-bg">
      <div className="cta-glow"></div>
      <div className="wrap">
        <div className="cta-inner js-reveal">
          <span className="eyebrow">{T(lang, 'cta_eyebrow')}</span>
          <h2 className="cta-title display">{T(lang, 'cta_title')}</h2>
          <p className="cta-sub">{T(lang, 'cta_sub')}</p>
          <div className="cta-actions">
            <button className="btn btn-primary btn-lg" onClick={() => navigate('book')}>{T(lang, 'cta_btn')} <Ic name="arrow" size={16} /></button>
            <a className="btn btn-wa btn-lg" href={window.ATLAS.waLink(lang)} target="_blank" rel="noopener"><Ic name="chat" size={16} />{T(lang, 'cta_wa')}</a>
            <a className="btn btn-ghost btn-lg" href={'tel:' + C.phone.replace(/\s/g, '')}><Ic name="phone" size={16} />{T(lang, 'cta_call')}</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Personnel / corporate transport ---------------- */
function Personnel({ lang, goBook }) {
  const feats = [
    { ic: 'cal', t: 'pers_f1', d: 'pers_f1d' },
    { ic: 'check', t: 'pers_f2', d: 'pers_f2d' },
    { ic: 'money', t: 'pers_f3', d: 'pers_f3d' },
  ];
  return (
    <section className="section pers-section zellij-bg" id="personnel">
      <div className="wrap">
        <div className="pers-grid">
          <div className="pers-photo zellij-frame js-reveal">
            <span className="zc tl"></span><span className="zc tr"></span><span className="zc bl"></span><span className="zc br"></span>
            {React.createElement('image-slot', { id: 'pers-photo', src: window.ATLAS.photo('pers-photo'), placeholder: T(lang, 'pers_photo'), shape: 'rounded', radius: '20' })}
            <span className="pers-badge"><Ic name="users" size={16} />{T(lang, 'svc_personnel_t')}</span>
          </div>
          <div className="pers-body js-reveal d2">
            <span className="eyebrow">{T(lang, 'pers_eyebrow')}</span>
            <h2 className="sec-title display">{T(lang, 'pers_title')}</h2>
            <p className="sec-sub">{T(lang, 'pers_sub')}</p>
            <div className="pers-feats">
              {feats.map(f => (
                <div className="pers-feat" key={f.t}>
                  <div className="pf-ic"><Ic name={f.ic} size={19} /></div>
                  <div><h4>{T(lang, f.t)}</h4><p>{T(lang, f.d)}</p></div>
                </div>
              ))}
            </div>
            <button className="btn btn-primary btn-lg" onClick={() => goBook('personnel', null)}>
              {T(lang, 'pers_cta')} <Ic name="arrow" size={16} />
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Events ---------------- */
function EventCard({ lang, e, goBook, full }) {
  const pick = window.ATLAS.pick;
  return (
    <div className={'event-card js-reveal' + (full ? ' full' : '')}>
      <div className="ev-photo">
        {React.createElement('image-slot', { id: e.img, src: window.ATLAS.photo(e.img), placeholder: pick(e.t, lang), shape: 'rect' })}
        <span className="ev-datechip">
          <span className="ev-d">{new Date(e.date + 'T00:00:00').getDate()}</span>
          <span className="ev-m">{new Date(e.date + 'T00:00:00').toLocaleDateString(window.ATLAS.localeOf(lang), { month: 'short' })}</span>
        </span>
      </div>
      <div className="ev-body">
        <div className="ev-meta"><Ic name="pin" size={13} />{e.city} · {window.ATLAS.fmtDate(e.date, lang)}</div>
        <h3 className="display">{pick(e.t, lang)}</h3>
        <p>{pick(e.d, lang)}</p>
        <button className="btn btn-dark btn-sm" onClick={() => goBook('events', null)}>{T(lang, 'ev_join')} <Ic name="arrow" size={14} /></button>
      </div>
    </div>
  );
}
function Events({ lang, goBook, page }) {
  return (
    <section className={'section events-section' + (page ? ' page-section' : '')} id="events">
      <div className="wrap">
        <div className="sec-head js-reveal">
          <span className="eyebrow">{T(lang, 'ev_eyebrow')}</span>
          <h2 className="sec-title display">{T(lang, 'ev_title')}</h2>
          <p className="sec-sub">{T(lang, 'ev_sub')}</p>
        </div>
        <div className="events-grid">
          {window.ATLAS.events.map(e => <EventCard key={e.id} lang={lang} e={e} goBook={goBook} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------------- News ---------------- */
function NewsCard({ lang, n }) {
  const pick = window.ATLAS.pick;
  return (
    <article className="news-card js-reveal">
      <div className="nw-photo">
        {React.createElement('image-slot', { id: n.img, src: window.ATLAS.photo(n.img), placeholder: pick(n.t, lang), shape: 'rect' })}
        <span className="nw-tag">{pick(n.tag, lang)}</span>
      </div>
      <div className="nw-body">
        <div className="nw-date">{window.ATLAS.fmtDate(n.date, lang)}</div>
        <h3 className="display">{pick(n.t, lang)}</h3>
        <p>{pick(n.d, lang)}</p>
        <span className="nw-read">{T(lang, 'news_read')} <Ic name="arrow" size={14} /></span>
      </div>
    </article>
  );
}
function News({ lang, page }) {
  return (
    <section className={'section news-section zellij-bg' + (page ? ' page-section' : '')} id="news">
      <div className="wrap">
        <div className="sec-head js-reveal">
          <span className="eyebrow">{T(lang, 'news_eyebrow')}</span>
          <h2 className="sec-title display">{T(lang, 'news_title')}</h2>
          <p className="sec-sub">{T(lang, 'news_sub')}</p>
        </div>
        <div className="news-grid">
          {window.ATLAS.news.map(n => <NewsCard key={n.id} lang={lang} n={n} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Booking page ---------------- */
function BookPage({ lang, prefill, user, navigate, onLogin, setTrackCode }) {
  const [form, setForm] = useState(Object.assign(
    { service: '', date: '', time: '', pickup: '', dropoff: '', passengers: 2, vehicle: '', billing: 'monthly', name: '', phone: '', email: '', notes: '' },
    prefill || {},
    user ? { name: user.name, email: user.email, phone: user.phone } : {}
  ));
  const [step, setStep] = useState(0);
  const [done, setDone] = useState(null);
  const [errs, setErrs] = useState({});
  const [mapOpen, setMapOpen] = useState(false);
  const steps = ['rq_step1', 'rq_step2', 'rq_step3', 'rq_step4'];
  const set = (k, v) => setForm(f => Object.assign({}, f, { [k]: v }));

  const validate = (s) => {
    const e = {};
    if (s === 0 && !form.service) e.service = 1;
    if (s === 1) { if (!form.date) e.date = 1; if (!form.time) e.time = 1; if (!form.pickup) e.pickup = 1; if (!form.dropoff) e.dropoff = 1; }
    if (s === 3) { if (!form.name) e.name = 1; if (!form.phone) e.phone = 1; }
    setErrs(e); return Object.keys(e).length === 0;
  };
  const next = () => { if (validate(step)) setStep(s => Math.min(3, s + 1)); };
  const back = () => setStep(s => Math.max(0, s - 1));
  const submit = () => {
    if (!validate(3)) return;
    const created = window.ATLAS.addRequest({
      service: form.service, date: form.date, time: form.time, pickup: form.pickup, dropoff: form.dropoff,
      passengers: form.passengers || 1, vehicleReq: form.vehicle || null, name: form.name, phone: form.phone,
      email: form.email, notes: form.notes, lang, billing: form.service === 'personnel' ? form.billing : null, ownerEmail: user ? user.email : null,
    });
    setDone(created);
  };

  if (done) {
    return (
      <section className="section book-section zellij-bg" id="book">
        <div className="wrap">
          <div className="book-card reveal zellij-frame">
            <span className="zc tl"></span><span className="zc tr"></span><span className="zc bl"></span><span className="zc br"></span>
            <div className="confirm">
              <div className="seal"><Ic name="check" size={36} /></div>
              <h2 className="display">{T(lang, 'rq_done_title')}</h2>
              <div className="ref-lbl">{T(lang, 'rq_done_sub')}</div>
              <div className="ref">{done.id}</div>
              <p>{T(lang, 'rq_done_msg')}</p>

              {user ? (
                <div className="confirm-actions">
                  <button className="btn btn-primary" onClick={() => navigate('account')}>{T(lang, 'cf_track_now')} <Ic name="arrow" size={15} /></button>
                </div>
              ) : (
                <div className="confirm-cta">
                  <div className="cta-line">{T(lang, 'cf_create_track')}</div>
                  <div className="confirm-actions">
                    <button className="btn btn-primary" onClick={() => onLogin('signup', { name: form.name, email: form.email, phone: form.phone }, done.id)}>
                      <Ic name="user" size={15} />{T(lang, 'cf_create_btn')}
                    </button>
                    <button className="btn btn-ghost" onClick={() => { setTrackCode(done.id); navigate('track'); }}>{T(lang, 'cf_guest_track')}</button>
                  </div>
                  <div className="guest-note">{T(lang, 'trk_guest_note')}</div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="section book-section zellij-bg" id="book">
      <div className="wrap">
        <div className="sec-head" style={{ textAlign: 'center', margin: '0 auto 40px' }}>
          <span className="eyebrow">{T(lang, 'rq_eyebrow')}</span>
          <h2 className="sec-title display">{T(lang, 'rq_title')}</h2>
          <p className="sec-sub">{T(lang, 'rq_sub')}</p>
        </div>
        <div className="book-card">
          <div className="steps">
            {steps.map((s, i) => (
              <div key={s} className={'step-pip' + (i === step ? ' active' : i < step ? ' done' : '')}>
                <div className="bar"></div><div className="lbl">{T(lang, s)}</div>
              </div>
            ))}
          </div>

          {step === 0 && (
            <div>
              <div className="field" style={{ marginBottom: 16 }}><label>{T(lang, 'rq_choose_service')}</label></div>
              <div className="choice-grid">
                {window.ATLAS.services.map(s => (
                  <button key={s.id} className={'choice' + (form.service === s.id ? ' sel' : '')} onClick={() => set('service', s.id)}>
                    <span className="ch-ic">{s.icon}</span>
                    <span className="col"><span className="ch-t">{serviceTitle(lang, s)}</span></span>
                  </button>
                ))}
              </div>
              {errs.service && <div className="form-err" style={{ marginTop: 12 }}>{T(lang, 'rq_required')}</div>}
              {form.service === 'personnel' && (
                <div className="billing-block">
                  <label className="billing-label">{T(lang, 'bill_label')}</label>
                  <div className="billing-seg">
                    {['daily', 'monthly', 'annual'].map(b => (
                      <button key={b} type="button" className={'bill-opt' + (form.billing === b ? ' on' : '')} onClick={() => set('billing', b)}>
                        {T(lang, 'bill_' + b)}
                      </button>
                    ))}
                  </div>
                  <div className="billing-hint">{T(lang, 'bill_hint')}</div>
                </div>
              )}
            </div>
          )}

          {step === 1 && (
            <div className="form-grid">
              <div className="field full map-cta-row">
                <button type="button" className="btn btn-dark btn-sm map-cta" onClick={() => setMapOpen(true)}>
                  <Ic name="pin" size={15} />{T(lang, 'map_open')}
                </button>
              </div>
              <div className="field"><label>{T(lang, 'rq_date')}</label>
                <input className="input" type="date" value={form.date} onChange={e => set('date', e.target.value)} />
                {errs.date && <span className="form-err">{T(lang, 'rq_required')}</span>}
              </div>
              <div className="field"><label>{T(lang, 'rq_time')}</label>
                <input className="input" type="time" value={form.time} onChange={e => set('time', e.target.value)} />
                {errs.time && <span className="form-err">{T(lang, 'rq_required')}</span>}
              </div>
              <div className="field full"><label>{T(lang, 'rq_pickup')}</label>
                <input className="input" list="atlas-cities" placeholder={T(lang, 'rq_pickup_ph')} value={form.pickup} onChange={e => set('pickup', e.target.value)} />
                {errs.pickup && <span className="form-err">{T(lang, 'rq_required')}</span>}
              </div>
              <div className="field full"><label>{T(lang, 'rq_dropoff')}</label>
                <input className="input" list="atlas-cities" placeholder={T(lang, 'rq_dropoff_ph')} value={form.dropoff} onChange={e => set('dropoff', e.target.value)} />
                {errs.dropoff && <span className="form-err">{T(lang, 'rq_required')}</span>}
              </div>
              <div className="field"><label>{T(lang, 'rq_passengers')}</label>
                <div className="row gap-12">
                  <button className="btn btn-dark btn-sm" type="button" onClick={() => set('passengers', Math.max(1, (form.passengers || 1) - 1))}>−</button>
                  <span className="display" style={{ fontSize: '1.6rem', minWidth: 40, textAlign: 'center' }}>{form.passengers || 1}</span>
                  <button className="btn btn-dark btn-sm" type="button" onClick={() => set('passengers', Math.min(60, (form.passengers || 1) + 1))}>+</button>
                </div>
              </div>
              <datalist id="atlas-cities">{window.ATLAS.cities.map(c => <option key={c} value={c} />)}</datalist>
              {mapOpen && <MapPicker lang={lang}
                initDep={window.ATLAS.mapCities.find(c => c.name === form.pickup)}
                initArr={window.ATLAS.mapCities.find(c => c.name === form.dropoff)}
                onConfirm={({ pickup, dropoff }) => { if (pickup) set('pickup', pickup); if (dropoff) set('dropoff', dropoff); setMapOpen(false); }}
                onCancel={() => setMapOpen(false)} />}
            </div>
          )}

          {step === 2 && (
            <div>
              <div className="field" style={{ marginBottom: 16 }}><label>{T(lang, 'rq_choose_vehicle')}</label></div>
              <div className="choice-grid">
                <button className={'choice' + (form.vehicle === '' ? ' sel' : '')} onClick={() => set('vehicle', '')}>
                  <span className="ch-ic">✶</span><span className="col"><span className="ch-t">{T(lang, 'rq_vehicle_any')}</span></span>
                </button>
                {window.ATLAS.vehicles.map(v => (
                  <button key={v.id} className={'choice' + (form.vehicle === v.id ? ' sel' : '')} onClick={() => set('vehicle', v.id)}>
                    <span className="ch-ic"><Ic name="car" size={20} /></span>
                    <span className="col">
                      <span className="ch-t">{vehicleTitle(lang, v)}</span>
                      <span className="ch-d">{v.seats} {T(lang, 'fleet_seats')} · {window.ATLAS.fmtMoney(v.priceDay, lang)}{T(lang, 'fleet_perday')}</span>
                    </span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="form-grid">
              <div className="field"><label>{T(lang, 'rq_name')}</label>
                <input className="input" placeholder={T(lang, 'rq_name_ph')} value={form.name} onChange={e => set('name', e.target.value)} />
                {errs.name && <span className="form-err">{T(lang, 'rq_required')}</span>}
              </div>
              <div className="field"><label>{T(lang, 'rq_phone')}</label>
                <input className="input" placeholder={T(lang, 'rq_phone_ph')} value={form.phone} onChange={e => set('phone', e.target.value)} />
                {errs.phone && <span className="form-err">{T(lang, 'rq_required')}</span>}
              </div>
              <div className="field full"><label>{T(lang, 'rq_email')}</label>
                <input className="input" type="email" placeholder={T(lang, 'rq_email_ph')} value={form.email} onChange={e => set('email', e.target.value)} />
              </div>
              <div className="field full"><label>{T(lang, 'rq_notes')}</label>
                <textarea className="input" rows="3" placeholder={T(lang, 'rq_notes_ph')} value={form.notes} onChange={e => set('notes', e.target.value)}></textarea>
              </div>
            </div>
          )}

          <div className="form-actions">
            <button className="btn btn-ghost" onClick={back} disabled={step === 0}>{T(lang, 'rq_back')}</button>
            {step < 3
              ? <button className="btn btn-primary" onClick={next}>{T(lang, 'rq_next')} <Ic name="arrow" size={15} /></button>
              : <button className="btn btn-primary" onClick={submit}>{T(lang, 'rq_submit')} <Ic name="check" size={15} /></button>}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Track page ---------------- */
function TrackPage({ lang, initialCode, user, navigate, onLogin }) {
  const [code, setCode] = useState(initialCode || '');
  const [found, setFound] = useState(initialCode ? window.ATLAS.getByCode(initialCode) : null);
  const [searched, setSearched] = useState(!!initialCode);
  const [, force] = useState(0);
  useEffect(() => { const u = window.ATLAS.subscribe(() => force(x => x + 1)); return u; }, []);
  useEffect(() => { if (initialCode) { setCode(initialCode); setFound(window.ATLAS.getByCode(initialCode)); setSearched(true); } }, [initialCode]);

  const lookup = () => { setFound(window.ATLAS.getByCode(code)); setSearched(true); };
  const fresh = found ? window.ATLAS.getByCode(found.id) : null;

  return (
    <section className="section page-section zellij-bg">
      <div className="wrap narrow">
        <div className="sec-head" style={{ textAlign: 'center', margin: '0 auto 32px' }}>
          <span className="eyebrow">{T(lang, 'trk_track')}</span>
          <h2 className="sec-title display">{T(lang, 'trk_title')}</h2>
        </div>
        <div className="track-bar card">
          <div className="field grow"><label>{T(lang, 'trk_code_label')}</label>
            <input className="input" placeholder={T(lang, 'trk_code_ph')} value={code}
              onChange={e => setCode(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') lookup(); }} />
          </div>
          <button className="btn btn-primary" onClick={lookup}><Ic name="search" size={16} />{T(lang, 'trk_find')}</button>
        </div>

        {!user && (
          <div className="track-hint">
            {T(lang, 'cf_create_track')} <button className="link-btn" onClick={() => onLogin('signup')}>{T(lang, 'cf_create_btn')}</button>
          </div>
        )}

        {searched && !fresh && <div className="empty-note card">{T(lang, 'trk_notfound')}</div>}
        {fresh && <div className="card crv-card"><ClientRequestView lang={lang} r={fresh} user={user} onChanged={() => force(x => x + 1)} /></div>}
      </div>
    </section>
  );
}

/* ---------------- Account page ---------------- */
function AccountPage({ lang, user, navigate, onLogin }) {
  const [sel, setSel] = useState(null);
  const [, force] = useState(0);
  useEffect(() => { const u = window.ATLAS.subscribe(() => force(x => x + 1)); return u; }, []);

  if (!user) {
    return (
      <section className="section page-section zellij-bg">
        <div className="wrap narrow">
          <div className="card signin-prompt">
            <span className="tile-chip"></span>
            <h2 className="display">{T(lang, 'ac_account')}</h2>
            <p className="muted">{T(lang, 'cf_create_track')}</p>
            <div className="row gap-12 center" style={{ marginTop: 18 }}>
              <button className="btn btn-primary" onClick={() => onLogin('login')}>{T(lang, 'ac_login')}</button>
              <button className="btn btn-ghost" onClick={() => onLogin('signup')}>{T(lang, 'ac_signup')}</button>
            </div>
          </div>
        </div>
      </section>
    );
  }

  const reqs = window.ATLAS.getUserRequests(user.email);
  const current = sel ? window.ATLAS.getByCode(sel) : null;

  return (
    <section className="section page-section zellij-bg">
      <div className="wrap">
        <div className="account-head">
          <div>
            <span className="eyebrow">{T(lang, 'ac_welcome')}</span>
            <h2 className="sec-title display">{user.name}</h2>
          </div>
          <button className="btn btn-primary" onClick={() => navigate('book')}><Ic name="plus" size={16} />{T(lang, 'nav_book')}</button>
        </div>

        {current ? (
          <div>
            <button className="link-btn back-link" onClick={() => setSel(null)}>← {T(lang, 'trk_back')}</button>
            <div className="card crv-card"><ClientRequestView lang={lang} r={current} user={user} onChanged={() => force(x => x + 1)} /></div>
          </div>
        ) : reqs.length === 0 ? (
          <div className="empty-note card">{T(lang, 'ac_no_requests')}</div>
        ) : (
          <div className="acct-reqs">
            {reqs.map(r => (
              <button className="acct-req card" key={r.id} onClick={() => setSel(r.id)}>
                <div className="ar-top">
                  <span className="ar-svc display">{T(lang, 'svc_' + r.service + '_t')}</span>
                  <StatusBadge status={r.status} lang={lang} />
                </div>
                <div className="ar-route"><Ic name="pin" size={14} />{r.pickup} → {r.dropoff}</div>
                <div className="ar-foot">
                  <span className="ar-id">{r.id}</span>
                  <span className="faint">{window.ATLAS.fmtDate(r.date, lang)}</span>
                  {r.quote ? <span className={'ar-quote' + (r.quoteAccepted ? ' ok' : '')}>{window.ATLAS.fmtMoney(r.quote, lang)}{r.quoteAccepted ? ' ✓' : ''}</span> : null}
                </div>
              </button>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

/* ---------------- Footer ---------------- */
function Footer({ lang, navigate }) {
  const C = window.ATLAS.config;
  return (
    <footer className="site-footer zellij-bg">
      <div className="zellij-band tall" style={{ position: 'absolute', top: 0, left: 0, right: 0 }}></div>
      <div className="wrap">
        <div className="footer-top">
          <div>
            <a className="brand-logo" href="#/">
              <BrandMark size={42} />
              <span className="brand-words"><span className="brand-name display"><span className="bw-a">GoTo</span><span className="bw-b">Morocco</span></span><span className="brand-sub">{C.domain}</span></span>
            </a>
            <p className="footer-tag display">{T(lang, 'foot_tag')}</p>
          </div>
          <div className="footer-cols">
            <div className="footer-col">
              <h4>{T(lang, 'nav_services')}</h4>
              {window.ATLAS.services.map(s => <a key={s.id} href="#/services">{serviceTitle(lang, s)}</a>)}
            </div>
            <div className="footer-col">
              <h4>{T(lang, 'foot_contact')}</h4>
              <p>{C.phone}</p><p>{C.email}</p><p>{C.address}</p>
              <a href={window.ATLAS.waLink(lang)} target="_blank" rel="noopener" style={{ color: 'var(--accent)' }}>{T(lang, 'wa_label')} →</a>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 {T(lang, 'brand')}. {T(lang, 'foot_rights')}</span>
          <a href="/admin">{T(lang, 'nav_admin')} →</a>
        </div>
      </div>
    </footer>
  );
}

/* ---------------- Tweaks ---------------- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "classic",
  "accent": "sand",
  "zellij": true
}/*EDITMODE-END*/;

/* ---------------- App ---------------- */
function App() {
  const [lang, setLang] = useLang();
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, navigate] = useRoute();
  const user = useAuth();
  const [bookPrefill, setBookPrefill] = useState(null);
  const [trackCode, setTrackCode] = useState('');
  const [auth, setAuth] = useState(null); // {mode, prefill, claimCode}

  useEffect(() => { applyAccent(t.accent); }, [t.accent]);
  useEffect(() => { document.body.classList.toggle('no-zellij', !t.zellij); }, [t.zellij]);

  // re-render whole tree when currency changes so prices refresh
  const [, setCurTick] = useState(0);
  useEffect(() => window.ATLAS.subscribeCurrency(() => setCurTick(x => x + 1)), []);

  // scroll-reveal (progressive enhancement; re-observe on page change)
  useEffect(() => {
    document.body.classList.add('js-ready');
    const els = document.querySelectorAll('.js-reveal:not(.in)');
    const io = new IntersectionObserver((es) => es.forEach(e => {
      if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); }
    }), { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [route]);

  const goBook = (service, vehicle) => { setBookPrefill({ service: service || '', vehicle: vehicle || '' }); navigate('book'); };
  const openLogin = (mode, prefill, claimCode) => setAuth({ mode: mode || 'login', prefill, claimCode });
  const onAuthed = (u) => {
    if (auth && auth.claimCode) { window.ATLAS.claimRequest(auth.claimCode, u.email); navigate('account'); }
  };

  let page;
  if (route === 'services') page = <Services lang={lang} navigate={navigate} goBook={goBook} />;
  else if (route === 'fleet') page = <Fleet lang={lang} goBook={goBook} />;
  else if (route === 'events') page = <Events lang={lang} goBook={goBook} page />;
  else if (route === 'news') page = <News lang={lang} page />;
  else if (route === 'book') page = <BookPage lang={lang} prefill={bookPrefill} user={user} navigate={navigate} onLogin={openLogin} setTrackCode={setTrackCode} />;
  else if (route === 'track') page = <TrackPage lang={lang} initialCode={trackCode} user={user} navigate={navigate} onLogin={openLogin} />;
  else if (route === 'account') page = <AccountPage lang={lang} user={user} navigate={navigate} onLogin={openLogin} />;
  else page = (
    <div>
      <Hero lang={lang} variant={t.heroVariant} navigate={navigate} />
      <Features lang={lang} />
      <Services lang={lang} navigate={navigate} goBook={goBook} />
      <Fleet lang={lang} goBook={goBook} />
      <Personnel lang={lang} goBook={goBook} />
      <Languages lang={lang} />
      <Destinations lang={lang} />
      <Events lang={lang} goBook={goBook} />
      <Reviews lang={lang} />
      <News lang={lang} />
      <CTABand lang={lang} navigate={navigate} />
    </div>
  );

  return (
    <div>
      <Header lang={lang} setLang={setLang} route={route} navigate={navigate} user={user} onLogin={openLogin} />
      {page}
      <Footer lang={lang} navigate={navigate} />
      <WhatsAppWidget lang={lang} />

      {auth && <AuthModal lang={lang} mode={auth.mode} prefill={auth.prefill} onClose={() => setAuth(null)} onAuthed={onAuthed} />}

      <TweaksPanel>
        <TweakSection label={lang === 'ar' ? 'الصفحة الرئيسية' : lang === 'en' ? 'Home page' : 'Page d\u2019accueil'} />
        <TweakRadio label={lang === 'ar' ? 'أسلوب الهيرو' : 'Hero'} value={t.heroVariant}
          options={['classic', 'split', 'minimal']} onChange={(v) => setTweak('heroVariant', v)} />
        <TweakSection label={lang === 'ar' ? 'الزخرفة واللون' : lang === 'en' ? 'Decor & accent' : 'Décor & accent'} />
        <TweakToggle label={lang === 'ar' ? 'زخرفة الزليج' : 'Zellij'} value={t.zellij} onChange={(v) => setTweak('zellij', v)} />
        <TweakColor label={lang === 'ar' ? 'اللون المميز' : 'Accent'} value={ACCENTS[t.accent].a}
          options={[ACCENTS.sand.a, ACCENTS.terracotta.a, ACCENTS.olive.a]}
          onChange={(v) => { const n = Object.keys(ACCENTS).find(k => ACCENTS[k].a === v) || 'sand'; setTweak('accent', n); }} />
      </TweaksPanel>
    </div>
  );
}

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