// src/tracking.jsx — Order-placed tracker. Distinct visual shape from cart/product
// screens: full-bleed hero with a hand-drawn map SVG, a live-ticking countdown,
// a step timeline, and a minimal order summary. No card grid.

function Tracking({ onNav, order }) {
  const isMobile = useMedia("(max-width: 720px)");
  // Fallback when user deep-links without an order (e.g., tweaks jump).
  const safeOrder = order || {
    storeId: "kalymnos",
    number: "4821",
    itemsCount: 3,
    items: [
      { id: "deli-eggcheese",  name: "Bacon-Egg-Cheese on a roll", qty: 1, unit: "6\" hero",  price: 8.50 },
      { id: "drk-gatorade",    name: "Gatorade Lemon-Lime",        qty: 1, unit: "32oz btl",  price: 2.99 },
      { id: "drk-topo",        name: "Topo Chico",                 qty: 2, unit: "355ml btl", price: 2.50 },
    ],
    total: 24.50,
    placedAt: Date.now(),
    etaSeconds: 18 * 60,
  };
  const store = STORES.find(s => s.id === safeOrder.storeId) || STORES[0];
  const [remaining, setRemaining] = React.useState(safeOrder.etaSeconds);

  React.useEffect(() => {
    const id = setInterval(() => setRemaining(r => Math.max(0, r - 1)), 1000);
    return () => clearInterval(id);
  }, []);

  const elapsed = safeOrder.etaSeconds - remaining;
  const progress = Math.min(1, elapsed / safeOrder.etaSeconds);

  // Four-step timeline — "current" step advances with elapsed time.
  const steps = [
    { id: "placed",  label: "Order placed",    sub: "We texted the store",    at: 0.0 },
    { id: "packed",  label: "Packed",          sub: `${store.name} bagged it`, at: 0.25 },
    { id: "out",     label: "Out for delivery", sub: "On a bike, not a truck", at: 0.55 },
    { id: "home",    label: "At your door",    sub: "Leave it with the doorman", at: 1.0 },
  ];
  const currentIdx = steps.reduce((acc, s, i) => progress >= s.at ? i : acc, 0);

  const mm = String(Math.floor(remaining / 60)).padStart(2, "0");
  const ss = String(remaining % 60).padStart(2, "0");

  return (
    <div style={{ maxWidth: 1080, margin: "0 auto", padding: isMobile ? "14px 16px 120px" : "28px 28px 80px" }}>
      {/* Hero — map + countdown, not a card stack */}
      <section style={{
        position: "relative", overflow: "hidden",
        borderRadius: "var(--radius-xl)",
        background: "var(--navy-fill)", color: "#fff",
        padding: isMobile ? "28px 24px 32px" : "36px 40px 40px",
        boxShadow: "var(--shadow-md)",
      }}>
        <div aria-hidden style={{
          position: "absolute", inset: 0,
          background: `
            radial-gradient(900px 380px at 100% 0%, oklch(from var(--accent) l c h / 0.22), transparent 65%),
            radial-gradient(600px 260px at 0% 120%, oklch(from var(--accent) l c h / 0.18), transparent 70%)
          `,
          pointerEvents: "none",
        }} />
        <div style={{ position: "relative", display: "flex", gap: 36, alignItems: "flex-start", flexWrap: "wrap" }}>
          <div style={{ flex: "1 1 340px", minWidth: 260 }}>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 8,
                          padding: "5px 12px", borderRadius: 999,
                          background: "rgba(255,255,255,0.1)",
                          fontSize: 11, fontWeight: 500, letterSpacing: "0.06em",
                          textTransform: "uppercase", marginBottom: 14 }}>
              <span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--accent)",
                             animation: "pulseDot 1.2s ease-in-out infinite" }} />
              Order #{safeOrder.number} · Live
            </div>
            <h1 className="serif" style={{ fontSize: isMobile ? 34 : 46, lineHeight: 1.05, margin: 0,
                                            letterSpacing: "-0.02em" }}>
              On the way.<br />
              <span style={{ fontStyle: "italic", color: "oklch(from #fff l c h / 0.72)" }}>
                From {store.name.split(" ")[0]} to {isMobile ? "you" : "your door"}.
              </span>
            </h1>
            <div style={{ marginTop: 22, display: "flex", alignItems: "baseline", gap: 12, flexWrap: "wrap" }}>
              <div className="num" style={{ fontSize: isMobile ? 42 : 56, fontWeight: 500,
                                            letterSpacing: "-0.02em", lineHeight: 1,
                                            fontFamily: '"Instrument Serif", Georgia, serif', fontStyle: "italic" }}>
                {mm}:{ss}
              </div>
              <div style={{ fontSize: 13.5, color: "oklch(from #fff l c h / 0.68)", maxWidth: 240 }}>
                {remaining > 0 ? "estimated to door" : "Should be knocking now."}
              </div>
            </div>
            <div style={{ marginTop: 20, height: 6, borderRadius: 999,
                          background: "rgba(255,255,255,0.12)", overflow: "hidden" }}>
              <div style={{ width: `${progress * 100}%`, height: "100%",
                            background: "linear-gradient(90deg, var(--accent), oklch(from var(--accent) calc(l + 0.06) c h))",
                            transition: "width 1s linear" }} />
            </div>
          </div>

          {/* Tiny map — inline SVG, not an image. Biker moves along a curve. */}
          {!isMobile && (
            <div style={{ flex: "1 1 300px", minWidth: 280, aspectRatio: "1 / 1", maxWidth: 340,
                          position: "relative",
                          background: "oklch(from var(--navy) calc(l + 0.08) c h / 0.35)",
                          borderRadius: 20, overflow: "hidden",
                          border: "1px solid rgba(255,255,255,0.08)" }}>
              <TrackingMap progress={progress} storeName={store.name} />
            </div>
          )}
        </div>
      </section>

      {/* Timeline — distinct shape: vertical ticks with an active ring */}
      <section style={{ marginTop: 28, display: "grid",
                        gridTemplateColumns: isMobile ? "1fr" : "1.3fr 1fr", gap: 28 }}>
        <div>
          <div className="uppercase-mono" style={{ marginBottom: 14 }}>Progress</div>
          <ol style={{ listStyle: "none", margin: 0, padding: 0, position: "relative" }}>
            <div style={{ position: "absolute", top: 12, bottom: 12, left: 13, width: 2,
                          background: "var(--line)" }} />
            {steps.map((s, i) => {
              const done = i < currentIdx;
              const active = i === currentIdx;
              return (
                <li key={s.id} style={{ position: "relative", padding: "0 0 22px 42px", display: "block" }}>
                  <span style={{
                    position: "absolute", left: 0, top: 2,
                    width: 28, height: 28, borderRadius: 999,
                    background: done || active ? "var(--navy-fill)" : "var(--surface)",
                    border: "2px solid " + (done || active ? "var(--navy-fill)" : "var(--line)"),
                    display: "inline-flex", alignItems: "center", justifyContent: "center",
                    color: "#fff",
                  }}>
                    {done ? <Icons.Check size={14} stroke={2.6} />
                         : active ? <span style={{ width: 8, height: 8, borderRadius: 99,
                                                   background: "#fff",
                                                   animation: "pulseDot 1.4s ease-in-out infinite" }} />
                         : null}
                  </span>
                  <div style={{ fontSize: 14.5, fontWeight: 600, color: active ? "var(--ink)" : (done ? "var(--ink)" : "var(--ink-3)") }}>
                    {s.label}
                  </div>
                  <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>{s.sub}</div>
                </li>
              );
            })}
          </ol>
        </div>

        {/* Summary — minimal, not another card grid */}
        <aside style={{
          padding: "18px 20px", borderRadius: "var(--radius-lg)",
          background: "var(--surface)", border: "1px solid var(--line)",
          display: "flex", flexDirection: "column", gap: 10,
          alignSelf: "flex-start",
        }}>
          <div className="uppercase-mono">Your order</div>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <Ph label={store.hero} aspect="1/1" img={storeImage(store)} seed={store.id}
                style={{ width: 46, height: 46, borderRadius: 10 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>{store.name}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>
                {safeOrder.itemsCount} items · <span className="num">{money(safeOrder.total)}</span>
              </div>
            </div>
          </div>

          {/* Actual line items — what was ordered. Renders only when the order
              carries an items snapshot (all placed orders and the fallback do). */}
          {Array.isArray(safeOrder.items) && safeOrder.items.length > 0 && (
            <ul style={{
              listStyle: "none", margin: "4px 0 0", padding: "10px 0",
              borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)",
              display: "flex", flexDirection: "column", gap: 10, maxHeight: 240, overflowY: "auto",
            }}>
              {safeOrder.items.map((it, idx) => (
                <li key={(it.id || "") + idx}
                  style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  {it.id && PRODUCT_INDEX[it.id] && (
                    <Ph label={it.name.split(" ")[0]} aspect="1/1"
                        img={productImage(PRODUCT_INDEX[it.id])} seed={it.id}
                        style={{ width: 36, height: 36, borderRadius: 8, flexShrink: 0, fontSize: 9 }} />
                  )}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)",
                                  overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                      {it.name}
                    </div>
                    <div style={{ fontSize: 11.5, color: "var(--ink-4)",
                                  overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                      {it.qty > 1 ? `×${it.qty}` : ""}{it.qty > 1 && it.unit ? " · " : ""}{it.unit || ""}
                    </div>
                  </div>
                  <span className="num" style={{ fontSize: 12.5, color: "var(--ink-2)", fontWeight: 600,
                                                  flexShrink: 0 }}>
                    {money(it.price * it.qty)}
                  </span>
                </li>
              ))}
            </ul>
          )}

          <Row2 l="Delivery" r={store.eta} />
          <Row2 l="Order #" r={`#${safeOrder.number}`} />
          <Row2 l="Placed" r="just now" />
          <div style={{ display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap" }}>
            <Btn variant="secondary" size="sm"
              icon={<Icons.Mic size={13} stroke={1.8} />}
              onClick={() => alert("We'll call the rider when they're 2 minutes away.")}>
              Call on arrival
            </Btn>
            <Btn variant="ghost" size="sm"
              onClick={() => onNav({ screen: "home" })}>
              Back to home
            </Btn>
          </div>
        </aside>
      </section>
    </div>
  );
}

function Row2({ l, r }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, color: "var(--ink-2)" }}>
      <span style={{ color: "var(--ink-3)" }}>{l}</span>
      <span className="num" style={{ fontWeight: 500, color: "var(--ink)" }}>{r}</span>
    </div>
  );
}

