/* Order tracking page — timeline dots matching order-success style */

const OrderLookup = () => {
  const { lang } = useLang();
  const route = useRoute();
  const token = (route.split('/order/')[1] || '').split('?')[0].split('#')[0].trim();
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    if (!token) { setError(lang === 'en' ? 'No order token.' : 'Nessun token ordine.'); setLoading(false); return; }
    let cancelled = false;
    fetch(`/api/order/${encodeURIComponent(token)}`)
      .then((r) => r.json())
      .then((result) => {
        if (cancelled) return;
        if (result.ok) setData(result.order);
        else setError(result.error || (lang === 'en' ? 'Order not found.' : 'Ordine non trovato.'));
      })
      .catch(() => { if (!cancelled) setError(lang === 'en' ? 'Could not load order.' : 'Impossibile caricare l\'ordine.'); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [token]);

  const statusLabels = {
    pending_payment: lang === 'en' ? 'Awaiting payment' : 'In attesa pagamento',
    cash_received: lang === 'en' ? 'In production' : 'In produzione',
    ready_for_pickup: lang === 'en' ? 'Ready for pickup' : 'Pronto per il ritiro',
    collected: lang === 'en' ? 'Collected' : 'Ritirato',
    abandoned: lang === 'en' ? 'Closed' : 'Chiuso',
    cancelled: lang === 'en' ? 'Cancelled' : 'Annullato'
  };

  if (loading) {
    return <section className="section"><div className="container stack" style={{ gap: 18, maxWidth: 700, margin: '0 auto', textAlign: 'center' }}>
      <p className="lead">{lang === 'en' ? 'Loading order…' : 'Caricamento ordine…'}</p>
    </div></section>;
  }

  if (error) {
    return <section className="section"><div className="container stack" style={{ gap: 18, maxWidth: 700, margin: '0 auto', textAlign: 'center' }}>
      <div className="eyebrow">{lang === 'en' ? 'Order tracking' : 'Tracking ordine'}</div>
      <h1 className="h-1">{error}</h1>
      <Link to="/" className="btn btn-secondary">{lang === 'en' ? 'Back to site' : 'Torna al sito'}</Link>
    </div></section>;
  }

  if (!data) return null;

  const statusLabel = statusLabels[data.status] || data.status;

  return (
    <section className="section">
      <div className="container stack" style={{ gap: 24, maxWidth: 700, margin: '0 auto' }}>
        <div>
          <div className="eyebrow">{lang === 'en' ? 'Order' : 'Ordine'} {data.orderNumber}</div>
          <h1 className="h-1">{statusLabel}</h1>
        </div>

        {/* Timeline with dots */}
        <OrderTimeline status={data.status} lang={lang} />

        {/* Customer + order info */}
        <div className="surface-plain stack" style={{ padding: 22 }}>
          <SpecRow k={lang === 'en' ? 'Name' : 'Nome'} v={data.name || '—'} />
          <SpecRow k={lang === 'en' ? 'Email' : 'Email'} v={data.email || '—'} />
          <SpecRow k={lang === 'en' ? 'Order number' : 'Numero ordine'} v={data.orderNumber || '—'} />
        </div>

        {/* Items */}
        <div className="surface-plain stack" style={{ padding: 22 }}>
          <h3 className="h-3">{lang === 'en' ? 'Items' : 'Articoli'}</h3>
          {(data.items || []).map((item, idx) => (
            <div key={idx} style={{ paddingBottom: 14, borderBottom: idx === (data.items || []).length - 1 ? 0 : '1px solid var(--border)' }}>
              <SpecRow k={lang === 'en' ? 'Product' : 'Prodotto'} v={item.name || '—'} />
              <SpecRow k={lang === 'en' ? 'Body' : 'Corpo'} v={item.bodyColor || '—'} />
              <SpecRow k={lang === 'en' ? 'Cap' : 'Cappuccio'} v={item.capColor || '—'} />
              {item.customText && <SpecRow k={lang === 'en' ? 'Text' : 'Testo'} v={item.customText} />}
              {item.emoji && <SpecRow k="Emoji" v={item.emoji} />}
              <SpecRow k={lang === 'en' ? 'Quantity' : 'Quantità'} v={String(item.quantity || 1)} />
              {item.totalCents != null && <SpecRow k={lang === 'en' ? 'Price' : 'Prezzo'} v={fmtEur(item.totalCents)} />}
            </div>
          ))}
          <div style={{ textAlign: 'right', marginTop: 8 }}>
            <strong>{lang === 'en' ? 'Total' : 'Totale'}: {fmtEur(data.totalCents)}</strong>
          </div>
        </div>

        <div className="row wrap">
          <Link to="/configurator" className="btn btn-secondary">{lang === 'en' ? 'Configure yours' : 'Personalizza la tua'}</Link>
          <Link to="/contact" className="btn btn-secondary">{lang === 'en' ? 'Contact' : 'Contatti'}</Link>
        </div>
      </div>
    </section>
  );
};

const OrderTimeline = ({ status, lang }) => {
  const steps = lang === 'en'
    ? ['Received', 'Awaiting payment', 'In production', 'Ready', 'Collected']
    : ['Ricevuto', 'In attesa pagamento', 'In produzione', 'Pronto', 'Ritirato'];
  const indexMap = {
    pending_payment: 1, cash_received: 2, ready_for_pickup: 3, collected: 4,
    cancelled: -1, abandoned: 3
  };
  const current = indexMap[status] != null ? indexMap[status] : 1;
  return (
    <div className="surface-plain" style={{ padding: 22 }}>
      <div className="order-timeline">
        {steps.map((label, idx) => (
          <div key={label} className={'order-timeline-step' + (idx <= current && current >= 0 ? ' done' : '') + (idx === current ? ' current' : '')}>
            <span className="order-timeline-dot"></span>
            <span>{label}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

window.OrderLookup = OrderLookup;
