/* global React */
// ============================================================
// WAVE AIR · STUDIO (V6) — product / cart / checkout. -> window.DGV6
// Checkout is wired to the real Stripe-hosted flow (/api/checkout).
// ============================================================
(function () {
const { useState } = React;
const { Icon, PRODUCT, money, useShop } = window.DGShop;

// Convex product slug this storefront sells.
const PRODUCT_SLUG = "disco-gringo-tee";

const colorBg = (k) => (PRODUCT.colors.find((c) => c.key === k) || PRODUCT.colors[0]).bg;
const back = { display: "inline-flex", alignItems: "center", gap: 7, background: "none", border: 0, cursor: "pointer", fontFamily: "var(--w-mono)", fontWeight: 700, fontSize: "0.74rem", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--w-ink2)", padding: 0 };

// garment tint behind the mockup print
const tints = { white: "transparent", pink: "rgba(232,160,192,0.32)", teal: "rgba(46,158,146,0.30)", ink: "rgba(27,23,19,0.55)" };

function TeeView({ color }) {
  return (
    <div style={{ position: "relative", width: "100%", aspectRatio: "1", borderRadius: 18, overflow: "hidden", background: "var(--w-paper)", border: "2.5px solid var(--w-ink)", boxShadow: "6px 6px 0 0 var(--w-ink)" }}>
      <img src="assets/scene/tee-blank.jpg" alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
      {tints[color] !== "transparent" && (
        <div style={{ position: "absolute", inset: 0, background: tints[color], mixBlendMode: "multiply", pointerEvents: "none" }} />
      )}
      <img src="assets/wave-air-tee-web.png" alt="WAVE AIR print" style={{ position: "absolute", left: "50%", top: "32.5%", width: "33%", transform: "translateX(-50%)", mixBlendMode: color === "ink" ? "screen" : "multiply" }} />
      <span className="w-mono" style={{ position: "absolute", bottom: 14, left: 14, fontSize: "0.68rem", letterSpacing: "0.08em", color: "var(--w-ink2)", background: "rgba(244,239,230,0.8)", padding: "3px 9px", borderRadius: 999 }}>SHOWN IN {(PRODUCT.colors.find((c) => c.key === color) || {}).name?.toUpperCase()}</span>
    </div>
  );
}

// ---------------- PRODUCT PAGE ----------------
function Product6() {
  const { addToCart, navigate } = useShop();
  const [color, setColor] = useState("white");
  const [size, setSize] = useState("M");
  const [qty, setQty] = useState(1);
  const [shake, setShake] = useState(false);
  const c = PRODUCT.colors.find((x) => x.key === color);
  const add = (then) => { if (!size) { setShake(true); setTimeout(() => setShake(false), 500); return; } addToCart({ id: "wave-air", color, colorName: c.name, size, qty, price: PRODUCT.price, art: PRODUCT.art }); if (then) then(); };
  return (
    <div className="w-wrap" style={{ padding: "92px 40px 80px" }}>
      <button onClick={() => navigate("home")} style={{ ...back, marginBottom: 18 }}><Icon name="arrow-left" size={15} /> Back to the drop</button>
      <div className="w-pdp" style={{ display: "grid", gridTemplateColumns: "1fr 0.92fr", gap: 50, alignItems: "start" }}>
        <div style={{ position: "sticky", top: 88 }} className="w-pdp-fig"><TeeView color={color} /></div>
        <div className={shake ? "w-shake" : ""}>
          <span className="w-kicker">Drop 001 · numbered run</span>
          <h1 className="w-disp" style={{ fontSize: "clamp(2.4rem,5vw,3.6rem)", margin: "8px 0 8px" }}>WAVE AIR TEE</h1>
          <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 18 }}>
            <span className="w-disp" style={{ fontSize: "2.4rem" }}>{money(PRODUCT.price)}</span>
            <span className="w-mono" style={{ textDecoration: "line-through", color: "var(--w-ink2)" }}>{money(PRODUCT.compareAt)}</span>
            <span className="w-mono" style={{ color: "var(--w-teal-deep)", fontWeight: 700, fontSize: "0.8rem" }}>SAVE {money(PRODUCT.compareAt - PRODUCT.price)}</span>
          </div>
          <p className="w-body" style={{ maxWidth: 440, marginBottom: 22 }}>{PRODUCT.blurb}</p>

          <div className="w-lab" style={{ marginBottom: 9 }}>Garment — {c.name}</div>
          <div style={{ display: "flex", gap: 13, marginBottom: 22 }}>
            {PRODUCT.colors.map((x) => <button key={x.key} className={`w-swatch ${color === x.key ? "on" : ""}`} aria-label={x.name} onClick={() => setColor(x.key)} style={{ background: x.bg }} />)}
          </div>

          <div className="w-lab" style={{ marginBottom: 9 }}>Size</div>
          <div style={{ display: "flex", gap: 9, marginBottom: 24, flexWrap: "wrap" }}>
            {PRODUCT.sizes.map((s) => <button key={s.k} disabled={!s.on} onClick={() => s.on && setSize(s.k)} className={`w-size ${size === s.k ? "on" : ""} ${!s.on ? "off" : ""}`}>{s.k}</button>)}
          </div>

          <div style={{ display: "flex", gap: 14, alignItems: "center", marginBottom: 14, flexWrap: "wrap" }}>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 10, border: "2px solid var(--w-ink)", borderRadius: 999, padding: "5px 8px" }}>
              <button className="w-step" onClick={() => setQty((q) => Math.max(1, q - 1))}>–</button>
              <span className="w-mono" style={{ minWidth: 22, textAlign: "center", fontWeight: 700 }}>{qty}</span>
              <button className="w-step" onClick={() => setQty((q) => q + 1)}>+</button>
            </div>
            <button className="w-btn lg" style={{ flex: 1, minWidth: 200 }} onClick={() => add()}>Add to bag · {money(PRODUCT.price * qty)}</button>
          </div>
          <button className="w-btn teal full lg" onClick={() => add(() => navigate("checkout"))}>Buy it now</button>

          <div style={{ marginTop: 24, borderTop: "1px solid var(--w-line)", paddingTop: 18, display: "grid", gap: 9 }}>
            {[["truck", "Printed & shipped worldwide by Gelato"], ["rotate-ccw", "30-day no-drama returns"], ["badge-check", "Numbered & authenticity-stamped"]].map(([ic, t]) => (
              <div key={t} style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--w-ink2)" }}><Icon name={ic} size={17} color="var(--w-teal-deep)" /><span className="w-body" style={{ fontSize: "0.96rem" }}>{t}</span></div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------------- CART ----------------
function Thumb({ item, size = 64 }) {
  return (
    <div style={{ width: size, height: size, flexShrink: 0, background: colorBg(item.color), border: "2px solid var(--w-ink)", borderRadius: 8, display: "grid", placeItems: "center", overflow: "hidden" }}>
      <img src={item.art} alt="" style={{ width: "84%", height: "84%", objectFit: "contain" }} draggable={false} />
    </div>
  );
}
function Step({ qty, onDec, onInc }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 8, border: "2px solid var(--w-ink)", borderRadius: 999, padding: "3px 6px" }}>
      <button className="w-step" style={{ width: 28, height: 28, fontSize: 15 }} onClick={onDec}>–</button>
      <span className="w-mono" style={{ minWidth: 18, textAlign: "center", fontWeight: 700 }}>{qty}</span>
      <button className="w-step" style={{ width: 28, height: 28, fontSize: 15 }} onClick={onInc}>+</button>
    </div>
  );
}
function CartDrawer6() {
  const { drawer, setDrawer, cart, updateQty, removeItem, subtotal, navigate, count } = useShop();
  return (
    <React.Fragment>
      <div className={`w-scrim ${drawer ? "open" : ""}`} onClick={() => setDrawer(false)} />
      <aside className={`w-drawer ${drawer ? "open" : ""}`} aria-hidden={!drawer}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 20px", borderBottom: "2.5px solid var(--w-ink)", background: "var(--w-pink)" }}>
          <div className="w-disp" style={{ fontSize: "1.4rem" }}>YOUR BAG · {count}</div>
          <button onClick={() => setDrawer(false)} aria-label="Close" style={{ width: 34, height: 34, border: "2px solid var(--w-ink)", background: "var(--w-paper)", cursor: "pointer", borderRadius: 8, display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="x" size={18} /></button>
        </div>
        <div className="no-bar" style={{ flex: 1, overflowY: "auto", padding: cart.length ? "12px 18px" : 0 }}>
          {cart.length === 0 ? (
            <div style={{ textAlign: "center", padding: "50px 20px" }}>
              <div className="w-disp" style={{ fontSize: "1.5rem", marginBottom: 8 }}>BAG'S EMPTY</div>
              <p className="w-body" style={{ marginBottom: 20 }}>No tees on board yet. Sit tight — the plane's loading.</p>
              <button className="w-btn" onClick={() => { setDrawer(false); navigate("product"); }}>Shop the tee</button>
            </div>
          ) : cart.map((item, i) => (
            <div key={item.color + item.size} style={{ display: "flex", gap: 12, padding: "12px 0", borderBottom: "1px solid var(--w-line)" }}>
              <Thumb item={item} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                  <span className="w-head" style={{ fontSize: "1rem" }}>WAVE AIR tee</span>
                  <button onClick={() => removeItem(i)} style={{ background: "none", border: 0, cursor: "pointer", color: "var(--w-ink2)" }}><Icon name="trash-2" size={16} /></button>
                </div>
                <div className="w-mono" style={{ fontSize: "0.72rem", color: "var(--w-ink2)", margin: "3px 0 9px" }}>{item.colorName.toUpperCase()} · {item.size}</div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <Step qty={item.qty} onDec={() => updateQty(i, item.qty - 1)} onInc={() => updateQty(i, item.qty + 1)} />
                  <span className="w-disp" style={{ fontSize: "1.15rem" }}>{money(item.price * item.qty)}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
        {cart.length > 0 && (
          <div style={{ borderTop: "2.5px solid var(--w-ink)", padding: "16px 20px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 12 }}>
              <span className="w-head" style={{ fontSize: "1.05rem" }}>Subtotal</span>
              <span className="w-disp" style={{ fontSize: "1.5rem" }}>{money(subtotal)}</span>
            </div>
            <button className="w-btn teal full lg" onClick={() => { setDrawer(false); navigate("checkout"); }}>Checkout</button>
          </div>
        )}
      </aside>
    </React.Fragment>
  );
}

// ---------------- CHECKOUT (real Stripe) ----------------
function Checkout6() {
  const { cart, subtotal, navigate } = useShop();
  const [submitting, setSubmitting] = useState(false);
  const [err, setErr] = useState("");

  if (cart.length === 0) {
    return (
      <div className="w-wrap" style={{ padding: "120px 40px", textAlign: "center", minHeight: "60vh" }}>
        <div className="w-disp" style={{ fontSize: "2.2rem", marginBottom: 10 }}>NOTHING TO CHECK OUT</div>
        <p className="w-body" style={{ marginBottom: 20 }}>Your bag's empty — grab the tee first.</p>
        <button className="w-btn" onClick={() => navigate("product")}>Shop the tee</button>
      </div>
    );
  }

  const pay = async () => {
    setErr(""); setSubmitting(true);
    try {
      const items = cart.map((x) => ({
        slug: PRODUCT_SLUG, size: x.size, color: x.color, colorName: x.colorName, quantity: x.qty,
      }));
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ items }),
      });
      const data = await res.json();
      if (!res.ok || !data.url) throw new Error(data.error || "Checkout failed");
      window.location.href = data.url;
    } catch (e) {
      setErr(e.message || "Something went wrong");
      setSubmitting(false);
    }
  };

  return (
    <div className="w-wrap" style={{ padding: "92px 40px 80px" }}>
      <button onClick={() => navigate("product")} style={{ ...back, marginBottom: 18 }}><Icon name="arrow-left" size={15} /> Keep shopping</button>
      <h1 className="w-disp" style={{ fontSize: "clamp(2.2rem,5vw,3.4rem)", margin: "0 0 28px" }}>CHECKOUT</h1>
      <div className="w-co" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 36, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="w-card">
            <div className="w-head" style={{ fontSize: "1.2rem", marginBottom: 10 }}>Secure checkout</div>
            <p className="w-body" style={{ margin: "0 0 14px" }}>
              You'll enter your email, worldwide shipping address and card details on the next step — handled securely by Stripe. Printed &amp; shipped by Gelato.
            </p>
            <div style={{ display: "grid", gap: 9, marginBottom: 6 }}>
              {[["lock", "Payments secured by Stripe"], ["globe", "Ships worldwide"], ["package", "Printed on demand by Gelato"]].map(([ic, t]) => (
                <div key={t} style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--w-ink2)" }}><Icon name={ic} size={17} color="var(--w-teal-deep)" /><span className="w-body" style={{ fontSize: "0.96rem" }}>{t}</span></div>
              ))}
            </div>
          </div>
          {err && <span className="w-mono" style={{ color: "var(--w-pink-deep)", fontSize: "0.82rem" }}>{err}</span>}
          <button className="w-btn full lg" disabled={submitting} style={{ opacity: submitting ? 0.6 : 1 }} onClick={pay}>
            {submitting ? "Redirecting to Stripe…" : `Pay ${money(subtotal)} securely`}
          </button>
        </div>
        <div className="w-card" style={{ position: "sticky", top: 88 }}>
          <div className="w-head" style={{ fontSize: "1.2rem", marginBottom: 14 }}>Order summary</div>
          {cart.map((item) => (
            <div key={item.color + item.size} style={{ display: "flex", gap: 10, alignItems: "center", padding: "7px 0" }}>
              <Thumb item={item} size={46} />
              <div style={{ flex: 1, minWidth: 0 }}><div className="w-head" style={{ fontSize: "0.95rem" }}>WAVE AIR ×{item.qty}</div><div className="w-mono" style={{ fontSize: "0.7rem", color: "var(--w-ink2)" }}>{item.colorName} · {item.size}</div></div>
              <span className="w-head" style={{ fontSize: "0.95rem" }}>{money(item.price * item.qty)}</span>
            </div>
          ))}
          <div style={{ borderTop: "1px solid var(--w-line)", marginTop: 8, paddingTop: 10 }}>
            <div style={{ display: "flex", justifyContent: "space-between" }}><span className="w-body" style={{ fontSize: "0.95rem" }}>Shipping</span><span className="w-head" style={{ fontSize: "0.95rem", color: "var(--w-teal-deep)" }}>Free</span></div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 8 }}><span className="w-head" style={{ fontSize: "1.15rem" }}>Total</span><span className="w-disp" style={{ fontSize: "1.8rem" }}>{money(subtotal)}</span></div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Toast6() {
  const { toast } = useShop();
  if (!toast) return null;
  return (
    <div style={{ position: "fixed", left: "50%", bottom: 26, transform: "translateX(-50%)", zIndex: 90, border: "2.5px solid var(--w-ink)", background: "var(--w-paper)", borderRadius: 12, padding: "12px 18px", boxShadow: "4px 4px 0 0 var(--w-ink)", display: "flex", alignItems: "center", gap: 12 }}>
      <span style={{ width: 28, height: 28, borderRadius: "50%", background: "var(--w-teal)", border: "2px solid var(--w-ink)", display: "grid", placeItems: "center" }}><Icon name="check" size={15} color="#fff" /></span>
      <div><div className="w-head" style={{ fontSize: "0.92rem" }}>Added to bag</div><div className="w-mono" style={{ fontSize: "0.72rem", color: "var(--w-ink2)" }}>{toast.msg}</div></div>
    </div>
  );
}

Object.assign(window.DGV6, { Product6, CartDrawer6, Checkout6, Toast6 });
})();