// TrackingMap — minimal inline SVG. Store pin at top-right, home pin at bottom-left,
// a curved route with a moving bike marker driven by `progress` [0..1].
function TrackingMap({ progress, storeName }) {
  // Control points for a gentle quadratic curve from store to home.
  const from = { x: 254, y: 46 };   // store corner
  const to   = { x: 46,  y: 254 };  // home corner
  const cp   = { x: 60,  y: 60 };   // curve control
  // Quadratic Bezier at time t
  const t = progress;
  const mt = 1 - t;
  const bx = mt * mt * from.x + 2 * mt * t * cp.x + t * t * to.x;
  const by = mt * mt * from.y + 2 * mt * t * cp.y + t * t * to.y;

  return (
    <svg viewBox="0 0 300 300" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
      {/* Grid — suggests a map without being literal */}
      <defs>
        <pattern id="g" width="20" height="20" patternUnits="userSpaceOnUse">
          <path d="M 20 0 L 0 0 0 20" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="1" />
        </pattern>
      </defs>
      <rect width="300" height="300" fill="url(#g)" />
      {/* Route (dashed — traveled portion draws first) */}
      <path d={`M ${from.x},${from.y} Q ${cp.x},${cp.y} ${to.x},${to.y}`}
            fill="none" stroke="rgba(255,255,255,0.12)" strokeWidth="3"
            strokeDasharray="6 6" strokeLinecap="round" />
      {/* Filled portion */}
      <path d={`M ${from.x},${from.y} Q ${cp.x},${cp.y} ${to.x},${to.y}`}
            fill="none" stroke="var(--accent)" strokeWidth="3" strokeLinecap="round"
            strokeDasharray={`${progress * 420} 1000`} />
      {/* Store pin */}
      <g>
        <circle cx={from.x} cy={from.y} r="10" fill="var(--accent)" />
        <circle cx={from.x} cy={from.y} r="3.5" fill="#fff" />
        <text x={from.x - 6} y={from.y - 18} fontSize="10" fontWeight="600" fill="#fff"
              textAnchor="end" fontFamily="JetBrains Mono, monospace" letterSpacing="0.06em">
          {storeName.split(" ")[0].toUpperCase()}
        </text>
      </g>
      {/* Home pin */}
      <g>
        <rect x={to.x - 8} y={to.y - 8} width="16" height="16" rx="3" fill="#fff" />
        <circle cx={to.x} cy={to.y} r="3" fill="var(--navy-fill)" />
        <text x={to.x + 14} y={to.y + 14} fontSize="10" fontWeight="600" fill="#fff"
              fontFamily="JetBrains Mono, monospace" letterSpacing="0.06em">
          YOU
        </text>
      </g>
      {/* Bike marker */}
      <g transform={`translate(${bx - 9}, ${by - 9})`}>
        <circle cx="9" cy="9" r="14" fill="rgba(255,255,255,0.08)" />
        <circle cx="9" cy="9" r="9" fill="#fff" />
        <text x="9" y="12.5" fontSize="11" textAnchor="middle">🚴</text>
      </g>
    </svg>
  );
}

