// Tracking — confirmación post-pago + página "Mi pedido" (línea de tiempo 3 estados)

const TRACK_STEPS = [
  { id: "confirmed", label: "Confirmado", icon: "✅", desc: "Recibimos tu pago y estamos preparando tu pedido" },
  { id: "in_transit", label: "En camino", icon: "🚚", desc: "El repartidor salió con tu pedido" },
  { id: "delivered", label: "Entregado", icon: "📦", desc: "Tu pedido fue entregado" },
];

function statusIndex(status) {
  if (status === "confirmed") return 0;
  if (status === "in_transit") return 1;
  if (status === "delivered") return 2;
  return -1;
}

function OrderTracking({ orderId, accent, waDeposito, onClose }) {
  const [order, setOrder] = React.useState(() => getOrder(orderId));
  React.useEffect(() => {
    const refresh = () => setOrder(getOrder(orderId));
    window.addEventListener("storage", refresh);
    const t = setInterval(refresh, 4000);
    return () => { window.removeEventListener("storage", refresh); clearInterval(t); };
  }, [orderId]);

  if (!order) return null;
  const idx = statusIndex(order.status);
  const isFailed = order.status === "failed";
  const isPickup = ["pickup_transit", "pickup_ready", "retired"].includes(order.status);
  const branches = loadBranches();
  const pickupBranch = order.pickupBranchId ? branches.find(b => b.id === order.pickupBranchId) : null;

  const waUrl = () => {
    const raw = (waDeposito || "").replace(/\D/g, "");
    const phone = raw.startsWith("549") ? raw : raw.startsWith("54") ? "549" + raw.slice(2) : "549" + raw;
    return `https://wa.me/${phone}?text=${encodeURIComponent(`Hola! Consulto por mi pedido ${order.id}`)}`;
  };

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(40,25,10,0.5)", zIndex: 400, display: "flex", alignItems: "flex-end", justifyContent: "center", backdropFilter: "blur(6px)" }} onClick={onClose}>
      <div style={{ background: "#fdfaf3", borderRadius: "22px 22px 0 0", padding: "22px 20px 32px", width: "100%", maxWidth: 520, maxHeight: "92vh", overflowY: "auto", fontFamily: "'DM Sans', sans-serif" }} onClick={e => e.stopPropagation()}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 800, color: "#8a7a66", textTransform: "uppercase", letterSpacing: "0.08em" }}>Mi pedido</div>
            <h2 style={{ fontFamily: "'Bebas Neue', cursive", fontSize: 30, letterSpacing: "0.04em", margin: 0, color: "#1a1008" }}>#{order.id}</h2>
          </div>
          <button onClick={onClose} style={{ background: "#f5ede1", border: "none", color: "#6b5d4e", borderRadius: "50%", width: 32, height: 32, cursor: "pointer", fontSize: 14 }}>✕</button>
        </div>

        {/* Aviso especial: fallida / retiro */}
        {isFailed && (
          <div style={{ background: "#fef2f2", border: "1.5px solid #fecaca", borderRadius: 14, padding: 16, marginBottom: 16 }}>
            <div style={{ fontWeight: 800, color: "#991b1b", fontSize: 14, marginBottom: 4 }}>😕 No pudimos entregarte</div>
            <div style={{ fontSize: 13, color: "#7f1d1d", lineHeight: 1.5 }}>
              Pasamos por tu dirección{order.failures?.length ? ` a las ${new Date(order.failures[order.failures.length - 1].at).toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit" })}` : ""} y no pudimos entregarte.
              Escribinos para coordinar un nuevo intento sin costo.
            </div>
            {order.failures?.length > 0 && order.failures[order.failures.length - 1].photo && (
              <img src={order.failures[order.failures.length - 1].photo} alt="constancia" style={{ width: "100%", borderRadius: 10, marginTop: 10 }} />
            )}
          </div>
        )}
        {isPickup && (
          <div style={{ background: "#fff7ed", border: "1.5px solid #fdba74", borderRadius: 14, padding: 16, marginBottom: 16 }}>
            <div style={{ fontWeight: 800, color: "#9a3412", fontSize: 14, marginBottom: 4 }}>
              {order.status === "pickup_ready" ? "🏪 Listo para retirar" : order.status === "retired" ? "✅ Retirado" : "🚚 En camino a la sucursal"}
            </div>
            {pickupBranch && (
              <div style={{ fontSize: 13, color: "#7c2d12", lineHeight: 1.5 }}>
                {order.status === "pickup_ready"
                  ? <span>Tu pedido te espera en <strong>{pickupBranch.name}</strong> — {pickupBranch.address}{pickupBranch.hours ? ` · ${pickupBranch.hours}` : ""}</span>
                  : order.status === "retired" ? "Gracias por retirar tu pedido."
                  : <span>Tras dos intentos de entrega, tu pedido va a <strong>{pickupBranch.name}</strong> para que lo retires.</span>}
              </div>
            )}
          </div>
        )}

        {/* Línea de tiempo */}
        {!isPickup && (
          <div style={{ background: "#fff", border: "1px solid #e8dcc8", borderRadius: 16, padding: "20px 18px", marginBottom: 16 }}>
            {TRACK_STEPS.map((s, i) => {
              const done = idx >= i;
              const current = idx === i && order.status !== "delivered";
              return (
                <div key={s.id} style={{ display: "flex", gap: 14, position: "relative", paddingBottom: i < 2 ? 26 : 0 }}>
                  {i < 2 && <div style={{ position: "absolute", left: 19, top: 40, bottom: 0, width: 3, borderRadius: 2, background: idx > i ? "#15803d" : "#ede1c8" }}></div>}
                  <div style={{
                    width: 40, height: 40, borderRadius: "50%", flexShrink: 0, zIndex: 1,
                    background: done ? (i === 2 ? "#15803d" : current ? accent : "#15803d") : "#f5ede1",
                    display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18,
                    border: current ? `3px solid ${accent}44` : "none",
                    filter: done ? "none" : "grayscale(1) opacity(0.5)"
                  }}>{s.icon}</div>
                  <div style={{ paddingTop: 2 }}>
                    <div style={{ fontWeight: 800, fontSize: 15, color: done ? "#1a1008" : "#a89882" }}>{s.label}</div>
                    <div style={{ fontSize: 12, color: done ? "#6b5d4e" : "#c9b88f", lineHeight: 1.4 }}>
                      {i === 0 && done ? `Te lo llevamos ${bandLabel(order).toLowerCase()}` : s.desc}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* Datos del pedido */}
        <div style={{ background: "#fff", border: "1px solid #e8dcc8", borderRadius: 14, padding: 16, marginBottom: 16, fontSize: 13 }}>
          <div style={{ marginBottom: 8 }}><span style={{ color: "#8a7a66" }}>📍</span> <strong>{order.customer.street}</strong>{order.customer.ref ? ` (${order.customer.ref})` : ""}</div>
          {order.items.map(it => (
            <div key={it.id} style={{ display: "flex", justifyContent: "space-between", padding: "3px 0", color: "#1a1008" }}>
              <span>{it.qty}× {it.name}</span>
              <span style={{ color: "#8a7a66", flexShrink: 0, marginLeft: 8 }}>${(it.price * it.qty).toLocaleString("es-AR")}</span>
            </div>
          ))}
          <div style={{ borderTop: "1px solid #f0e6d2", marginTop: 8, paddingTop: 8, display: "flex", flexDirection: "column", gap: 3 }}>
            <div style={{ display: "flex", justifyContent: "space-between", color: "#6b5d4e" }}><span>Envío</span><span>{order.shipping === 0 ? "GRATIS 🎉" : "$" + order.shipping.toLocaleString("es-AR")}</span></div>
            <div style={{ display: "flex", justifyContent: "space-between", fontWeight: 800, fontSize: 15 }}><span>Total pagado</span><span>${order.total.toLocaleString("es-AR")}</span></div>
          </div>
        </div>

        <a href={waUrl()} target="_blank" rel="noopener" style={{
          display: "block", textAlign: "center", background: "#25D366", color: "#fff",
          borderRadius: 12, padding: "13px 0", fontWeight: 800, fontSize: 14, textDecoration: "none"
        }}>💬 ¿Algún problema? Escribinos</a>
      </div>
    </div>
  );
}

// Confirmación inmediata al volver de MP
function PaymentConfirmation({ orderId, accent, onTrack, onClose }) {
  const order = getOrder(orderId);
  if (!order) return null;
  return (
    <div style={{ position: "fixed", inset: 0, background: "#fdfaf3", zIndex: 450, display: "flex", alignItems: "center", justifyContent: "center", padding: 24, fontFamily: "'DM Sans', sans-serif", overflowY: "auto" }}>
      <div style={{ maxWidth: 420, width: "100%", textAlign: "center" }}>
        <div style={{ fontSize: 64, animation: "confirmPop 0.5s ease" }}>✅</div>
        <h1 style={{ fontFamily: "'Bebas Neue', cursive", fontSize: 34, letterSpacing: "0.04em", color: "#1a1008", margin: "8px 0 2px" }}>Pago aprobado</h1>
        <div style={{ fontSize: 15, color: "#6b5d4e", marginBottom: 20 }}>Tu pedido es el <strong style={{ color: "#1a1008", fontSize: 18 }}>#{order.id}</strong></div>

        <div style={{ background: "linear-gradient(135deg,#fff7ed,#ffedd5)", border: `2px solid ${accent}`, borderRadius: 16, padding: 18, marginBottom: 14, textAlign: "left" }}>
          <div style={{ fontSize: 14, fontWeight: 800, color: "#1a1008", marginBottom: 4 }}>🚚 Te lo llevamos {bandLabel(order).toLowerCase()}</div>
          <div style={{ fontSize: 13, color: "#6b5d4e" }}>📍 {order.customer.street}{order.customer.ref ? ` (${order.customer.ref})` : ""}</div>
        </div>

        <div style={{ background: "#fff", border: "1px solid #e8dcc8", borderRadius: 14, padding: 16, marginBottom: 20, textAlign: "left", fontSize: 13 }}>
          {order.items.map(it => (
            <div key={it.id} style={{ display: "flex", justifyContent: "space-between", padding: "3px 0" }}>
              <span>{it.qty}× {it.name}</span>
              <span style={{ color: "#8a7a66", flexShrink: 0, marginLeft: 8 }}>${(it.price * it.qty).toLocaleString("es-AR")}</span>
            </div>
          ))}
          <div style={{ borderTop: "1px solid #f0e6d2", marginTop: 8, paddingTop: 8, display: "flex", justifyContent: "space-between", fontWeight: 800, fontSize: 15 }}>
            <span>Total pagado</span><span>${order.total.toLocaleString("es-AR")}</span>
          </div>
        </div>

        <button onClick={onTrack} style={{ width: "100%", background: accent, color: "#fff", border: "none", borderRadius: 12, padding: "15px 0", fontWeight: 800, fontSize: 15, cursor: "pointer", marginBottom: 10 }}>📦 Seguir mi pedido</button>
        <button onClick={onClose} style={{ width: "100%", background: "transparent", color: "#6b5d4e", border: "1px solid #e8dcc8", borderRadius: 12, padding: "13px 0", fontWeight: 700, fontSize: 13, cursor: "pointer" }}>Volver al catálogo</button>
      </div>
      <style>{`@keyframes confirmPop { 0% { transform: scale(0.4); opacity: 0; } 70% { transform: scale(1.15); } 100% { transform: scale(1); opacity: 1; } }`}</style>
    </div>
  );
}

// Lista "Mis últimos pedidos" — hasta 3, antes de entrar al detalle
function MyOrdersList({ accent, onSelect, onClose }) {
  const list = myOrders().slice(-3).reverse();
  const chip = (s) => ({
    confirmed: ["Confirmado", "#0e7490"], in_transit: ["En camino", "#d97706"],
    delivered: ["Entregado", "#15803d"], failed: ["No entregado", "#b91c1c"],
    pickup_transit: ["A sucursal", "#9a3412"], pickup_ready: ["P/ retirar", "#9a3412"],
    retired: ["Retirado", "#64748b"], cancelled: ["Cancelado", "#64748b"], pending_payment: ["Pago pendiente", "#b45309"],
  }[s] || [s, "#64748b"]);
  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(40,25,10,0.5)", zIndex: 400, display: "flex", alignItems: "flex-end", justifyContent: "center", backdropFilter: "blur(6px)" }} onClick={onClose}>
      <div style={{ background: "#fdfaf3", borderRadius: "22px 22px 0 0", padding: "22px 20px 32px", width: "100%", maxWidth: 520, fontFamily: "'DM Sans', sans-serif" }} onClick={e => e.stopPropagation()}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <h2 style={{ fontFamily: "'Bebas Neue', cursive", fontSize: 26, letterSpacing: "0.04em", margin: 0, color: "#1a1008" }}>Mis últimos pedidos</h2>
          <button onClick={onClose} style={{ background: "#f5ede1", border: "none", color: "#6b5d4e", borderRadius: "50%", width: 32, height: 32, cursor: "pointer", fontSize: 14 }}>✕</button>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {list.map(o => {
            const [label, color] = chip(o.status);
            return (
              <button key={o.id} onClick={() => onSelect(o.id)} style={{
                display: "flex", alignItems: "center", gap: 12, textAlign: "left", width: "100%",
                background: "#fff", border: "1.5px solid #e8dcc8", borderRadius: 14, padding: "14px 16px",
                cursor: "pointer", fontFamily: "'DM Sans', sans-serif"
              }}>
                <span style={{ flex: 1 }}>
                  <span style={{ display: "block", fontWeight: 800, fontSize: 15, color: "#1a1008" }}>#{o.id} · ${o.total.toLocaleString("es-AR")}</span>
                  <span style={{ display: "block", fontSize: 12, color: "#8a7a66" }}>
                    {o.items.reduce((s, i) => s + i.qty, 0)} productos · {new Date(o.createdAt).toLocaleDateString("es-AR", { day: "numeric", month: "short" })}{o.band ? ` · ${bandLabel(o).toLowerCase()}` : ""}
                  </span>
                </span>
                <span style={{ background: color + "18", color, fontSize: 11, fontWeight: 800, padding: "4px 10px", borderRadius: 12, whiteSpace: "nowrap" }}>{label}</span>
                <span style={{ color: "#c9b88f", fontSize: 16 }}>›</span>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OrderTracking, PaymentConfirmation, MyOrdersList, statusIndex });
