// Order confirmation + tracking. Polls /api/order until payment + waybill land.

const STATUS_COPY = {
  pending:    { label: "Awaiting payment", note: "We're waiting for your payment to confirm." },
  paid:       { label: "Paid", note: "Payment received. We're arranging your courier." },
  processing: { label: "Preparing shipment", note: "Your courier is booked. Resi below." },
  shipped:    { label: "On the way", note: "Your order is with the courier." },
  delivered:  { label: "Delivered", note: "Enjoy your final third." },
  cancelled:  { label: "Cancelled", note: "This order was cancelled." },
  expired:    { label: "Expired", note: "The payment window lapsed. Please order again." },
};

const Order = ({ id, navigate }) => {
  const [order, setOrder] = React.useState(null);
  const [error, setError] = React.useState("");

  const load = React.useCallback(async () => {
    try {
      const r = await fetch("/api/order?id=" + encodeURIComponent(id));
      const j = await r.json();
      if (!r.ok || j.error) throw new Error(j.error || "Not found");
      setOrder(j);
      return j;
    } catch (e) { setError(e.message); return null; }
  }, [id]);

  React.useEffect(() => {
    let timer;
    let tries = 0;
    const tick = async () => {
      const o = await load();
      tries += 1;
      // keep polling while still pending and not yet shipped, up to ~2 min
      if (o && (o.status === "pending" || (o.status === "paid" && !o.waybill_id)) && tries < 40) {
        timer = setTimeout(tick, 3000);
      }
    };
    tick();
    return () => clearTimeout(timer);
  }, [load]);

  if (error) {
    return (
      <main><section style={{ padding: "120px var(--pad-x)", maxWidth: 720, margin: "0 auto", textAlign: "center" }}>
        <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 32 }}>We couldn't find that order.</p>
        <button className="lnk" style={{ marginTop: 24 }} onClick={() => navigate("/products")}>Back to shop →</button>
      </section></main>
    );
  }

  if (!order) {
    return <main><section style={{ padding: "160px var(--pad-x)", textAlign: "center" }}><span className="mono" style={{ fontSize: 11, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--ink-mute)" }}>Loading order…</span></section></main>;
  }

  const sc = STATUS_COPY[order.status] || STATUS_COPY.pending;

  return (
    <main>
      <section style={{ padding: "60px var(--pad-x) 120px", maxWidth: 820, margin: "0 auto" }}>
        <span className="caption">Order {order.id}</span>
        <h1 className="d-l" style={{ fontStyle: "italic", margin: "16px 0 8px" }}>Thank you.</h1>
        <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 24, color: "var(--ink-mute)", margin: 0 }}>{sc.note}</p>

        {/* Status pill */}
        <div style={{ margin: "40px 0", display: "flex", alignItems: "center", gap: 14, borderTop: "1px solid var(--hair-strong)", borderBottom: "1px solid var(--hair-strong)", padding: "24px 0", flexWrap: "wrap" }}>
          <span className="dot" style={{ width: 8, height: 8 }} />
          <span className="mono" style={{ fontSize: 12, letterSpacing: ".16em", textTransform: "uppercase" }}>{sc.label}</span>
          {order.status === "pending" && order.snap_token && (
            <button className="btn solid" style={{ marginLeft: "auto", padding: "10px 16px", fontSize: 10 }} onClick={async () => {
              if (typeof loadSnap !== "function") return;
              const snap = await loadSnap();
              snap.pay(order.snap_token, { onSuccess: load, onPending: load, onClose: () => {} });
            }}>Continue payment <span className="arr">→</span></button>
          )}
        </div>

        {order.waybill_id && (
          <div style={{ marginBottom: 40 }}>
            <span className="mono" style={{ fontSize: 10, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--ink-mute)", display: "block", marginBottom: 8 }}>Tracking number ({order.courier_name})</span>
            <div style={{ display: "flex", alignItems: "baseline", gap: 16, flexWrap: "wrap" }}>
              <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 32 }}>{order.waybill_id}</span>
              {order.tracking_url && <a className="lnk" href={order.tracking_url} target="_blank" rel="noreferrer">Track shipment →</a>}
            </div>
          </div>
        )}

        {/* Items */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {(order.items || []).map((it) => (
            <div key={it.id} style={{ display: "flex", justifyContent: "space-between", borderTop: "1px solid var(--hair)", paddingTop: 12 }}>
              <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 18 }}>{it.name} <span className="mono" style={{ fontSize: 11, fontStyle: "normal", color: "var(--ink-mute)" }}>×{it.qty}</span></span>
              <span className="mono" style={{ fontSize: 12 }}>{formatIDR(it.price * it.qty)}</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 16, borderTop: "1px solid var(--hair-strong)", paddingTop: 16, display: "flex", flexDirection: "column", gap: 8 }}>
          <Row label="Subtotal" value={formatIDR(order.subtotal)} />
          <Row label={"Shipping · " + (order.courier_name || "")} value={formatIDR(order.shipping_cost)} />
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 8 }}>
            <span className="mono" style={{ fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase" }}>Total</span>
            <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 28 }}>{formatIDR(order.total)}</span>
          </div>
        </div>

        <p className="mono" style={{ fontSize: 11, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-mute)", marginTop: 40, lineHeight: 1.7 }}>
          Shipping to {order.area_label || "—"}. Questions? <a className="lnk" href="https://wa.me/6287789777109" target="_blank" rel="noreferrer">WhatsApp us</a>.
        </p>
        <button className="btn" style={{ marginTop: 32 }} onClick={() => navigate("/products")}>Back to shop</button>
      </section>
    </main>
  );
};

window.Order = Order;
