// OrderDetail.jsx — detail view for a single order, opened from Account > Mis compras.
// Timeline of states, items table, shipping address, payment summary, invoice.

const ORDER_DETAIL_DATA = {
  "AL-712304": {
    id: "AL-712304", date: "12 feb 2026 · 14:38", status: "DELIVERED",
    items: [{ pid: "p001", qty: 1 }, { pid: "p008", qty: 1 }],
    subtotal: 2548, shipping: 0, total: 2548,
    address: { name: "Bau Andalón", street: "Av. Francisco Villa 1180, Int. 4", area: "Versalles, Puerto Vallarta", state: "Jalisco · CP 48330" },
    payment: { brand: "VISA", last4: "4242", msi: 12 },
    timeline: [
      { state: "REQUESTED",   label: "Pedido recibido",            t: "12 feb · 14:38", done: true },
      { state: "ACCEPTED",    label: "Confirmado por la tienda",   t: "12 feb · 14:42", done: true },
      { state: "READY",       label: "Listo para envío",           t: "12 feb · 17:10", done: true },
      { state: "IN_PROGRESS", label: "En camino a tu dirección",   t: "13 feb · 09:24", done: true },
      { state: "DELIVERED",   label: "Entregado",                  t: "14 feb · 11:50", done: true, pin: "8432" },
    ],
  },
  "AL-711981": {
    id: "AL-711981", date: "08 feb 2026 · 18:12", status: "IN_PROGRESS",
    items: [{ pid: "p005", qty: 1 }],
    subtotal: 1899, shipping: 0, total: 1899,
    address: { name: "Bau Andalón", street: "Av. Francisco Villa 1180, Int. 4", area: "Versalles, Puerto Vallarta", state: "Jalisco · CP 48330" },
    payment: { brand: "MASTERCARD", last4: "5588", msi: 6 },
    timeline: [
      { state: "REQUESTED",   label: "Pedido recibido",            t: "08 feb · 18:12", done: true },
      { state: "ACCEPTED",    label: "Confirmado por la tienda",   t: "08 feb · 18:18", done: true },
      { state: "READY",       label: "Listo para envío",           t: "09 feb · 11:30", done: true },
      { state: "IN_PROGRESS", label: "En camino — llega mañana entre 10 y 18", t: "10 feb · 09:14", done: true, current: true },
      { state: "DELIVERED",   label: "Entregado",                  t: "Llegada estimada: 11 feb", done: false },
    ],
  },
};

const STATE_ORDER = ["REQUESTED", "ACCEPTED", "READY", "IN_PROGRESS", "DELIVERED"];

