// web/orders.jsx — Orders history page + reorder
const { useState: ohS, useEffect: ohE } = React;

// [HONESTY 2026-07-19] `PAST_ORDERS` (fausses commandes démo C-1234…) SUPPRIMÉ : jamais référencé
// (l'historique réel vient de api.history) — donnée morte + noms de commande fabriqués retirés.

// [WEB-WIREUP 2026-06-26] Map a backend order list row → display shape.
function mapOrderRow(o) {
  const sn = (o.status_name || '').toLowerCase();
  const cat = /annul/.test(sn) ? 'cancelled'
            // [HEAL 2026-07-19] « prêt » (prête, pas encore retirée) ≠ « terminée / livrée » : catégorie
            // propre 'ready' (pastille pending-style orange) au lieu d'un vert « Terminée » trompeur.
            : /(prêt|pret)/.test(sn) ? 'ready'
            : /(termin|livr|récup|recup|complet|servi)/.test(sn) ? 'delivered'
            : 'pending';
  return {
    id: o.order_serial_no || o.id,   // [FIX 2026-07-19] pas de '#' ici : le rendu (#{o.id}) l'ajoute → évitait ##123 sur une commande sans serial
    date: o.order_datetime || '',
    total: parseFloat(o.total_amount_price || 0) || 0,
    statusName: o.status_name || '—',
    status: cat,
    count: o.order_items || 0,
    emoji: '🧾',
  };
}

// [HEAL 2026-07-19] Formatte order_datetime en FR — même motif que fmtHistDate (screens.jsx) :
// « 8 juil. · 19h47 ». Repli sur la chaîne brute si non parsable (format MySQL « … » toléré via T).
function fmtOrderDate(raw) {
  if (!raw) return '';
  var d = new Date(raw);
  if (isNaN(d.getTime())) d = new Date(String(raw).replace(' ', 'T'));
  if (isNaN(d.getTime())) return String(raw);
  var day = d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' });
  var hm = d.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }).replace(':', 'h');
  return day + ' · ' + hm;
}