window.Tracking = Tracking;

// ─── Orders (list) ─────────────────────────────────────────────────────────
// Entry point for the Orders tab. Shows 2 active orders as compact tracker
// cards up top, then a list of recent orders below. Tapping a card opens the
// full Tracking screen for that order.
function Orders({ onNav, activeOrder, setActiveOrder }) {
  const isMobile = useMedia("(max-width: 720px)");

  // If there's a live order from checkout, put it at the front. Otherwise two
  // mocked in-progress orders so the page has meaningful content in the demo.
  // Each fallback carries a realistic item snapshot so the Tracking sidebar
  // has something to render when the user taps "Track order".
  const now = Date.now();
  const fallbacks = [
    { number: "4821", storeId: "kalymnos", itemsCount: 3, total: 24.50,
      items: [
        { id: "deli-eggcheese", name: "Bacon-Egg-Cheese on a roll", qty: 1, unit: "6\" hero",  price: 8.50 },
        { id: "drk-gatorade",   name: "Gatorade Lemon-Lime",        qty: 1, unit: "32oz btl",  price: 2.99 },
        { id: "drk-topo",       name: "Topo Chico",                 qty: 2, unit: "355ml btl", price: 2.50 },
      ],
      placedAt: now - 4 * 60 * 1000, etaSeconds: 14 * 60 },
    { number: "4833", storeId: "verde", itemsCount: 6, total: 38.75,
      items: [
        { id: "prd-tomato", name: "Vine tomatoes",    qty: 1, unit: "lb",    price: 3.49 },
        { id: "prd-apple",  name: "Honeycrisp apples", qty: 2, unit: "lb",    price: 3.99 },
        { id: "prd-lemon",  name: "Lemons",            qty: 3, unit: "each",  price: 0.79 },
        { id: "prd-avocado",name: "Hass avocado",      qty: 2, unit: "each",  price: 2.49 },
      ],
      placedAt: now - 11 * 60 * 1000, etaSeconds: 7 * 60 },
  ];
  const inProgress = activeOrder
    ? [activeOrder, fallbacks[1]]
    : fallbacks;

  const openTracking = (order) => {
    setActiveOrder?.(order);
    onNav({ screen: "tracking" });
  };

  const recent = [
    { number: "4802", storeId: "kalymnos", itemsCount: 3, total: 24.50,
      when: "Mar 28 · 6:14 PM", status: "Delivered", items: ["Bacon-Egg-Cheese", "Gatorade Lemon-Lime", "Topo Chico"] },
    { number: "4791", storeId: "fig", itemsCount: 2, total: 47.00,
      when: "Mar 25 · 8:02 PM", status: "Delivered", items: ["Meiomi Pinot Noir", "Whispering Angel"] },
    { number: "4785", storeId: "liu", itemsCount: 5, total: 18.20,
      when: "Mar 22 · 11:47 PM", status: "Delivered", items: ["Advil 50ct", "Red Bull 12oz", "Liquid Death ×2", "Gum"] },
    { number: "4770", storeId: "arbor", itemsCount: 4, total: 41.85,
      when: "Mar 18 · 10:15 AM", status: "Delivered", items: ["Hammer", "Picture hooks", "Drywall anchors", "Level"] },
    { number: "4758", storeId: "kalymnos", itemsCount: 7, total: 52.40,
      when: "Mar 14 · 5:30 PM", status: "Delivered", items: ["Modelo 12pk", "Flamin' Hot Cheetos", "Oreo", "Topo Chico ×2", "Peanuts", "Doritos"] },
  ];

  return (
    <div style={{ maxWidth: 1080, margin: "0 auto", padding: isMobile ? "14px 16px 120px" : "28px 28px 80px" }}>
      <div style={{ marginBottom: 22 }}>
        <div className="uppercase-mono">Your orders</div>
        <h1 className="serif" style={{ margin: "2px 0 0", fontSize: isMobile ? 30 : 40,
                                       letterSpacing: "-0.02em", lineHeight: 1.1 }}>
          In progress & recent.
        </h1>
      </div>

      {/* In-progress section */}
      <section>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
                      marginBottom: 12 }}>
          <div className="uppercase-mono" style={{ color: "var(--accent)" }}>
            In progress · {inProgress.length}
          </div>
          <span style={{ fontSize: 12, color: "var(--ink-4)" }}>Live ETA from each store</span>
        </div>
        <div style={{ display: "grid",
                      gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr",
                      gap: 14 }}>
          {inProgress.map(o => (
            <ActiveOrderCard key={o.number} order={o} onOpen={() => openTracking(o)} />
          ))}
        </div>
      </section>

      {/* Recent section */}
      <section style={{ marginTop: 36 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
                      marginBottom: 12 }}>
          <div className="uppercase-mono">Recent</div>
          <span style={{ fontSize: 12, color: "var(--ink-4)" }}>Last 30 days · {recent.length}</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {recent.map(o => (
            <RecentOrderRow key={o.number} order={o} isMobile={isMobile}
              onOpen={() => onNav({ screen: "store", storeId: o.storeId })} />
          ))}
        </div>

        <div style={{ marginTop: 20, textAlign: "center" }}>
          <button className="btn-reset"
            style={{ fontSize: 13, color: "var(--navy)", fontWeight: 500,
                     display: "inline-flex", alignItems: "center", gap: 4,
                     padding: "8px 14px", borderRadius: 999,
                     background: "var(--surface)", border: "1px solid var(--line)" }}>
            See all orders
            <Icons.Chevron size={13} stroke={2} />
          </button>
        </div>
      </section>
    </div>
  );
}

