// Orders history screen
function OrdersScreen({ navigate, user, isMobile }) {
  const P = window.POP;
  const [orders, setOrders] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [expandedId, setExpandedId] = React.useState(null);

  const fmt     = n => Number(n).toLocaleString('es-UY');
  const fmtDate = d => new Date(d).toLocaleDateString('es-UY', { day: 'numeric', month: 'short', year: 'numeric' });

  React.useEffect(() => {
    if (!user?.id || !window.sb) { setLoading(false); return; }
    window.sb
      .from('orders')
      .select('id, status, subtotal, shipping, discount, total, created_at, shipping_address, order_items(id, name, price, qty, sku, product_id)')
      .eq('user_id', user.id)
      .order('created_at', { ascending: false })
      .then(({ data, error }) => {
        if (!error && data) setOrders(data);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [user?.id]);

  const STATUS = {
    pending:   { label: 'Pendiente',   icon: '🕐', bg: '#fff3b0', fg: P.ink },
    paid:      { label: 'Pagado',      icon: '✅', bg: P.green,   fg: P.card },
    shipped:   { label: 'En camino',   icon: '🚚', bg: P.blue,    fg: P.card },
    delivered: { label: 'Entregado',   icon: '🏠', bg: '#0bb36a', fg: P.card },
    cancelled: { label: 'Cancelado',   icon: '✗',  bg: P.red,     fg: P.card },
  };

  // ── No logueado ──────────────────────────────────────────────────────────
  if (!user) {
    return (
      <div className="pop-page-in" style={{ padding: isMobile ? 24 : 64, textAlign: 'center' }}>
        <div style={{ fontSize: 72, lineHeight: 1 }}>🔐</div>
        <div style={{ fontFamily: P.display, fontSize: isMobile ? 28 : 44, letterSpacing: -1.5, marginTop: 16 }}>
          INICIA SESIÓN
        </div>
        <div style={{ fontSize: 14, color: P.dim, marginTop: 8, maxWidth: 380, margin: '8px auto 0', lineHeight: 1.6 }}>
          Para ver tu historial de pedidos necesitas tener una cuenta MAGIC CELL.
        </div>
        <div style={{ marginTop: 24, display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
          <PopButton variant="dark" size="lg" onClick={() => navigate('home')}>← Volver al inicio</PopButton>
        </div>
      </div>
    );
  }

  // ── Loading skeletons ────────────────────────────────────────────────────
  const Skeleton = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {[1, 2, 3].map(i => (
        <div key={i} className="pop-shimmer" style={{ height: 80, borderRadius: 14 }} />
      ))}
    </div>
  );

  return (
    <div className="pop-page-in" style={{ padding: isMobile ? 16 : 32, maxWidth: 900, margin: '0 auto' }}>

      {/* Breadcrumb */}
      <div style={{ fontSize: 11, color: P.dim, letterSpacing: 0.5, marginBottom: 6 }}>
        <span onClick={() => navigate('home')} style={{ cursor: 'pointer', textDecoration: 'underline' }}>Inicio</span>
        {' › '}Mi cuenta › Pedidos
      </div>

      {/* Title row */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
        marginBottom: isMobile ? 20 : 28, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div style={{ fontFamily: P.display, fontSize: isMobile ? 32 : 52, letterSpacing: -2, lineHeight: 1 }}>
            📦 MIS PEDIDOS
          </div>
          {!loading && (
            <div style={{ fontSize: 13, color: P.dim, marginTop: 6 }}>
              {user.name} · {orders.length} pedido{orders.length !== 1 ? 's' : ''}
            </div>
          )}
        </div>
        <PopButton variant="secondary" size="md" onClick={() => navigate('listing')}>
          🛍 Seguir comprando
        </PopButton>
      </div>

      {loading && <Skeleton />}

      {/* Empty state */}
      {!loading && orders.length === 0 && (
        <div style={{ textAlign: 'center', padding: '72px 24px', background: P.card,
          border: `2px dashed ${P.ink}`, borderRadius: 20 }}>
          <div style={{ fontSize: 72, lineHeight: 1 }}>🛍</div>
          <div style={{ fontFamily: P.display, fontSize: isMobile ? 24 : 32, marginTop: 16, letterSpacing: -0.5 }}>
            Aún no tienes pedidos
          </div>
          <div style={{ fontSize: 13, color: P.dim, marginTop: 8, maxWidth: 360, margin: '8px auto 0' }}>
            ¡Explora el catálogo y estrena tu primera compra!
          </div>
          <div style={{ marginTop: 24, display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
            <PopButton variant="dark" size="lg" onClick={() => navigate('listing', { category: 'Ofertas' })}>
              🔥 VER OFERTAS
            </PopButton>
            <PopButton variant="secondary" size="lg" onClick={() => navigate('listing')}>
              Ver catálogo
            </PopButton>
          </div>
        </div>
      )}

      {/* Orders list */}
      {!loading && orders.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {orders.map((order, i) => {
            const st = STATUS[order.status] || { label: order.status, icon: '·', bg: P.cream, fg: P.ink };
            const isExpanded = expandedId === order.id;
            const addr = order.shipping_address;
            const items = order.order_items || [];

            return (
              <div key={order.id} className="pop-fade-up" style={{
                background: P.card, border: `2px solid ${P.ink}`, borderRadius: 16,
                boxShadow: `4px 4px 0 ${P.ink}`, overflow: 'hidden',
                animationDelay: `${Math.min(i, 6) * 0.06}s`,
              }}>

                {/* ── Cabecera del pedido ── */}
                <div
                  onClick={() => setExpandedId(isExpanded ? null : order.id)}
                  style={{ padding: isMobile ? '14px 16px' : '16px 22px',
                    display: 'flex', alignItems: 'center', gap: isMobile ? 10 : 16,
                    flexWrap: 'wrap', cursor: 'pointer', userSelect: 'none',
                    borderBottom: isExpanded ? `2px dashed ${P.line2}` : 'none',
                  }}
                >
                  {/* Status badge */}
                  <div style={{ padding: '4px 10px', borderRadius: 8, background: st.bg, color: st.fg,
                    border: `2px solid ${P.ink}`, boxShadow: `2px 2px 0 ${P.ink}`,
                    fontFamily: P.display, fontSize: 11, letterSpacing: 0.5, flexShrink: 0 }}>
                    {st.icon} {st.label.toUpperCase()}
                  </div>

                  {/* Meta */}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                      <span style={{ fontFamily: 'ui-monospace,monospace', fontSize: 11, color: P.dim }}>
                        #{order.id.slice(0, 8).toUpperCase()}
                      </span>
                      <span style={{ fontSize: 11, color: P.dim }}>· {fmtDate(order.created_at)}</span>
                      {items.length > 0 && (
                        <span style={{ fontSize: 11, color: P.dim }}>
                          · {items.length} producto{items.length !== 1 ? 's' : ''}
                        </span>
                      )}
                    </div>
                    {/* Items preview — nombres en una línea */}
                    {items.length > 0 && !isExpanded && (
                      <div style={{ fontSize: 12, color: P.ink2, marginTop: 3, fontWeight: 500,
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: isMobile ? 180 : 420 }}>
                        {items.map(it => it.name).join(' · ')}
                      </div>
                    )}
                  </div>

                  {/* Total + chevron */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
                    <span style={{ fontFamily: P.display, fontSize: isMobile ? 18 : 22, letterSpacing: -0.5 }}>
                      ${fmt(order.total)}
                    </span>
                    <span style={{ fontSize: 18, color: P.dim, lineHeight: 1,
                      transition: 'transform .25s', transform: isExpanded ? 'rotate(180deg)' : 'none',
                      display: 'inline-block' }}>▾</span>
                  </div>
                </div>

                {/* ── Detalle expandido ── */}
                {isExpanded && (
                  <div className="pop-page-in" style={{ padding: isMobile ? '16px 16px' : '20px 22px' }}>

                    {/* Productos */}
                    {items.length > 0 && (
                      <div style={{ marginBottom: 16 }}>
                        <div style={{ fontFamily: P.display, fontSize: 11, letterSpacing: 0.5, color: P.dim, marginBottom: 10 }}>
                          PRODUCTOS
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                          {items.map(item => {
                            // Intentar obtener imagen del catálogo cargado en memoria
                            const memProduct = (window.POP_PRODUCTS || []).find(p =>
                              String(p.id) === String(item.product_id)
                            );
                            return (
                              <div key={item.id} style={{ display: 'flex', alignItems: 'center', gap: 12,
                                padding: '10px 12px', background: P.cream, borderRadius: 10,
                                border: `1.5px solid ${P.line2}` }}>
                                {/* Thumbnail */}
                                <div style={{ width: 44, height: 44, flexShrink: 0, borderRadius: 8,
                                  border: `1.5px solid ${P.line2}`, overflow: 'hidden',
                                  background: getCategoryTone(memProduct?.category) }}>
                                  {memProduct?.image_url
                                    ? <img src={memProduct.image_url} alt={item.name}
                                        style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 4 }} />
                                    : <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', fontSize: 20 }}>📦</div>
                                  }
                                </div>
                                {/* Info */}
                                <div style={{ flex: 1, minWidth: 0 }}>
                                  <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.3,
                                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                    {item.name}
                                  </div>
                                  {item.sku && (
                                    <div style={{ fontSize: 10, color: P.dim, fontFamily: 'ui-monospace,monospace' }}>
                                      SKU: {item.sku}
                                    </div>
                                  )}
                                </div>
                                {/* Precio */}
                                <div style={{ flexShrink: 0, textAlign: 'right' }}>
                                  <div style={{ fontSize: 11, color: P.dim }}>{item.qty} × ${fmt(item.price)}</div>
                                  <div style={{ fontFamily: P.display, fontSize: 15, letterSpacing: -0.5 }}>
                                    ${fmt(item.price * item.qty)}
                                  </div>
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    )}

                    {/* Resumen + Dirección */}
                    <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 12, marginBottom: 14 }}>

                      {/* Desglose de precio */}
                      <div style={{ padding: '14px 16px', background: P.cream, borderRadius: 12,
                        border: `1.5px solid ${P.line2}`, fontSize: 13 }}>
                        <div style={{ fontFamily: P.display, fontSize: 11, letterSpacing: 0.5, color: P.dim, marginBottom: 10 }}>
                          RESUMEN DE PAGO
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                            <span style={{ color: P.dim }}>Subtotal</span>
                            <span style={{ fontWeight: 600 }}>${fmt(order.subtotal)}</span>
                          </div>
                          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                            <span style={{ color: P.dim }}>Envío</span>
                            <span style={{ fontWeight: 600, color: order.shipping === 0 ? P.green : P.ink }}>
                              {order.shipping === 0 ? '¡GRATIS!' : `$${fmt(order.shipping)}`}
                            </span>
                          </div>
                          {order.discount > 0 && (
                            <div style={{ display: 'flex', justifyContent: 'space-between', color: P.green }}>
                              <span>Descuento</span>
                              <span style={{ fontWeight: 700 }}>-${fmt(order.discount)}</span>
                            </div>
                          )}
                          <div style={{ display: 'flex', justifyContent: 'space-between',
                            borderTop: `1.5px dashed ${P.line2}`, paddingTop: 8, marginTop: 2 }}>
                            <span style={{ fontFamily: P.display, fontSize: 14 }}>TOTAL</span>
                            <span style={{ fontFamily: P.display, fontSize: 18, letterSpacing: -0.5 }}>
                              ${fmt(order.total)}
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Dirección de entrega */}
                      {addr && (
                        <div style={{ padding: '14px 16px', background: P.cream, borderRadius: 12,
                          border: `1.5px solid ${P.line2}`, fontSize: 13 }}>
                          <div style={{ fontFamily: P.display, fontSize: 11, letterSpacing: 0.5, color: P.dim, marginBottom: 10 }}>
                            DIRECCIÓN DE ENTREGA
                          </div>
                          <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
                            {addr.name && <div style={{ fontWeight: 600 }}>{addr.name}</div>}
                            {addr.address && <div style={{ color: P.ink2 }}>{addr.address}</div>}
                            {(addr.city || addr.zip) && (
                              <div style={{ color: P.ink2 }}>{[addr.city, addr.zip].filter(Boolean).join(' ')}</div>
                            )}
                            {addr.phone && (
                              <div style={{ color: P.dim, marginTop: 4, fontSize: 12 }}>📞 {addr.phone}</div>
                            )}
                            {addr.email && (
                              <div style={{ color: P.dim, fontSize: 12 }}>✉ {addr.email}</div>
                            )}
                          </div>
                        </div>
                      )}
                    </div>

                    {/* Status timeline */}
                    <div style={{ padding: '14px 16px', background: P.card, border: `2px solid ${P.line2}`,
                      borderRadius: 12, marginBottom: 14 }}>
                      <div style={{ fontFamily: P.display, fontSize: 11, letterSpacing: 0.5, color: P.dim, marginBottom: 12 }}>
                        ESTADO DEL PEDIDO
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
                        {[
                          { key: 'pending',   label: 'Confirmado', icon: '✓' },
                          { key: 'paid',      label: 'Pagado',     icon: '💳' },
                          { key: 'shipped',   label: 'En camino',  icon: '🚚' },
                          { key: 'delivered', label: 'Entregado',  icon: '🏠' },
                        ].map((step, idx, arr) => {
                          const statusOrder = ['pending', 'paid', 'shipped', 'delivered'];
                          const currentIdx = statusOrder.indexOf(order.status);
                          const stepIdx   = statusOrder.indexOf(step.key);
                          const done  = stepIdx <= currentIdx;
                          const active = stepIdx === currentIdx;
                          return (
                            <React.Fragment key={step.key}>
                              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, flexShrink: 0 }}>
                                <div style={{ width: isMobile ? 28 : 36, height: isMobile ? 28 : 36, borderRadius: '50%',
                                  background: done ? P.green : P.cream, color: done ? P.card : P.dim,
                                  border: `2px solid ${done ? P.ink : P.line2}`,
                                  boxShadow: active ? `3px 3px 0 ${P.ink}` : 'none',
                                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                                  fontSize: isMobile ? 12 : 14, fontWeight: 700,
                                  transition: 'all .3s', }}>
                                  {done ? step.icon : idx + 1}
                                </div>
                                <div style={{ fontSize: isMobile ? 9 : 10, fontFamily: P.display,
                                  letterSpacing: 0.5, color: done ? P.ink : P.dim, textAlign: 'center' }}>
                                  {step.label.toUpperCase()}
                                </div>
                              </div>
                              {idx < arr.length - 1 && (
                                <div style={{ flex: 1, height: 3, margin: '0 4px', marginBottom: 18, borderRadius: 999,
                                  background: stepIdx < currentIdx
                                    ? `repeating-linear-gradient(90deg,${P.green} 0 6px,transparent 6px 10px)`
                                    : P.line2 }} />
                              )}
                            </React.Fragment>
                          );
                        })}
                      </div>
                    </div>

                    {/* Acciones */}
                    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                      <PopButton variant="secondary" size="sm" onClick={() => navigate('listing')}>
                        🔄 Volver a comprar
                      </PopButton>
                      {order.status !== 'cancelled' && (
                        <PopButton variant="secondary" size="sm">
                          📞 Contactar soporte
                        </PopButton>
                      )}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

window.OrdersScreen = OrdersScreen;