function OrdersPage({ onItem, onCart, isAuth, onAccount, onRoute }) {
  const [filter, setFilter] = ohS('all');
  // [WEB-WIREUP 2026-06-26] Real order history from the backend (window.LC.api).
  const [orders, setOrders] = ohS(null);   // null = loading, [] = loaded empty
  const [histErr, setHistErr] = ohS(null);
  ohE(() => {
    if (!isAuth) return;
    const api = (typeof window !== 'undefined' && window.LC && window.LC.api) || null;
    if (!api) { setOrders([]); return; }
    let alive = true;
    setOrders(null); setHistErr(null);
    api.history(50)
      .then(rows => { if (alive) setOrders((rows || []).map(mapOrderRow)); })
      .catch(e => {
        if (!alive) return;
        setOrders([]);
        // [HEAL 2026-07-19] 401 = session invité expirée (api.js throw {kind:'auth'}) → rouvre le
        // login plutôt qu'un « Chargement impossible » sur écran vide, qui masquait l'expiration d'auth.
        if (e && e.kind === 'auth') { if (onAccount) onAccount(); return; }
        setHistErr((e && e.message) || 'Chargement impossible.');
      });
    return () => { alive = false; };
  }, [isAuth]);
  if (!isAuth) {
    return (
      <div className="lc-section">
        <div className="lc-container" style={{ textAlign: 'center', padding: '60px 0' }}>
          <div className="lc-eyebrow" style={{ display: 'inline-block' }}>// Mes commandes</div>
          <h2 className="lc-display" style={{ fontSize: 'var(--fs-h1)', margin: '14px 0' }}>Connecte-toi<br/>pour <span style={{ color: 'var(--orange-text)' }}>retrouver</span></h2>
          <p style={{ color: 'var(--gray-4)', fontSize: 16, maxWidth: 480, margin: '0 auto 30px' }}>Ton historique de commandes et tes points cumulés sur chaque achat.</p>
          <button className="lc-btn lc-btn--orange" onClick={onAccount}>Me connecter <WC_I.arrow s={16}/></button>
        </div>
      </div>
    );
  }
  const loading = orders === null;
  const list = orders || [];
  const filtered = filter === 'all' ? list : list.filter(o => o.status === filter);
  // [T2-04 HEAL 2026-06-05] Derive the count + summary from the array instead of hardcoding "5".
  const totalCount = list.length;
  const totalSpent = list.reduce((s, o) => s + o.total, 0);
  return (
    <div className="lc-section">
      <div className="lc-container">
        <Reveal className="lc-section-head">
          <div className="lc-section-head-text">
            <div className="lc-eyebrow">// Historique</div>
            <h2>Mes <span>commandes.</span></h2>
            <p>{totalCount} commande{totalCount > 1 ? 's' : ''} au total · {totalSpent.toFixed(2).replace('.', ',')} € dépensés.</p>
          </div>
        </Reveal>

        {/* [HEAL A11Y-TABS-01 2026-06-04] tablist/tab/aria-selected semantics. */}
        <div className="lc-cat-tabs" role="tablist" aria-label="Filtrer les commandes" style={{ marginBottom: 18 }}>
          {[{id:'all',l:'Tout'},{id:'delivered',l:'Terminées'},{id:'cancelled',l:'Annulées'}].map(t => (
            <button key={t.id} role="tab" aria-selected={filter===t.id} onClick={()=>setFilter(t.id)} className={'lc-cat-tab' + (filter===t.id?' is-on':'')}>{t.l}</button>
          ))}
        </div>

        {/* [WEB-WIREUP 2026-06-26] Loading / empty / real-list states. */}
        {histErr && (
          <div className="lcf-field-error" role="alert" aria-live="assertive" style={{ marginBottom: 12 }}>
            <WC_I.close s={12}/> {histErr}
          </div>
        )}
        {loading ? (
          <div style={{ textAlign: 'center', padding: '56px 24px', background: 'var(--paper)', borderRadius: 22, boxShadow: 'var(--shadow-1)', color: 'var(--gray-3)' }}>
            Chargement de tes commandes…
          </div>
        ) : filtered.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '56px 24px', background: 'var(--paper)', borderRadius: 22, boxShadow: 'var(--shadow-1)' }}>
            <div style={{ fontSize: 48 }}>🍽️</div>
            <div style={{ fontSize: 16, fontWeight: 700, marginTop: 12 }}>Aucune commande pour l'instant — passe ta première commande !</div>
            <button className="lc-btn lc-btn--orange" style={{ marginTop: 20 }} onClick={()=>{ if (onRoute) onRoute('menu'); }}>Voir le menu <WC_I.arrow s={16}/></button>
          </div>
        ) : (
        <div style={{ display: 'grid', gap: 12 }}>
          {filtered.map((o, i) => {
            const pill = o.status === 'delivered'
              ? { bg: 'rgba(31,166,83,0.15)', c: 'var(--green-text)' }
              : o.status === 'cancelled'
              ? { bg: 'rgba(215,38,56,0.15)', c: 'var(--red-text)' }
              : { bg: 'rgba(255,90,31,0.15)', c: 'var(--orange-text)' };
            return (
            <Reveal key={o.id} delay={(i%4)+1}>
              <div style={{ background: 'var(--paper)', borderRadius: 22, padding: 24, boxShadow: 'var(--shadow-1)', display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
                <div style={{ width: 64, height: 64, borderRadius: 16, background: 'linear-gradient(135deg, var(--yellow), var(--orange))', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 32, flexShrink: 0 }}>{o.emoji}</div>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
                    <span className="lc-mono" style={{ fontSize: 12, fontWeight: 700, color: 'var(--gray-3)' }}>#{o.id}</span>
                    <span style={{ background: pill.bg, color: pill.c, padding: '3px 10px', borderRadius: 999, fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase' }}>
                      {o.statusName}
                    </span>
                  </div>
                  <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>{o.count} article{o.count > 1 ? 's' : ''}</div>
                  <div style={{ fontSize: 12, color: 'var(--gray-3)' }}>{fmtOrderDate(o.date)} · Hénin-Beaumont</div>
                </div>
                <div style={{ textAlign: 'right', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
                  <span className="lc-display" style={{ fontSize: 28, color: 'var(--orange)' }}>{o.total.toFixed(2).replace('.', ',')} €</span>
                  <button onClick={()=>{ if (onRoute) onRoute('menu'); }} className="lc-btn lc-btn--ink" style={{ padding: '10px 18px', fontSize: 12 }}>Voir le menu</button>
                </div>
              </div>
            </Reveal>
            );
          })}
        </div>
        )}
      </div>
    </div>
  );
}

window.OrdersPage = OrdersPage;