// Compact active-order card — store thumb, live countdown, progress bar, Track.
function ActiveOrderCard({ order, onOpen }) {
  const store = STORES.find(s => s.id === order.storeId) || STORES[0];
  const [remaining, setRemaining] = React.useState(order.etaSeconds);
  React.useEffect(() => {
    const id = setInterval(() => setRemaining(r => Math.max(0, r - 1)), 1000);
    return () => clearInterval(id);
  }, []);
  const progress = Math.min(1, (order.etaSeconds - remaining) / order.etaSeconds);
  const mm = String(Math.floor(remaining / 60)).padStart(2, "0");
  const ss = String(remaining % 60).padStart(2, "0");
  const stage = progress < 0.25 ? "Packing" : progress < 0.55 ? "Packed" : progress < 1 ? "On the way" : "At your door";

  return (
    <div style={{
      display: "flex", flexDirection: "column", gap: 14,
      padding: 18,
      background: "var(--surface)",
      border: "1px solid var(--line)",
      borderRadius: "var(--radius-lg)",
      boxShadow: "var(--shadow-sm)",
      position: "relative", overflow: "hidden",
    }}>
      <div aria-hidden style={{
        position: "absolute", inset: 0,
        background: "radial-gradient(400px 180px at 100% 0%, oklch(from var(--accent) l c h / 0.08), transparent 70%)",
        pointerEvents: "none",
      }} />
      <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 12 }}>
        <Ph label={store.hero} aspect="1/1" img={storeImage(store)} seed={store.id}
            style={{ width: 44, height: 44, borderRadius: 10, flexShrink: 0 }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)",
                           overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {store.name}
            </span>
            <span style={{ fontSize: 10.5, color: "var(--accent)", fontWeight: 600,
                           letterSpacing: "0.06em", textTransform: "uppercase",
                           display: "inline-flex", alignItems: "center", gap: 4 }}>
              <span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--accent)",
                             animation: "pulseDot 1.2s ease-in-out infinite" }} />
              Live
            </span>
          </div>
          <div style={{ fontSize: 12, color: "var(--ink-3)",
                        fontFamily: '"JetBrains Mono", monospace' }}>
            #{order.number} · {order.itemsCount} items · <span className="num">{money(order.total)}</span>
          </div>
        </div>
      </div>

      <div style={{ position: "relative", display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 10 }}>
        <div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", letterSpacing: "0.05em",
                        textTransform: "uppercase", fontFamily: '"JetBrains Mono", monospace' }}>
            {stage}
          </div>
          <div className="num" style={{ fontSize: 30, fontWeight: 500, color: "var(--ink)",
                                         letterSpacing: "-0.01em", lineHeight: 1, marginTop: 4,
                                         fontFamily: '"Instrument Serif", Georgia, serif', fontStyle: "italic" }}>
            {mm}:{ss}
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontSize: 11, color: "var(--ink-4)" }}>to door</div>
          <div style={{ fontSize: 13, color: "var(--ink-2)" }}>~{store.distance}</div>
        </div>
      </div>

      <div style={{ position: "relative", height: 6, borderRadius: 999,
                    background: "var(--surface-2)", overflow: "hidden" }}>
        <div style={{ width: `${progress * 100}%`, height: "100%",
                      background: "linear-gradient(90deg, var(--accent), oklch(from var(--accent) calc(l + 0.06) c h))",
                      transition: "width 1s linear" }} />
      </div>

      <div style={{ position: "relative", display: "flex", gap: 8, marginTop: 2 }}>
        <Btn variant="primary" size="sm" onClick={onOpen}
             icon={<Icons.Pin size={13} stroke={1.9} />}>
          Track order
        </Btn>
        <Btn variant="ghost" size="sm" onClick={() => alert("We'll text the rider.")}>
          Message rider
        </Btn>
      </div>
    </div>
  );
}

