/* ============================================================
   GoToMorocco — accounts, tracking, signature, WhatsApp
   (loaded after shared.jsx — relies on its React hook bindings)
   ============================================================ */

/* ---------------- auth hook ---------------- */
function useAuth() {
  const [user, setUser] = useState(window.ATLAS.currentUser());
  useEffect(() => window.ATLAS.subscribeSession(() => setUser(window.ATLAS.currentUser())), []);
  return user;
}

/* ---------------- WhatsApp floating widget ---------------- */
function WhatsAppWidget({ lang }) {
  return (
    <a className="wa-widget" href={window.ATLAS.waLink(lang)} target="_blank" rel="noopener"
       aria-label={T(lang, 'wa_label')} title={T(lang, 'wa_label')}>
      <svg viewBox="0 0 32 32" width="30" height="30" aria-hidden="true">
        <path fill="currentColor" d="M16 3C9.4 3 4 8.4 4 15c0 2.1.6 4.1 1.6 5.9L4 29l8.3-1.6c1.7.9 3.6 1.4 5.6 1.4h.1c6.6 0 12-5.4 12-12S22.6 3 16 3zm0 21.8c-1.8 0-3.5-.5-5-1.4l-.4-.2-4.9 1 1-4.8-.2-.4c-1-1.6-1.5-3.4-1.5-5.3 0-5.5 4.5-9.9 10-9.9 2.7 0 5.2 1 7 2.9 1.9 1.9 2.9 4.4 2.9 7 0 5.5-4.5 9.8-9.4 9.8zm5.5-7.4c-.3-.2-1.8-.9-2.1-1-.3-.1-.5-.2-.7.2-.2.3-.8 1-.9 1.1-.2.2-.3.2-.6.1-.3-.2-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6l.5-.5c.2-.2.2-.3.3-.5.1-.2.1-.4 0-.5l-1-2.3c-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.2.2 2.1 3.3 5.2 4.6.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.8-.7 2-1.4.3-.7.3-1.3.2-1.4-.1-.2-.3-.3-.6-.4z"/>
      </svg>
      <span className="wa-pulse"></span>
    </a>
  );
}

/* ---------------- Modal base ---------------- */
function Modal({ children, onClose, wide, lang }) {
  useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', h); document.body.style.overflow = ''; };
  }, []);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className={'modal-card zellij-frame' + (wide ? ' wide' : '')} onClick={e => e.stopPropagation()}>
        <span className="zc tl"></span><span className="zc tr"></span>
        <span className="zc bl"></span><span className="zc br"></span>
        <button className="modal-close" onClick={onClose} aria-label={T(lang, 'close')}><Ic name="x" size={18} /></button>
        {children}
      </div>
    </div>
  );
}

