// Track Order page
const { useState: useState4, useMemo: useMemo4 } = React;

const STAGES = [
  'Placed',
  'Processing',
  'Packed',
  'Shipped',
  'Out for Delivery',
  'Delivered',
];

function getStageIndex(order) {
  const placed = new Date(order.placedAt).getTime();
  const now = Date.now();
  const elapsedH = (now - placed) / 36e5;
  const etaDays = order.details && order.details.shipping === 'express' ? 2 : 4;
  const etaMs = placed + etaDays * 864e5;

  if (order.status === 'cancelled') return -1;
  if (now >= etaMs) return 5;
  if (elapsedH >= 48) return 4;
  if (elapsedH >= 24) return 3;
  if (elapsedH >= 6) return 2;
  if (elapsedH >= 1) return 1;
  return 0;
}

function stageTimestamp(order, stageIdx) {
  const placed = new Date(order.placedAt).getTime();
  const offsets = [0, 1, 6, 24, 48, 96]; // hours after placed
  const t = placed + offsets[stageIdx] * 36e5;
  if (t > Date.now()) return null;
  return new Date(t).toLocaleString('en-PK', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
}

function Timeline({ order }) {
  const current = getStageIndex(order);

  return (
    <div style={{ margin: '32px 0' }}>
      {STAGES.map((label, i) => {
        const done = i < current;
        const active = i === current;
        const ts = stageTimestamp(order, i);
        return (
          <div key={label} style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 24 }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: 24, flexShrink: 0 }}>
              <div style={{
                width: 24, height: 24, borderRadius: '50%',
                background: done ? 'var(--color-accent)' : active ? 'var(--color-accent)' : 'var(--color-border)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
                boxShadow: active ? '0 0 0 4px rgba(107,31,38,.18)' : 'none',
                animation: active ? 'pulse 1.4s ease-in-out infinite' : 'none',
              }}>
                {done && (
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                    <path d="M2 6l3 3 5-5" stroke="#f7f0e0" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                )}
              </div>
              {i < STAGES.length - 1 && (
                <div style={{ width: 1, flex: 1, minHeight: 20, background: done ? 'var(--color-accent)' : 'var(--color-border)', marginTop: 2 }} />
              )}
            </div>
            <div style={{ paddingTop: 2 }}>
              <div style={{ fontWeight: active ? 700 : 500, color: (done || active) ? 'var(--color-ink)' : 'var(--color-text-mute)', fontSize: 15 }}>{label}</div>
              {ts && <div style={{ fontSize: 12, color: 'var(--color-text-mute)', marginTop: 2 }}>{ts}</div>}
            </div>
          </div>
        );
      })}
      <style>{`@keyframes pulse { 0%,100%{box-shadow:0 0 0 4px rgba(107,31,38,.18)}50%{box-shadow:0 0 0 8px rgba(107,31,38,.08)} }`}</style>
    </div>
  );
}

function OrderSummary({ order }) {
  const products = window.PRODUCTS || [];
  const etaDays = order.details && order.details.shipping === 'express' ? 2 : 4;
  const eta = new Date(new Date(order.placedAt).getTime() + etaDays * 864e5);

  return (
    <div style={{ background: 'var(--color-paper-2)', border: '1px solid var(--color-border)', borderRadius: 4, padding: 24, marginTop: 8 }}>
      <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 16 }}>Order Summary</div>
      {order.items && order.items.map((item, i) => {
        const p = products.find(x => x.id === item.id);
        if (!p) return null;
        return (
          <div key={i} style={{ display: 'flex', gap: 12, marginBottom: 12, alignItems: 'center' }}>
            <img src={p.img} alt={p.name} style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 2 }} />
            <div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{p.name}</div>
              {item.size && <div style={{ fontSize: 12, color: 'var(--color-text-mute)' }}>Size: {item.size}</div>}
              <div style={{ fontSize: 12, color: 'var(--color-text-mute)' }}>Qty: {item.qty}</div>
            </div>
          </div>
        );
      })}
      <div style={{ borderTop: '1px solid var(--color-border)', paddingTop: 12, marginTop: 4 }}>
        {order.details && order.details.address && (
          <div style={{ fontSize: 13, marginBottom: 8 }}>
            <span style={{ color: 'var(--color-text-mute)' }}>Shipping to: </span>
            {[order.details.address.first, order.details.address.last].filter(Boolean).join(' ')}<br/>
            {order.details.address.street}{order.details.address.apt ? ', ' + order.details.address.apt : ''}<br/>
            {order.details.address.city}, {order.details.address.state} {order.details.address.pin}
          </div>
        )}
        {order.details && order.details.payment && (
          <div style={{ fontSize: 13, marginBottom: 8 }}>
            <span style={{ color: 'var(--color-text-mute)' }}>Payment: </span>
            {order.details.payment}
          </div>
        )}
        <div style={{ fontSize: 13, marginBottom: 8 }}>
          <span style={{ color: 'var(--color-text-mute)' }}>Total: </span>
          <strong>{fmt(order.total)}</strong>
        </div>
        <div style={{ fontSize: 13 }}>
          <span style={{ color: 'var(--color-text-mute)' }}>Estimated delivery: </span>
          {eta.toLocaleDateString('en-PK', { weekday: 'long', day: 'numeric', month: 'long' })}
        </div>
      </div>
    </div>
  );
}