// Dense past-order row — store, order number, when, items count, total.
function RecentOrderRow({ order, onOpen, isMobile }) {
  const store = STORES.find(s => s.id === order.storeId) || STORES[0];
  return (
    <button className="btn-reset" onClick={onOpen}
      style={{
        display: "flex", gap: 14, alignItems: "center", padding: 12,
        background: "var(--surface)", border: "1px solid var(--line)",
        borderRadius: 14, textAlign: "left", flexWrap: isMobile ? "wrap" : "nowrap",
      }}>
      <Ph label={store.hero} aspect="1/1" img={storeImage(store)} seed={store.id}
          style={{ width: 44, height: 44, borderRadius: 10, flexShrink: 0 }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10, flexWrap: "wrap", rowGap: 2 }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>{store.name}</span>
          <span style={{ fontSize: 11, color: "var(--ok)", fontWeight: 600,
                         letterSpacing: "0.04em", textTransform: "uppercase",
                         padding: "2px 8px", borderRadius: 999,
                         background: "var(--pickup-bg)", border: "1px solid var(--pickup-border)" }}>
            {order.status}
          </span>
          <span style={{ fontSize: 11.5, color: "var(--ink-4)",
                         fontFamily: '"JetBrains Mono", monospace' }}>
            #{order.number}
          </span>
        </div>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4,
                      overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {order.when} · {order.itemsCount} items · {order.items.slice(0, 3).join(", ")}
          {order.items.length > 3 ? `, +${order.items.length - 3} more` : ""}
        </div>
      </div>
      <div style={{ textAlign: "right", flexShrink: 0, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6 }}>
        <span className="num" style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>{money(order.total)}</span>
        <span style={{ fontSize: 11, color: "var(--navy)", fontWeight: 500,
                       display: "inline-flex", alignItems: "center", gap: 4 }}>
          Reorder <Icons.Chevron size={11} stroke={2} />
        </span>
      </div>
    </button>
  );
}

window.Orders = Orders;