/* ---------------- Auth modal (login / signup) ---------------- */
function AuthModal({ lang, mode, prefill, onClose, onAuthed }) {
  const [tab, setTab] = useState(mode || 'login');
  const [f, setF] = useState({ name: prefill?.name || '', email: prefill?.email || '', phone: prefill?.phone || '', password: '' });
  const [err, setErr] = useState('');
  const set = (k, v) => setF(s => Object.assign({}, s, { [k]: v }));

  const submit = () => {
    setErr('');
    if (tab === 'login') {
      const res = window.ATLAS.login(f.email, f.password);
      if (res.error) return setErr(T(lang, 'ac_bad_login'));
      onAuthed && onAuthed(res.user); onClose();
    } else {
      if (!f.name || !f.email || !f.password) return setErr(T(lang, 'ac_fields'));
      const res = window.ATLAS.signup(f);
      if (res.error === 'exists') return setErr(T(lang, 'ac_exists'));
      if (res.error) return setErr(T(lang, 'ac_fields'));
      onAuthed && onAuthed(res.user); onClose();
    }
  };

  return (
    <Modal onClose={onClose} lang={lang}>
      <div className="auth-head">
        <span className="tile-chip"></span>
        <h2 className="display">{T(lang, tab === 'login' ? 'ac_login_title' : 'ac_signup_title')}</h2>
      </div>
      <div className="auth-form">
        {tab === 'signup' && (
          <div className="field"><label>{T(lang, 'ac_name')}</label>
            <input className="input" value={f.name} onChange={e => set('name', e.target.value)} autoFocus />
          </div>
        )}
        <div className="field"><label>{T(lang, 'ac_email')}</label>
          <input className="input" type="email" value={f.email} onChange={e => set('email', e.target.value)} />
        </div>
        {tab === 'signup' && (
          <div className="field"><label>{T(lang, 'ac_phone')}</label>
            <input className="input" value={f.phone} onChange={e => set('phone', e.target.value)} />
          </div>
        )}
        <div className="field"><label>{T(lang, 'ac_password')}</label>
          <input className="input" type="password" value={f.password}
            onChange={e => set('password', e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') submit(); }} />
        </div>
        {err && <div className="form-err">{err}</div>}
        <button className="btn btn-primary" style={{ width: '100%' }} onClick={submit}>
          {T(lang, tab === 'login' ? 'ac_do_login' : 'ac_do_signup')}
        </button>
        <button className="auth-switch" onClick={() => { setTab(tab === 'login' ? 'signup' : 'login'); setErr(''); }}>
          {T(lang, tab === 'login' ? 'ac_no_account' : 'ac_have_account')}
        </button>
        {tab === 'login' && <div className="auth-demo">{T(lang, 'ac_demo')}</div>}
      </div>
    </Modal>
  );
}

/* ---------------- Signature pad ---------------- */
function SignaturePad({ lang, defaultName, onConfirm, onCancel }) {
  const canvasRef = useRef(null);
  const [name, setName] = useState(defaultName || '');
  const [drawn, setDrawn] = useState(false);
  const [err, setErr] = useState('');
  const drawing = useRef(false);
  const last = useRef(null);

  useEffect(() => {
    const c = canvasRef.current;
    const dpr = window.devicePixelRatio || 1;
    const rect = c.getBoundingClientRect();
    c.width = rect.width * dpr; c.height = rect.height * dpr;
    const ctx = c.getContext('2d');
    ctx.scale(dpr, dpr);
    ctx.strokeStyle = '#f0e6d2'; ctx.lineWidth = 2.4; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
  }, []);

  const pos = (e) => {
    const c = canvasRef.current; const rect = c.getBoundingClientRect();
    const p = e.touches ? e.touches[0] : e;
    return { x: p.clientX - rect.left, y: p.clientY - rect.top };
  };
  const start = (e) => { e.preventDefault(); drawing.current = true; last.current = pos(e); };
  const move = (e) => {
    if (!drawing.current) return; e.preventDefault();
    const ctx = canvasRef.current.getContext('2d'); const p = pos(e);
    ctx.beginPath(); ctx.moveTo(last.current.x, last.current.y); ctx.lineTo(p.x, p.y); ctx.stroke();
    last.current = p; setDrawn(true);
  };
  const end = () => { drawing.current = false; };

  const clear = () => {
    const c = canvasRef.current; const ctx = c.getContext('2d');
    ctx.clearRect(0, 0, c.width, c.height); setDrawn(false);
  };
  const confirm = () => {
    if (!drawn || !name.trim()) { setErr(T(lang, 'sig_empty')); return; }
    onConfirm(canvasRef.current.toDataURL('image/png'), name.trim());
  };

  return (
    <Modal onClose={onCancel} lang={lang} wide>
      <div className="auth-head">
        <span className="tile-chip"></span>
        <h2 className="display">{T(lang, 'sig_title')}</h2>
      </div>
      <p className="muted" style={{ marginBottom: 14 }}>{T(lang, 'sig_hint')}</p>
      <div className="sig-wrap">
        <canvas ref={canvasRef} className="sig-canvas"
          onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
          onTouchStart={start} onTouchMove={move} onTouchEnd={end}></canvas>
        <button className="sig-clear" onClick={clear}>{T(lang, 'sig_clear')}</button>
      </div>
      <div className="field" style={{ marginTop: 16 }}>
        <label>{T(lang, 'sig_name')}</label>
        <input className="input" value={name} onChange={e => setName(e.target.value)} />
      </div>
      {err && <div className="form-err" style={{ marginTop: 8 }}>{err}</div>}
      <div className="row gap-12" style={{ marginTop: 18 }}>
        <button className="btn btn-ghost grow" onClick={onCancel}>{T(lang, 'rq_back')}</button>
        <button className="btn btn-primary grow" onClick={confirm}><Ic name="check" size={16} />{T(lang, 'sig_confirm')}</button>
      </div>
    </Modal>
  );
}

/* ---------------- Status timeline ---------------- */
function StatusTimeline({ lang, status }) {
  if (status === 'refused') {
    return <div className="timeline refused"><span className="badge refused"><span className="dot"></span>{T(lang, 'st_refused')}</span></div>;
  }
  const steps = ['pending', 'confirmed', 'progress', 'done'];
  const idx = steps.indexOf(status);
  return (
    <div className="timeline">
      {steps.map((s, i) => (
        <div key={s} className={'tl-step' + (i <= idx ? ' done' : '') + (i === idx ? ' current' : '')}>
          <span className="tl-dot">{i <= idx ? <Ic name="check" size={13} /> : i + 1}</span>
          <span className="tl-lbl">{T(lang, 'st_' + s)}</span>
        </div>
      ))}
    </div>
  );
}

/* ---------------- Client quote box (accept + sign) ---------------- */
function ClientQuoteBox({ lang, r, user, onChanged }) {
  const [signing, setSigning] = useState(false);
  const [paying, setPaying] = useState(false);
  const [method, setMethod] = useState('card');
  const [err, setErr] = useState('');
  const payLabel = (key) => ({
    fr: { pay: 'Payer maintenant', paid: 'Paiement confirme', pending: 'Paiement en attente', choose: 'Mode de paiement', card: 'Carte bancaire', cash: 'Paiement agence', transfer: 'Virement', confirm: 'Confirmer le paiement', ref: 'Reference paiement', hint: 'Paiement local de demonstration. Aucune donnee carte n\u2019est stockee.' },
    en: { pay: 'Pay now', paid: 'Payment confirmed', pending: 'Payment pending', choose: 'Payment method', card: 'Bank card', cash: 'Agency payment', transfer: 'Bank transfer', confirm: 'Confirm payment', ref: 'Payment reference', hint: 'Local demo payment. No card data is stored.' },
    ar: { pay: 'ادفع الآن', paid: 'تم تأكيد الدفع', pending: 'الدفع في الانتظار', choose: 'طريقة الدفع', card: 'بطاقة بنكية', cash: 'الدفع في الوكالة', transfer: 'تحويل بنكي', confirm: 'تأكيد الدفع', ref: 'مرجع الدفع', hint: 'دفع محلي تجريبي. لا يتم تخزين بيانات البطاقة.' },
  }[lang] || {})[key] || key;
  if (!r.quote) {
    return <div className="qbox awaiting"><Ic name="clock" size={18} /><span>{T(lang, 'q_awaiting')}</span></div>;
  }
  const accept = (sig, name) => {
    window.ATLAS.acceptQuote(r.id, sig, name);
    setSigning(false); onChanged && onChanged();
  };
  const pay = () => {
    setErr(''); setPaying(true);
    window.ATLAS.api.createPayment(r.id, { method, amount: r.quote, payerName: user?.name || r.name })
      .then(() => { setPaying(false); onChanged && onChanged(); })
      .catch(() => { setPaying(false); setErr(lang === 'ar' ? 'تعذر الدفع' : 'Paiement impossible'); });
  };
  return (
    <div className={'qbox' + (r.quoteAccepted ? ' accepted' : '')}>
      <div className="qbox-top">
        <span className="qbox-lbl">{T(lang, 'q_proposed')}</span>
        <span className="qbox-amt display">{window.ATLAS.fmtMoney(r.quote, lang)}</span>
      </div>
      {r.quoteAccepted ? (
        <div className="qbox-accepted">
          <div className="quote-state-row">
            <div className="badge confirmed"><span className="dot"></span>{T(lang, 'q_accepted')}</div>
            {r.payment ? <div className={'badge ' + (r.payment.status === 'paid' ? 'confirmed' : 'pending')}><span className="dot"></span>{r.payment.status === 'paid' ? payLabel('paid') : payLabel('pending')}</div> : null}
          </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')} {new Date(r.acceptedAt).toLocaleDateString(lang === 'ar' ? 'ar-MA' : lang === 'en' ? 'en-GB' : 'fr-FR')}</div>
            </div>
          </div>
          {r.payment ? (
            <div className="payment-proof">
              <span>{payLabel('ref')}</span>
              <strong>{r.payment.id}</strong>
              <span>{r.payment.method} · {window.ATLAS.fmtMoney(r.payment.amount, lang)}</span>
            </div>
          ) : (
            <div className="payment-box">
              <div className="field">
                <label>{payLabel('choose')}</label>
                <div className="payment-methods">
                  {['card', 'cash', 'transfer'].map(m => (
                    <button key={m} className={'pay-method' + (method === m ? ' on' : '')} onClick={() => setMethod(m)}>{payLabel(m)}</button>
                  ))}
                </div>
              </div>
              <div className="payment-hint">{payLabel('hint')}</div>
              {err && <div className="form-err" style={{ marginTop: 8 }}>{err}</div>}
              <button className="btn btn-primary" style={{ width: '100%', marginTop: 12 }} onClick={pay} disabled={paying}>
                <Ic name="money" size={16} />{paying ? '...' : payLabel('confirm')}
              </button>
            </div>
          )}
        </div>
      ) : (
        <button className="btn btn-primary" style={{ width: '100%', marginTop: 14 }} onClick={() => setSigning(true)}>
          <Ic name="check" size={16} />{T(lang, 'q_accept')}
        </button>
      )}
      {signing && <SignaturePad lang={lang} defaultName={user?.name || r.name} onConfirm={accept} onCancel={() => setSigning(false)} />}
    </div>
  );
}

/* ---------------- Client chat ---------------- */
function ClientChat({ lang, r, onChanged }) {
  const [msg, setMsg] = useState('');
  const threadRef = useRef(null);
  useEffect(() => { if (threadRef.current) threadRef.current.scrollTop = threadRef.current.scrollHeight; }, [r.messages.length]);
  const send = () => {
    if (!msg.trim()) return;
    window.ATLAS.addMessage(r.id, 'client', msg.trim());
    setMsg(''); onChanged && onChanged();
  };
  return (
    <div>
      <div className="chat-thread" ref={threadRef} style={{ maxHeight: 260 }}>
        {(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, 'trk_msg_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>
  );
}

/* ---------------- Client request view (shared by track + account) ---------------- */
function ClientRequestView({ lang, r, user, onChanged }) {
  const drv = window.ATLAS.drivers.find(d => d.id === r.driver);
  return (
    <div className="crv">
      <div className="crv-head">
        <div>
          <div className="crv-id">{r.id}</div>
          <div className="crv-svc display">{T(lang, 'svc_' + r.service + '_t')}</div>
        </div>
        <StatusBadge status={r.status} lang={lang} />
      </div>

      <StatusTimeline lang={lang} status={r.status} />

      <div className="crv-grid">
        <div className="crv-cell">
          <div className="crv-lbl"><Ic name="pin" size={13} />{T(lang, 'ad_trip')}</div>
          <div className="crv-val">{r.pickup}<br /><span className="faint">↓</span><br />{r.dropoff}</div>
        </div>
        <div className="crv-cell">
          <div className="crv-lbl"><Ic name="cal" size={13} />{T(lang, 'ad_col_when')}</div>
          <div className="crv-val">{window.ATLAS.fmtDate(r.date, lang)}<br /><span className="faint">{r.time}</span></div>
        </div>
        <div className="crv-cell">
          <div className="crv-lbl"><Ic name="car" size={13} />{T(lang, 'ad_col_vehicle')}</div>
          <div className="crv-val">{r.vehicle ? T(lang, 'veh_' + r.vehicle + '_t') : T(lang, 'ad_unassigned')}</div>
        </div>
        <div className="crv-cell">
          <div className="crv-lbl"><Ic name="user" size={13} />{T(lang, 'ad_assign_driver')}</div>
          <div className="crv-val">{drv ? drv.name : T(lang, 'ad_unassigned')}</div>
        </div>
      </div>

      <div className="crv-sec">
        <h4>{T(lang, 'ad_quote')}</h4>
        <ClientQuoteBox lang={lang} r={r} user={user} onChanged={onChanged} />
      </div>

      <div className="crv-sec">
        <h4>{T(lang, 'ad_chat')}</h4>
        <ClientChat lang={lang} r={r} onChanged={onChanged} />
      </div>
    </div>
  );
}

/* ---------------- Morocco map picker ---------------- */
const MOROCCO_PATH = "M40 7 L52 8 L64 12 L76 16 L80 30 L74 46 L70 60 L63 70 L52 80 L40 92 L26 104 L14 119 L8 127 L12 116 L17 96 L20 78 L17 62 L21 50 L17 45 L24 38 L29 30 L33 22 L37 13 Z";

function MapPicker({ lang, initDep, initArr, onConfirm, onCancel }) {
  const cities = window.ATLAS.mapCities;
  const [mode, setMode] = useState('dep');
  const [dep, setDep] = useState(initDep || null); // {name,x,y}
  const [arr, setArr] = useState(initArr || null);
  const boxRef = useRef(null);

  const nearest = (px, py) => {
    let best = null, bd = 1e9;
    cities.forEach(c => { const d = (c.x - px) ** 2 + (c.y - py) ** 2; if (d < bd) { bd = d; best = c; } });
    return best;
  };
  const place = (e) => {
    const r = boxRef.current.getBoundingClientRect();
    const p = e.touches ? e.touches[0] : e;
    const px = (p.clientX - r.left) / r.width, py = (p.clientY - r.top) / r.height;
    const c = nearest(px, py);
    if (!c) return;
    if (mode === 'dep') { setDep(c); setMode('arr'); } else { setArr(c); }
  };
  const confirm = () => onConfirm({ pickup: dep ? dep.name : '', dropoff: arr ? arr.name : '' });

  const pin = (c, kind) => c ? (
    <span className={'map-pin ' + kind} style={{ left: (c.x * 100) + '%', top: (c.y * 100) + '%' }}>
      <Ic name="pin" size={20} />
    </span>
  ) : null;

  return (
    <Modal onClose={onCancel} lang={lang} wide>
      <div className="auth-head"><span className="tile-chip"></span><h2 className="display">{T(lang, 'map_title')}</h2></div>
      <div className="map-toggle">
        <button className={'map-tg dep' + (mode === 'dep' ? ' on' : '')} onClick={() => setMode('dep')}>
          <span className="mt-dot"></span>{T(lang, 'map_set_dep')}{dep ? ': ' + dep.name : ''}
        </button>
        <button className={'map-tg arr' + (mode === 'arr' ? ' on' : '')} onClick={() => setMode('arr')}>
          <span className="mt-dot"></span>{T(lang, 'map_set_arr')}{arr ? ': ' + arr.name : ''}
        </button>
      </div>
      <div className="map-box" ref={boxRef} onClick={place} onTouchStart={place}>
        <svg className="map-svg" viewBox="0 0 100 130" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
          <path d={MOROCCO_PATH} fill="oklch(0.30 0.03 60 / 0.55)" stroke="var(--accent)" strokeWidth="0.7" strokeLinejoin="round" />
        </svg>
        {cities.map(c => (
          <span key={c.name} className="map-city" style={{ left: (c.x * 100) + '%', top: (c.y * 100) + '%' }} title={c.name}>
            <span className="mc-dot"></span><span className="mc-name">{c.name}</span>
          </span>
        ))}
        {pin(dep, 'dep')}
        {pin(arr, 'arr')}
      </div>
      <div className="map-hint">{T(lang, 'map_hint')}</div>
      <div className="row gap-12" style={{ marginTop: 16 }}>
        <button className="btn btn-ghost grow" onClick={() => { setDep(null); setArr(null); setMode('dep'); }}>{T(lang, 'map_clear')}</button>
        <button className="btn btn-primary grow" onClick={confirm} disabled={!dep && !arr}><Ic name="check" size={16} />{T(lang, 'map_confirm')}</button>
      </div>
    </Modal>
  );
}

Object.assign(window, {
  useAuth, WhatsAppWidget, Modal, AuthModal, SignaturePad, MapPicker,
  StatusTimeline, ClientQuoteBox, ClientChat, ClientRequestView,
});