function CancelModal({ onConfirm, onClose }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999
    }} onClick={onClose}>
      <div style={{
        background: '#fff', borderRadius: 4, padding: 32, maxWidth: 400, width: '90%'
      }} onClick={e => e.stopPropagation()}>
        <h3 style={{ marginBottom: 12 }}>Cancel this order?</h3>
        <p style={{ color: 'var(--color-text-mute)', fontSize: 14, marginBottom: 24 }}>
          This action cannot be undone. Your refund will be processed in 5–7 business days.
        </p>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
          <button className="btn" onClick={onClose}>Keep Order</button>
          <button className="btn btn-primary" onClick={onConfirm} style={{ background: 'var(--color-accent)' }}>
            Yes, Cancel
          </button>
        </div>
      </div>
    </div>
  );
}

function TrackOrderPage({ route: routeProp }) {
  const { orders, navigate, route, cancelOrder } = useStore();
  const toast = useToast();
  const [input, setInput] = useState4((routeProp && routeProp.orderId) || (route && route.orderId) || '');
  const [searched, setSearched] = useState4(false);
  const [showCancel, setShowCancel] = useState4(false);

  const valid = /^SAN\d{6}$/.test(input.trim());

  const found = useMemo4(() => {
    if (!searched) return null;
    return orders.find(o => o.id === input.trim().toUpperCase()) || null;
  }, [searched, input, orders]);

  function handleTrack() {
    if (!valid) return;
    setSearched(true);
    if (!orders.find(o => o.id === input.trim().toUpperCase())) {
      toast('Order not found');
    }
  }

  function handleCancel() {
    const ord = found;
    if (!ord) return;
    cancelOrder(ord.id);
    setShowCancel(false);
    toast('Order cancelled. Refund will be processed in 5–7 days.');
  }

  const displayOrder = found || null;
  const stageIdx = displayOrder ? getStageIndex(displayOrder) : -1;
  const canCancel = displayOrder && displayOrder.status !== 'cancelled' && stageIdx >= 0 && stageIdx <= 1;

  return (
    <div className="container" style={{ maxWidth: 640, padding: '40px 16px 80px' }}>
      <div className="crumbs" style={{ marginBottom: 24 }}>
        <a onClick={() => navigate({ name: 'home' })}>Home</a>
        <span className="sep">/</span>
        <span className="current">Track Order</span>
      </div>

      <div className="eyebrow-gold" style={{ marginBottom: 8 }}>Order Status</div>
      <h1 style={{ fontSize: 28, marginBottom: 8 }}>Track Your Order</h1>
      <p style={{ color: 'var(--color-text-mute)', fontSize: 14, marginBottom: 32 }}>
        Enter your order number to see status. Order numbers begin with SAN.
      </p>

      <div style={{ display: 'flex', gap: 12, marginBottom: 32 }}>
        <div className="field" style={{ flex: 1, marginBottom: 0 }}>
          <input
            className="input"
            type="text"
            placeholder="e.g. SAN123456"
            value={input}
            onChange={e => { setInput(e.target.value.toUpperCase()); setSearched(false); }}
            onKeyDown={e => { if (e.key === 'Enter' && valid) handleTrack(); }}
            style={{ width: '100%' }}
          />
        </div>
        <button
          className="btn btn-primary"
          disabled={!valid}
          onClick={handleTrack}
          style={{ flexShrink: 0 }}
        >
          Track
        </button>
      </div>

      {searched && !found && (
        <div className="empty-state" style={{ textAlign: 'left', paddingLeft: 0, paddingRight: 0 }}>
          <p style={{ fontWeight: 600, marginBottom: 8 }}>Order not found.</p>
          <p style={{ color: 'var(--color-text-mute)', fontSize: 14 }}>
            Need help? Contact <strong>+92 51 272 8463</strong> or{' '}
            <a href="mailto:hello@saanchashoes.shop">hello@saanchashoes.shop</a>
          </p>
        </div>
      )}

      {displayOrder && (
        <>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
            <div>
              <div style={{ fontSize: 13, color: 'var(--color-text-mute)' }}>Order #{displayOrder.id}</div>
              {displayOrder.status === 'cancelled' && (
                <div style={{ color: 'var(--color-accent)', fontWeight: 700, fontSize: 14, marginTop: 4 }}>Cancelled</div>
              )}
            </div>
            {canCancel && (
              <button
                className="btn"
                onClick={() => setShowCancel(true)}
                style={{ fontSize: 13, color: 'var(--color-accent)' }}
              >
                Cancel Order
              </button>
            )}
          </div>

          {displayOrder.status !== 'cancelled' && <Timeline order={displayOrder} />}

          <OrderSummary order={displayOrder} />
        </>
      )}

      {showCancel && <CancelModal onConfirm={handleCancel} onClose={() => setShowCancel(false)} />}
    </div>
  );
}

window.TrackOrderPage = TrackOrderPage;
