// src/cart.jsx — Cart screen (drawer-style) with delivery summary, tip, promo.

function EmptyCart({ onNav, isMobile }) {
  const nearby = STORES.slice(0, 3);
  const quickCats = [
    { id: "deli",    label: "Deli",    icon: "Baguette" },
    { id: "coffee",  label: "Coffee",  icon: "Coffee" },
    { id: "drinks",  label: "Drinks",  icon: "Snow" },
    { id: "beer",    label: "Beer & Wine", icon: "Beer" },
    { id: "snacks",  label: "Snacks",  icon: "Cookie" },
    { id: "produce", label: "Produce", icon: "Apple" },
  ];
  return (
    <div style={{ maxWidth: 1080, margin: "0 auto", padding: isMobile ? "28px 16px 120px" : "56px 28px 80px" }}>
      {/* Hero */}
      <div style={{
        position: "relative", overflow: "hidden",
        borderRadius: "var(--radius-xl)",
        background: "var(--navy-fill)", color: "#fff",
        padding: isMobile ? "32px 24px" : "48px 44px",
        boxShadow: "var(--shadow-md)",
      }}>
        <div aria-hidden style={{
          position: "absolute", inset: 0,
          background: `
            radial-gradient(780px 340px at 88% -10%, oklch(from var(--accent) l c h / 0.3), transparent 60%),
            radial-gradient(600px 300px at 10% 120%, oklch(from var(--accent) l c h / 0.22), transparent 65%)
          `,
          pointerEvents: "none",
        }} />
        <div style={{ position: "relative", maxWidth: 620 }}>
          <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 }}>
            <Icons.Bag size={12} stroke={2} /> Cart · empty
          </div>
          <h1 className="serif" style={{ fontSize: isMobile ? 32 : 44, lineHeight: 1.05, margin: 0, letterSpacing: "-0.02em" }}>
            Nothing in the bag yet.<br />
            <span style={{ fontStyle: "italic", color: "oklch(from #fff l c h / 0.72)" }}>Tell us what you need.</span>
          </h1>
          <p style={{ marginTop: 12, fontSize: 15, color: "oklch(from #fff l c h / 0.72)", maxWidth: 480, lineHeight: 1.5 }}>
            Describe your evening in one sentence and Opa builds the cart — or pick a store nearby and browse the old-fashioned way.
          </p>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 22 }}>
            <button className="btn-reset" onClick={() => onNav({ screen: "home" })}
              style={{
                height: 48, padding: "0 20px", borderRadius: 999,
                background: "var(--accent)", color: "#fff",
                fontWeight: 600, fontSize: 14,
                display: "inline-flex", alignItems: "center", gap: 8,
              }}>
              <Icons.Sparkle size={15} stroke={2} />
              Ask Opa to build it
            </button>
            <button className="btn-reset" onClick={() => onNav({ screen: "search" })}
              style={{
                height: 48, padding: "0 18px", borderRadius: 999,
                background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.18)",
                color: "#fff", fontWeight: 500, fontSize: 14,
                display: "inline-flex", alignItems: "center", gap: 8,
              }}>
              <Icons.Search size={15} stroke={2} />
              Browse all 412 stores
            </button>
          </div>
        </div>
      </div>

      {/* Quick categories */}
      <div style={{ marginTop: 32 }}>
        <div className="uppercase-mono" style={{ marginBottom: 12 }}>Jump in</div>
        <div style={{
          display: "grid",
          gridTemplateColumns: `repeat(${isMobile ? 3 : 6}, 1fr)`,
          gap: 10,
        }}>
          {quickCats.map(c => {
            const Icon = Icons[c.icon];
            return (
              <button key={c.id} className="btn-reset"
                onClick={() => onNav({ screen: "store", storeId: "kalymnos", category: c.id })}
                style={{
                  display: "flex", flexDirection: "column", alignItems: "center", gap: 8,
                  padding: "18px 10px",
                  background: "var(--surface)", border: "1px solid var(--line)",
                  borderRadius: 14,
                }}>
                <span style={{
                  width: 40, height: 40, borderRadius: "50%",
                  background: "var(--navy-tint)", color: "var(--navy)",
                  display: "grid", placeItems: "center",
                }}>
                  <Icon size={18} stroke={1.8} />
                </span>
                <span style={{ fontSize: 13, fontWeight: 500, color: "var(--ink-2)" }}>{c.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Nearby stores */}
      <div style={{ marginTop: 36 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 12 }}>
          <div className="uppercase-mono">Near 98 Orchard St</div>
          <button className="btn-reset" onClick={() => onNav({ screen: "search" })}
            style={{ fontSize: 13, color: "var(--ink-2)", display: "inline-flex", alignItems: "center", gap: 4 }}>
            See all 412 <Icons.Chevron size={12} stroke={2} />
          </button>
        </div>
        <div style={{
          display: "grid",
          gridTemplateColumns: `repeat(${isMobile ? 1 : 3}, 1fr)`,
          gap: 14,
        }}>
          {nearby.map(s => (
            <button key={s.id} className="btn-reset"
              onClick={() => onNav({ screen: "store", storeId: s.id })}
              style={{
                background: "var(--surface)", border: "1px solid var(--line)",
                borderRadius: 16, overflow: "hidden",
                textAlign: "left", display: "flex", flexDirection: "column",
                boxShadow: "var(--shadow-sm)",
              }}>
              <Ph label={s.hero} aspect="16/9" img={storeImage(s)} seed={s.id}
                  style={{ width: "100%", borderRadius: 0 }} />
              <div style={{ padding: "14px 16px 16px" }}>
                <div style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)" }}>{s.name}</div>
                <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>{s.tagline}</div>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 10, fontSize: 12.5, color: "var(--ink-2)" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                    <Icons.Clock size={12} stroke={1.8} /> {s.eta}
                  </span>
                  <span style={{ color: "var(--ink-4)" }}>·</span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                    <Icons.Pin size={12} stroke={1.8} /> {s.distance}
                  </span>
                  <span style={{ color: "var(--ink-4)" }}>·</span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
                    <Icons.Star size={12} stroke={1.8} style={{ color: "var(--accent)" }} /> {s.rating}
                  </span>
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function Cart({ onNav, cart, addToCart, clear, tweaks, onPlaceOrder }) {
  const isMobile = useMedia("(max-width: 720px)");
  const store = STORES.find(s => s.id === (cart.items[0]?.storeId)) || STORES[0];
  const items = cart.items.map(i => ({ ...i, p: PRODUCT_INDEX[i.productId] })).filter(i => i.p);
  const subtotal = items.reduce((s, i) => s + i.p.price * i.qty, 0);
  const fee = subtotal > 0 ? 1.99 : 0;
  const serviceFee = subtotal > 0 ? Math.max(0.99, subtotal * 0.05) : 0;
  const [tipPct, setTipPct] = React.useState(15);
  const tip = subtotal * (tipPct / 100);
  const total = subtotal + fee + serviceFee + tip;

  if (items.length === 0) {
    return <EmptyCart onNav={onNav} isMobile={isMobile} />;
  }

  return (
    <div style={{ maxWidth: 1080, margin: "0 auto", padding: isMobile ? "14px 16px 120px" : "28px 28px 80px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
        <div>
          <div className="uppercase-mono">Your order</div>
          <h1 className="serif" style={{ fontSize: 36, margin: 0, letterSpacing: "-0.02em" }}>Cart</h1>
        </div>
        <Btn variant="ghost" size="sm" onClick={clear} icon={<Icons.Trash size={14} stroke={1.8} />}>Clear</Btn>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.5fr 1fr", gap: 28 }}>
        <div>
          {/* Store info */}
          <div style={{ padding: 16, borderRadius: 14, background: "var(--surface)", border: "1px solid var(--line)",
                        display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
            <Ph label={store.hero} aspect="1/1" radius={10} img={storeImage(store)} seed={store.id} style={{ width: 52, height: 52 }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15, fontWeight: 600 }}>{store.name}</div>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)" }}>
                <Icons.Truck size={12} stroke={1.8} style={{ verticalAlign: "-2px", marginRight: 4 }} />
                Delivery · {store.eta} · {store.fee}
              </div>
            </div>
            <Btn variant="ghost" size="sm" onClick={() => onNav({ screen: "store", storeId: store.id })} iconRight={<Icons.Chevron size={13} stroke={2} />}>
              Add more
            </Btn>
          </div>

          {/* Items list */}
          <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 14, overflow: "hidden" }}>
            {items.map((i, idx) => (
              <div key={i.productId} style={{
                display: "flex", gap: 14, padding: 14,
                borderBottom: idx < items.length - 1 ? "1px solid var(--line-soft)" : "none",
                alignItems: "center",
              }}>
                <Ph label={i.p.name.split(" ")[0]} aspect="1/1" radius={10} img={productImage(i.p)} seed={i.p.id} style={{ width: 64, height: 64, flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 500, color: "var(--ink)" }}>{i.p.name}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-4)", marginTop: 2 }}>{i.p.unit}</div>
                  <div className="num" style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 4, fontWeight: 500 }}>{money(i.p.price)} each</div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <AddStepper qty={i.qty}
                    onAdd={() => addToCart(store.id, i.productId, 1)}
                    onRemove={() => addToCart(store.id, i.productId, -1)}
                    size="md" pattern="stepper" tone="outline" />
                  <span className="num" style={{ fontSize: 15, fontWeight: 600, minWidth: 64, textAlign: "right" }}>
                    {money(i.p.price * i.qty)}
                  </span>
                </div>
              </div>
            ))}
          </div>

          {/* Suggested add-ons */}
          <div style={{ marginTop: 20 }}>
            <SectionHeader eyebrow="Forgot something?" title="Quick add" />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
              {["drk-topo", "snk-kind", "prd-lime", "hh-advil"].map(id => {
                const p = PRODUCT_INDEX[id];
                return (
                  <div key={id} style={{ padding: 10, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12 }}>
                    <Ph label={p.name.split(" ")[0]} aspect="1/1" radius={8} img={productImage(p)} seed={p.id} />
                    <div style={{ fontSize: 12, fontWeight: 500, marginTop: 6, lineHeight: 1.3,
                                  display: "-webkit-box", WebkitLineClamp: 1, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{p.name}</div>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 6 }}>
                      <span className="num" style={{ fontSize: 12.5, fontWeight: 600 }}>{money(p.price)}</span>
                      <AddStepper qty={0} onAdd={() => addToCart(store.id, id, 1)} onRemove={()=>{}} size="sm" pattern="morph" />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Summary panel */}
        <aside style={{ position: isMobile ? "static" : "sticky", top: 92, alignSelf: "flex-start" }}>
          <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 14, padding: 20 }}>
            <h3 className="serif" style={{ fontSize: 20, margin: "0 0 14px" }}>Summary</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, fontSize: 14, color: "var(--ink-2)" }}>
              <Row l="Subtotal" r={money(subtotal)} />
              <Row l="Delivery" r={money(fee)} />
              <Row l="Service fee" r={money(serviceFee)} sub="5% · supports neighborhood stores" />
            </div>

            <div style={{ margin: "16px 0 8px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8, fontSize: 13, color: "var(--ink-2)" }}>
                <span style={{ fontWeight: 500 }}>Tip for runner</span>
                <span className="num" style={{ fontWeight: 600 }}>{money(tip)}</span>
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                {[10, 15, 20, 25].map(p => (
                  <button key={p} className="btn-reset" onClick={() => setTipPct(p)}
                    style={{ flex: 1, padding: "10px 0", borderRadius: 10,
                             background: tipPct === p ? "var(--navy-fill)" : "var(--surface-2)",
                             color: tipPct === p ? "#fff" : "var(--ink-2)",
                             border: "1px solid " + (tipPct === p ? "transparent" : "var(--line)"),
                             fontSize: 13, fontWeight: 500 }}>
                    {p}%
                  </button>
                ))}
              </div>
            </div>

            <div style={{ height: 1, background: "var(--line)", margin: "16px 0" }} />
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontSize: 16, fontWeight: 600 }}>Total</span>
              <span className="num" style={{ fontSize: 24, fontWeight: 600 }}>{money(total)}</span>
            </div>

            <Btn variant="primary" size="lg" full style={{ marginTop: 16 }}
              onClick={() => onPlaceOrder?.()}>
              Place order · <span className="num" style={{ marginLeft: 4 }}>{money(total)}</span>
            </Btn>
            <div style={{ marginTop: 12, fontSize: 12, color: "var(--ink-4)", textAlign: "center", display: "flex", alignItems: "center", gap: 6, justifyContent: "center" }}>
              <Icons.ShieldCheck size={12} stroke={1.8} /> Secure checkout · arrives in {store.eta}
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

function Row({ l, r, sub }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
      <span>
        <span>{l}</span>
        {sub && <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 1 }}>{sub}</div>}
      </span>
      <span className="num" style={{ fontWeight: 500, color: "var(--ink)" }}>{r}</span>
    </div>
  );
}

window.Cart = Cart;