const OrderDetailPage = ({ params, onNav }) => {
  const order = ORDER_DETAIL_DATA[params?.id] || ORDER_DETAIL_DATA["AL-712304"];
  const items = order.items.map(i => ({ ...CATALOG.find(p => p.id === i.pid), qty: i.qty }));
  const status = STATUS_LABEL[order.status];

  return (
    <div style={{ maxWidth: "var(--container)", margin: "0 auto", padding: "0 32px" }}>
      <Breadcrumb items={["Inicio", "Mi cuenta", "Mis compras", `#${order.id}`]} />

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 32, gap: 16, flexWrap: "wrap" }}>
        <div>
          <a onClick={() => onNav("account", { tab: "compras" })} style={{ font: "600 13px var(--font-sans)", color: "var(--primary)", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 4 }}>
            <AllenIcon name="chevron_right" size={14} style={{ transform: "rotate(180deg)" }} /> Volver a Mis compras
          </a>
          <h1 className="display-sm" style={{ marginTop: 12 }}>Pedido #{order.id}</h1>
          <p className="body-sm" style={{ marginTop: 6 }}>{order.date}</p>
        </div>
        <span style={{
          font: "700 12px var(--font-sans)", color: status.fg, background: status.bg,
          padding: "8px 16px", borderRadius: "9999px", letterSpacing: ".04em"
        }}>{status.label}</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 32, alignItems: "start" }}>
        {/* LEFT: timeline + items */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {/* Timeline */}
          <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 28 }}>
            <h3 className="title" style={{ marginBottom: 20 }}>Seguimiento</h3>
            <div style={{ position: "relative" }}>
              {order.timeline.map((step, i) => (
                <div key={step.state} style={{ display: "flex", gap: 16, position: "relative", paddingBottom: i === order.timeline.length - 1 ? 0 : 24 }}>
                  {/* connector line */}
                  {i < order.timeline.length - 1 && (
                    <div style={{ position: "absolute", left: 13, top: 28, bottom: 0, width: 2, background: step.done ? "var(--success)" : "var(--border)" }} />
                  )}
                  {/* dot */}
                  <div style={{
                    width: 28, height: 28, borderRadius: 14, flexShrink: 0,
                    background: step.done ? (step.current ? "var(--warning)" : "var(--success)") : "var(--bg-elev-2)",
                    border: step.done ? 0 : "2px solid var(--border-strong)",
                    display: "grid", placeItems: "center", color: "#fff",
                    boxShadow: step.current ? "0 0 0 6px var(--warning-bg)" : "none",
                    zIndex: 1,
                  }}>
                    {step.done && <AllenIcon name={step.current ? "local_shipping" : "check"} size={14} color="#fff" weight={2.5} />}
                  </div>
                  <div style={{ flex: 1, paddingTop: 2 }}>
                    <div className="title-sm" style={{ fontSize: 14, color: step.done ? "var(--fg-strong)" : "var(--fg-muted)" }}>{step.label}</div>
                    <div className="body-sm" style={{ marginTop: 2, fontSize: 12 }}>{step.t}</div>
                    {step.pin && (
                      <div style={{ marginTop: 8, padding: "8px 12px", background: "var(--success-bg)", borderRadius: "var(--radius-sm)", display: "inline-flex", alignItems: "center", gap: 8 }}>
                        <AllenIcon name="lock" size={14} color="var(--success)" />
                        <span style={{ font: "600 12px var(--font-sans)", color: "var(--fg-strong)" }}>PIN de entrega: <strong style={{ fontFamily: "var(--font-mono)", letterSpacing: ".15em" }}>{step.pin}</strong></span>
                      </div>
                    )}
                    {step.current && (
                      <button style={{ marginTop: 8, background: "var(--primary)", color: "#fff", border: 0, padding: "8px 16px", borderRadius: "9999px", font: "700 12px var(--font-sans)", cursor: "pointer", boxShadow: "var(--elev-cta-blue)" }}>
                        Ver mapa en vivo
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Items */}
          <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", overflow: "hidden" }}>
            <h3 className="title" style={{ padding: "20px 28px 8px" }}>Productos ({items.length})</h3>
            {items.map((it, i) => (
              <div key={it.id} style={{ display: "grid", gridTemplateColumns: "72px 1fr auto", gap: 16, padding: "16px 28px", borderTop: "1px solid var(--border-soft)" }}>
                <button onClick={() => onNav("pdp", { id: it.id })} style={{ width: 72, height: 72, padding: 0, border: 0, background: it.imgBg, borderRadius: "var(--radius-sm)", overflow: "hidden", cursor: "pointer" }}>
                  <img src={it.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </button>
                <div>
                  <div className="label-sm" style={{ color: "var(--fg-subtle)" }}>{it.brand}</div>
                  <a onClick={() => onNav("pdp", { id: it.id })} className="title-sm" style={{ cursor: "pointer", display: "block", marginTop: 2 }}>{it.name}</a>
                  <div className="body-sm" style={{ marginTop: 4 }}>Cantidad: {it.qty}</div>
                </div>
                <div style={{ textAlign: "right", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "flex-end", gap: 8 }}>
                  <div className="price">${(it.price * it.qty).toLocaleString("es-MX")}</div>
                  {order.status === "DELIVERED" && (
                    <button style={{ background: "transparent", color: "var(--primary)", border: 0, font: "700 12px var(--font-sans)", cursor: "pointer", padding: 0 }}>
                      Reseñar producto
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>

          {/* Help */}
          <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24, display: "flex", alignItems: "center", gap: 16 }}>
            <div style={{ width: 44, height: 44, borderRadius: 22, background: "var(--primary-soft)", display: "grid", placeItems: "center" }}>
              <AllenIcon name="support_agent" size={20} color="var(--primary-press)" />
            </div>
            <div style={{ flex: 1 }}>
              <div className="title-sm">¿Algo no salió bien?</div>
              <div className="body-sm" style={{ marginTop: 2 }}>Reporta un problema con este pedido y un agente Allen te contacta en menos de 1 hora.</div>
            </div>
            <button style={{ background: "transparent", color: "var(--primary)", border: "1.5px solid var(--primary)", padding: "10px 18px", borderRadius: "9999px", font: "700 13px var(--font-sans)", cursor: "pointer" }}>Reportar</button>
          </div>
        </div>

        {/* RIGHT: address + payment + summary */}
        <aside style={{ display: "flex", flexDirection: "column", gap: 16, position: "sticky", top: 160 }}>
          <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 20 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
              <AllenIcon name="location_on" size={18} color="var(--primary)" />
              <h4 className="title-sm">Dirección de entrega</h4>
            </div>
            <div className="body" style={{ color: "var(--fg-strong)" }}>{order.address.name}</div>
            <div className="body-sm">{order.address.street}</div>
            <div className="body-sm">{order.address.area}</div>
            <div className="body-sm">{order.address.state}</div>
          </div>

          <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 20 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
              <AllenIcon name="credit_card" size={18} color="var(--primary)" />
              <h4 className="title-sm">Pago</h4>
            </div>
            <div className="body" style={{ color: "var(--fg-strong)", display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ font: "700 11px var(--font-sans)", letterSpacing: ".06em", color: "var(--fg-muted)" }}>{order.payment.brand}</span>
              <span style={{ fontFamily: "var(--font-mono)" }}>•••• {order.payment.last4}</span>
            </div>
            {order.payment.msi > 1 && <div className="body-sm" style={{ marginTop: 4 }}>{order.payment.msi} meses sin intereses</div>}
          </div>

          <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 20 }}>
            <h4 className="title-sm" style={{ marginBottom: 12 }}>Resumen</h4>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <Line k="Subtotal" v={`$${order.subtotal.toLocaleString("es-MX")}`} />
              <Line k="Envío" v={order.shipping === 0 ? "GRATIS" : `$${order.shipping}`} color={order.shipping === 0 ? "var(--success)" : null} />
              <div style={{ borderTop: "1px solid var(--border-soft)", paddingTop: 10, marginTop: 4, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <span className="title-sm">Total</span>
                <span className="price-lg">${order.total.toLocaleString("es-MX")}</span>
              </div>
            </div>
            <button style={{ width: "100%", marginTop: 16, background: "var(--bg-elev-2)", color: "var(--fg-strong)", border: "1px solid var(--border-strong)", padding: "12px 18px", borderRadius: "9999px", font: "700 13px var(--font-sans)", cursor: "pointer" }}>
              Descargar factura
            </button>
            {order.status === "DELIVERED" && (
              <button style={{ width: "100%", marginTop: 8, background: "var(--primary)", color: "#fff", border: 0, padding: "12px 18px", borderRadius: "9999px", font: "700 13px var(--font-sans)", cursor: "pointer", boxShadow: "var(--elev-cta-blue)" }}>
                Volver a comprar
              </button>
            )}
          </div>
        </aside>
      </div>
    </div>
  );
};

// Small price-line component (mirrors the one in Cart.jsx).
const Line = ({ k, v, color }) => (
  <div style={{ display: "flex", justifyContent: "space-between", font: "500 14px var(--font-sans)", color: "var(--fg-strong)" }}>
    <span style={{ color: "var(--fg-muted)" }}>{k}</span>
    <span style={{ color: color || "var(--fg-strong)", fontWeight: color ? 700 : 500 }}>{v}</span>
  </div>
);

window.OrderDetailPage = OrderDetailPage;
