// pages/track.jsx — public order tracking + client portal entry

function TrackPage() {
  const route = useRoute();
  const store = useStore();
  const initial = route.query.o || '';
  const [orderId, setOrderId] = React.useState(initial);
  const [query, setQuery] = React.useState(initial);
  const [phone4, setPhone4] = React.useState('');
  const [remoteOrder, setRemoteOrder] = React.useState(null);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => { setQuery(route.query.o || ''); setOrderId(route.query.o || ''); }, [route.query.o]);

  React.useEffect(() => {
    if (!query || !(window.APG_CONFIG && window.APG_CONFIG.useRemote && window.APGRemote)) {
      setRemoteOrder(null);
      return;
    }
    setLoading(true);
    window.APGRemote.trackOrder(query, phone4 || undefined)
      .then(res => setRemoteOrder(res.order))
      .catch(() => setRemoteOrder(null))
      .finally(() => setLoading(false));
  }, [query, phone4]);

  const orders = (window.APG ? APG.getOrders() : (store.state.orders || []));
  const raw = query ? orders.find((o) => o.id.toLowerCase() === query.trim().toLowerCase()) : null;
  let order = remoteOrder;
  let gate = null;
  if (!order && raw) {
    const user = store.state.user;
    if (user) {
      const access = window.CustomerAccount.getOrderForViewer(raw.id, user);
      if (access.ok) order = access.order;
      else {
        const guest = window.CustomerAccount.guestTrack(raw.id, phone4);
        if (guest.ok) order = guest.order;
        else gate = guest.code === 'PHONE_REQUIRED' || guest.code === 'FORBIDDEN'
          ? 'Enter the last 4 digits of the phone used at checkout to view this order.'
          : 'Unable to verify access to this order.';
      }
    } else {
      const guest = window.CustomerAccount.guestTrack(raw.id, phone4);
      if (guest.ok) order = guest.order;
      else gate = 'Enter the last 4 digits of the checkout phone to view order details.';
    }
  }

  const FLOW = ['new', 'packed', 'shipped', 'out_for_delivery', 'delivered'];
  const LABEL = { new: 'Order placed', packed: 'Packed', shipped: 'Shipped', out_for_delivery: 'Out for delivery', delivered: 'Delivered' };

  return (
    <main className="container" style={{ paddingBlock: 48, maxWidth: 820 }}>
      <div className="crumb" style={{ marginBottom: 16 }}><a href="#/">Home</a><span className="sep">/</span><span className="here">Track order</span></div>
      <span className="eyebrow">Customer portal</span>
      <h1 className="serif" style={{ fontSize: 'var(--fs-hero)', lineHeight: 1, marginBlock: 8 }}>Track your order</h1>
      <p style={{ color: 'var(--ink-2)', marginBottom: 28 }}>Enter your order number. Guests must verify with phone last-4. Timeline shows only stored events — never fabricated tracking.</p>

      <form onSubmit={(e) => { e.preventDefault(); setQuery(orderId); }} style={{ display: 'flex', gap: 10, marginBottom: 16, maxWidth: 560, flexWrap: 'wrap' }}>
        <input className="input input--lg" placeholder="APG-100200" value={orderId} onChange={(e) => setOrderId(e.target.value)} style={{ flex: 1, minWidth: 160 }} />
        <input className="input input--lg" placeholder="Phone last 4" value={phone4} onChange={(e) => setPhone4(e.target.value.replace(/\D/g, '').slice(0, 4))} style={{ width: 140 }} aria-label="Phone last 4 digits" />
        <button className="btn btn--primary btn--lg" type="submit" disabled={loading}>{loading ? '…' : 'Track'}</button>
      </form>

      {query && !order && (
        <div style={{ background: 'var(--cream)', borderRadius: 16, padding: 32, textAlign: 'center' }}>
          <h3 className="serif" style={{ fontSize: '1.4rem' }}>{gate ? 'Verify to continue' : 'No order found'}</h3>
          <p style={{ color: 'var(--muted)', marginTop: 8 }}>{gate || "We couldn't find an order with that number."}</p>
          <a className="btn btn--secondary" style={{ marginTop: 14 }} href="https://wa.me/917559907176" target="_blank" rel="noreferrer">
            <Icon name="whatsapp" size={16} /> WhatsApp us
          </a>
        </div>
      )}

      {order && !order.awb && order.status !== 'delivered' && order.status !== 'cancelled' && (
        <p style={{ fontSize: '.85rem', color: 'var(--muted)', marginBottom: 12 }}>Tracking will appear once your order is dispatched.</p>
      )}
      {order && (
        <div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 28 }} className="track-meta">
            <div style={{ background: 'var(--cream)', borderRadius: 16, padding: 24 }}>
              <div className="eyebrow">Order</div>
              <div className="serif" style={{ fontSize: '1.6rem' }}>{order.id}</div>
              <div style={{ color: 'var(--muted)', fontSize: '.85rem', marginTop: 4 }}>Placed {new Date(order.placedAt).toLocaleDateString('en-IN', { dateStyle: 'medium' })}</div>
            </div>
            <div style={{ background: order.status === 'delivered' ? 'var(--forest)' : 'var(--ink)', color: 'var(--paper)', borderRadius: 16, padding: 24 }}>
              <div className="eyebrow" style={{ color: 'var(--sage)' }}>Current status</div>
              <div className="serif" style={{ fontSize: '1.6rem' }}>{LABEL[order.status] || order.status}</div>
              {order.courier && <div style={{ fontSize: '.85rem', color: 'rgba(255,255,255,.75)', marginTop: 4 }}>{order.courier} · {order.awb}</div>}
            </div>
          </div>

          {order.status === 'cancelled' ? (
            <div style={{ background: 'var(--cream)', borderRadius: 16, padding: 24, textAlign: 'center', color: 'var(--danger)' }}>This order was cancelled.</div>
          ) : (
            <div style={{ display: 'flex', justifyContent: 'space-between', position: 'relative', marginBottom: 36, marginTop: 12 }}>
              <div style={{ position: 'absolute', top: 18, left: 24, right: 24, height: 3, background: 'var(--line-strong)' }}></div>
              <div style={{ position: 'absolute', top: 18, left: 24, height: 3, background: 'var(--forest)', width: `calc((100% - 48px) * ${FLOW.indexOf(order.status) / (FLOW.length - 1)})`, transition: 'width .4s' }}></div>
              {FLOW.map((st, i) => {
                const done = i <= FLOW.indexOf(order.status);
                const tl = (order.timeline || []).find(t => t.status === st);
                return (
                  <div key={st} style={{ position: 'relative', textAlign: 'center', flex: 1, zIndex: 1 }}>
                    <div style={{ width: 38, height: 38, borderRadius: 999, margin: '0 auto', display: 'grid', placeItems: 'center', background: done ? 'var(--forest)' : 'var(--paper)', color: done ? 'var(--paper)' : 'var(--muted)', border: '2px solid ' + (done ? 'var(--forest)' : 'var(--line-strong)') }}>
                      {done ? <Icon name="check" size={16} /> : <span style={{ width: 7, height: 7, borderRadius: 9, background: 'currentColor' }}></span>}
                    </div>
                    <div style={{ fontSize: '.74rem', marginTop: 8, fontWeight: done ? 600 : 400, color: done ? 'var(--ink)' : 'var(--muted)' }}>{LABEL[st]}</div>
                    {tl && <div style={{ fontSize: '.66rem', color: 'var(--muted)', marginTop: 2 }}>{new Date(tl.at).toLocaleDateString('en-IN', { day: 'numeric', month: 'short' })}</div>}
                  </div>
                );
              })}
            </div>
          )}

          {/* items */}
          <h3 className="serif" style={{ fontSize: '1.3rem', marginBottom: 12 }}>Items</h3>
          <div style={{ background: 'var(--shell)', border: '1px solid var(--line)', borderRadius: 16, overflow: 'hidden' }}>
            {order.lines.map(l => (
              <div key={l.productId + l.variant} style={{ display: 'flex', gap: 14, padding: 16, borderBottom: '1px solid var(--line)', alignItems: 'center' }}>
                <div style={{ width: 56, height: 64, borderRadius: 8, overflow: 'hidden', background: 'var(--cream)' }}>
                  <img src={l.product.image} alt={l.product.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                </div>
                <div style={{ flex: 1 }}>
                  <div className="serif" style={{ fontSize: '1rem' }}>{l.product.name}</div>
                  <div style={{ fontSize: '.78rem', color: 'var(--muted)' }}>{l.variant} · qty {l.qty}</div>
                </div>
                <div style={{ fontSize: '.9rem' }}>{HAP.formatPrice(l.line)}</div>
              </div>
            ))}
            <div className="spread" style={{ padding: 16, fontFamily: 'var(--serif)', fontSize: '1.2rem' }}>
              <span>Total</span><span>{HAP.formatPrice(order.total)}</span>
            </div>
          </div>

          <div style={{ marginTop: 24, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <a className="btn btn--secondary" href="https://wa.me/917559907176" target="_blank" rel="noreferrer"><Icon name="whatsapp" size={16} /> Need help?</a>
            <a className="btn btn--ghost" href="#/account/orders">My orders</a>
          </div>
        </div>
      )}
      <style>{`@media (max-width:600px){ .track-meta { grid-template-columns: 1fr !important; } }`}</style>
    </main>
  );
}
window.TrackPage = TrackPage;
