/* Shop.jsx — Love Park merchandise page (CR #264).
   Storefront pulls live catalog from /api/shop (GET). Cart state lives
   in component state; on checkout we POST to /api/shop and redirect to
   the Stripe-hosted page. Off-nav: JJ asked for this page to not appear
   in header/footer; reach it via /#shop direct URL.

   Both GET (list) and POST (create session) share a single Vercel
   serverless function -- POST with a stripe-signature header is the
   Stripe webhook path. This keeps the project under the Hobby plan's
   12-function cap.

   Until SHOP_LIVE=true is set on the Vercel project, POST /api/shop
   returns 503 and the UI surfaces a friendly preview-mode message. */

// Fallback design mockups when no image_url is returned. Each composites
// the official Love Park logo (CR #265 attachment) onto a simple garment
// shape so a brand-new client storefront can render before product photos
// are shot.
const LOGO_HREF = "/img/shop/lovepark-logo.png";
const SHOP_DESIGNS = {
  'lp-red-jacket': (
    <svg viewBox="0 0 200 220" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style={{ width: "100%", height: "100%" }}>
      <rect x="40" y="40" width="120" height="160" rx="8" fill="var(--c-primary)" stroke="var(--c-ink)" strokeWidth="2" />
      <path d="M40,40 L70,20 L130,20 L160,40 Z" fill="var(--c-primary)" stroke="var(--c-ink)" strokeWidth="2" />
      <line x1="100" y1="40" x2="100" y2="200" stroke="var(--c-ink)" strokeWidth="1.5" strokeDasharray="3 3" />
      <image href={LOGO_HREF} x="108" y="62" width="44" height="42" preserveAspectRatio="xMidYMid meet" />
    </svg>
  ),
  'lp-tee': (
    <svg viewBox="0 0 200 220" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style={{ width: "100%", height: "100%" }}>
      <path d="M50,60 L80,30 L120,30 L150,60 L170,80 L150,100 L150,200 L50,200 L50,100 L30,80 Z" fill="#cfeaf3" stroke="var(--c-ink)" strokeWidth="2" />
      <image href={LOGO_HREF} x="65" y="95" width="70" height="68" preserveAspectRatio="xMidYMid meet" />
    </svg>
  ),
  'lp-mug': (
    <svg viewBox="0 0 200 220" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style={{ width: "100%", height: "100%" }}>
      <rect x="40" y="60" width="100" height="120" rx="8" fill="var(--c-cream)" stroke="var(--c-ink)" strokeWidth="2" />
      <path d="M140,90 q30,0 30,30 q0,30 -30,30" fill="none" stroke="var(--c-ink)" strokeWidth="3" />
      <image href={LOGO_HREF} x="52" y="92" width="76" height="74" preserveAspectRatio="xMidYMid meet" />
    </svg>
  ),
  'lp-paddles': (
    <svg viewBox="0 0 200 220" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style={{ width: "100%", height: "100%" }}>
      <ellipse cx="78" cy="100" rx="34" ry="42" fill="var(--c-primary)" stroke="var(--c-ink)" strokeWidth="2" />
      <rect x="70" y="138" width="16" height="60" rx="3" fill="#c8a070" stroke="var(--c-ink)" strokeWidth="2" />
      <ellipse cx="130" cy="100" rx="34" ry="42" fill="var(--c-primary)" stroke="var(--c-ink)" strokeWidth="2" transform="rotate(8 130 100)" />
      <rect x="122" y="138" width="16" height="60" rx="3" fill="#c8a070" stroke="var(--c-ink)" strokeWidth="2" transform="rotate(8 130 168)" />
      <image href={LOGO_HREF} x="62" y="80" width="32" height="32" preserveAspectRatio="xMidYMid meet" />
    </svg>
  ),
};

const SWATCH_FOR_SLUG = {
  'lp-red-jacket': 'var(--c-primary)',
  'lp-tee': '#cfeaf3',
  'lp-mug': 'var(--c-cream-deep)',
  'lp-paddles': 'var(--c-cream-deep)',
};

const fmtUsd = (cents) => (cents / 100).toLocaleString('en-US', { style: 'currency', currency: 'USD' });

function ShopPage() {
  const [products, setProducts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [cart, setCart] = React.useState([]); // [{slug, size, qty, name, price_cents}]
  const [checkoutError, setCheckoutError] = React.useState("");
  const [checkingOut, setCheckingOut] = React.useState(false);
  const [cartOpen, setCartOpen] = React.useState(false);

  React.useEffect(() => {
    fetch('/api/shop')
      .then(r => r.ok ? r.json() : { ok: false })
      .then(j => setProducts(j.rows || []))
      .catch(() => setProducts([]))
      .finally(() => setLoading(false));
  }, []);

  const addToCart = (product, size) => {
    setCart(prev => {
      const key = `${product.slug}__${size || ''}`;
      const idx = prev.findIndex(i => `${i.slug}__${i.size || ''}` === key);
      if (idx >= 0) {
        const next = prev.slice();
        next[idx] = { ...next[idx], qty: Math.min(99, next[idx].qty + 1) };
        return next;
      }
      return [...prev, { slug: product.slug, name: product.name, size: size || null, qty: 1, price_cents: product.price_cents }];
    });
    setCartOpen(true);
  };

  const updateQty = (idx, qty) => {
    setCart(prev => {
      if (qty <= 0) return prev.filter((_, i) => i !== idx);
      const next = prev.slice();
      next[idx] = { ...next[idx], qty: Math.min(99, qty) };
      return next;
    });
  };

  const removeLine = (idx) => setCart(prev => prev.filter((_, i) => i !== idx));

  const subtotalCents = cart.reduce((sum, i) => sum + i.price_cents * i.qty, 0);

  const checkout = async () => {
    if (!cart.length) return;
    setCheckingOut(true);
    setCheckoutError("");
    try {
      const r = await fetch('/api/shop', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ items: cart.map(i => ({ slug: i.slug, size: i.size, qty: i.qty })) }),
      });
      const j = await r.json().catch(() => ({}));
      if (r.status === 503 && j.error === 'shop_not_live') {
        setCheckoutError(j.message || "The shop isn't taking payments yet.");
      } else if (!j.ok || !j.url) {
        setCheckoutError(j.error ? `Checkout failed: ${j.error}` : "Couldn't start checkout. Try again.");
      } else {
        window.location.href = j.url;
        return;
      }
    } catch (e) {
      setCheckoutError(`Network error: ${e.message || e}`);
    } finally {
      setCheckingOut(false);
    }
  };

  return (
    <div>
      {/* Hero -- Love Park red with the LOVE YOUR PARKS billboard backdrop */}
      <section style={{
        position: "relative",
        background: "var(--c-primary)",
        color: "var(--c-cream)",
        borderBottom: "2px solid var(--c-ink)",
        overflow: "hidden",
      }}>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: "url(/img/shop/lovepark-atmosphere.jpg)",
          backgroundSize: "cover",
          backgroundPosition: "center",
          opacity: 0.32,
          mixBlendMode: "multiply",
        }} aria-hidden="true" />
        <div className="container" style={{ padding: "96px 0 64px", position: "relative" }}>
          <div className="eyebrow" style={{ color: "var(--c-cream)", opacity: 0.85 }}>Love Park Merch</div>
          <h1 className="display" style={{ fontSize: "clamp(54px, 9vw, 132px)", margin: "12px 0 18px", lineHeight: 0.92, color: "var(--c-cream)" }}>
            Wear the<br /><span style={{ fontStyle: "italic" }}>park.</span>
          </h1>
          <p style={{ fontSize: 19, maxWidth: 640, lineHeight: 1.55, opacity: 0.95 }}>
            Every jacket, tee, mug, and paddle set funds free and low-cost programming at Love Park —
            performances, community workshops, and youth nights that bring the park to life.
          </p>
        </div>
      </section>

      {/* About */}
      <section className="section">
        <div className="container" style={{ maxWidth: 820 }}>
          <div className="eyebrow">Why this merch exists</div>
          <h2 className="display" style={{ fontSize: "clamp(34px, 5vw, 60px)", marginTop: 12, lineHeight: 1.05 }}>
            100% of net proceeds fund Love Park programming.
          </h2>
          <p style={{ fontSize: 17, lineHeight: 1.6, color: "var(--c-ink)", marginTop: 18 }}>
            Philadelphia Parks &amp; Recreation runs a year-round slate of
            free performances and community events at Love Park. From spring jazz showcases to
            December tree-lighting concerts to summer family movie nights, every program is funded
            by ticket-free, donation-driven support. This merch line is the most direct way to keep
            those nights happening.
          </p>
          <p style={{ fontSize: 17, lineHeight: 1.6, color: "var(--c-ink)", marginTop: 14 }}>
            When you buy a jacket, you're paying for an entire family's night out — admission, the
            stage, the sound crew, all of it. Thank you.
          </p>
        </div>
      </section>

      {/* Events */}
      <section className="section-tight" style={{ background: "var(--c-cream-deep)", borderTop: "2px solid var(--c-ink)", borderBottom: "2px solid var(--c-ink)" }}>
        <div className="container" style={{ maxWidth: 820 }}>
          <div className="eyebrow">Coming up at Love Park</div>
          <h3 className="display" style={{ fontSize: "clamp(26px, 4vw, 44px)", marginTop: 12, lineHeight: 1.1 }}>
            What your support pays for.
          </h3>
          <ul style={{ marginTop: 18, paddingLeft: 18, fontSize: 16, lineHeight: 1.7, color: "var(--c-ink)" }}>
            <li><strong>Spring jazz showcase</strong> — community ensembles, every Sunday afternoon in May and June.</li>
            <li><strong>Youth open-mic nights</strong> — first Friday of every month, ages 13–18, no entry fee.</li>
            <li><strong>Summer family movies</strong> — projector + popcorn + lawn chairs, every other Thursday in July.</li>
            <li><strong>Tree-lighting concert</strong> — first weekend of December, MECE City Choir + neighborhood youth choirs.</li>
          </ul>
          {/* CR #266: shortcut links to the official phila.gov events list +
              the Love Park Philly Instagram so shoppers can see what's on. */}
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 22 }}>
            <a
              href="https://www.phila.gov/the-latest/all-events/?category=Love%20Park%20events"
              target="_blank"
              rel="noopener"
              className="btn small"
            >
              Full Love Park events calendar ↗
            </a>
            <a
              href="https://www.instagram.com/loveparkphilly/"
              target="_blank"
              rel="noopener"
              className="btn small secondary"
            >
              Follow @loveparkphilly ↗
            </a>
          </div>
          <p style={{ fontSize: 13, color: "var(--c-ink-soft)", marginTop: 14, fontStyle: "italic" }}>
            Specific dates posted on the events calendar each season.
          </p>
        </div>
      </section>

      {/* Catalog */}
      <section className="section">
        <div className="container">
          <div className="eyebrow">Shop</div>
          <h2 className="display" style={{ fontSize: "clamp(32px, 5vw, 56px)", marginTop: 12, marginBottom: 28, lineHeight: 1.05 }}>
            The line.
          </h2>
          {loading
            ? <div style={{ color: "var(--c-ink-soft)", fontSize: 14 }}>Loading catalog…</div>
            : products.length === 0
              ? <div style={{ color: "var(--c-ink-soft)", fontSize: 14 }}>Catalog coming soon. Email JJ to pre-order.</div>
              : (
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 24 }} className="shop-grid">
                  {products.map(p => <ProductCard key={p.slug} product={p} onAdd={addToCart} />)}
                </div>
              )
          }
        </div>
        <style>{`
          @media (max-width: 900px) { .shop-grid { grid-template-columns: 1fr 1fr !important; } }
          @media (max-width: 600px) { .shop-grid { grid-template-columns: 1fr !important; } }
        `}</style>
      </section>

      {/* Pre-order / inquiry CTA -- CR #265/#271: contact is Andrew Emma,
          with his photo + short bio. */}
      <section className="section-tight" style={{ background: "var(--c-ink)", color: "var(--c-cream)" }}>
        <div className="container">
          <div className="card andrew-card" style={{
            background: "var(--c-primary)",
            color: "var(--c-cream)",
            padding: 32,
            display: "grid",
            gridTemplateColumns: "220px 1fr",
            gap: 28,
            alignItems: "center",
          }}>
            <div style={{
              borderRadius: 18,
              overflow: "hidden",
              border: "2px solid var(--c-ink)",
              boxShadow: "var(--shadow-lift)",
              aspectRatio: "1/1",
            }}>
              <img
                src="/img/shop/andrew-emma.jpg"
                alt="Andrew Emma, Manager of Love Park, in front of the LOVE sculpture"
                style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
                loading="lazy"
              />
            </div>
            <div>
              <div className="eyebrow" style={{ color: "var(--c-cream)", opacity: 0.85 }}>Manager of Love Park</div>
              <div className="display" style={{ fontSize: 36, marginTop: 6, lineHeight: 1, color: "var(--c-cream)" }}>
                Andrew Emma.
              </div>
              <p style={{ fontSize: 14, marginTop: 12, color: "var(--c-cream)", opacity: 0.95, lineHeight: 1.55 }}>
                Andrew is the Manager of Love Park for the Philadelphia Parks &amp;
                Recreation department, a position he&rsquo;s held since September 2018.
                During this time, he&rsquo;s developed and supported diverse programming
                that has brought nearly 1,000 weddings, 7 seasons of Friday evening
                salsa, multiple installations in partnership with Mural Arts, and
                numerous other activations featuring a wide array of local creatives.
              </p>
              <p style={{ fontSize: 14, marginTop: 10, color: "var(--c-cream)", opacity: 0.9, lineHeight: 1.55 }}>
                Prior to this role, his work at PPR included creating TreeKeepers, a
                workforce development program that combined reentry and sustainable
                land care, and expanding a Standards &amp; Inspections program for all
                citywide park assets.
              </p>
              <div style={{ marginTop: 16 }}>
                <a
                  href="mailto:Andrew.Emma@Phila.gov?subject=Love%20Park%20Merch%20%E2%80%94%20Pre-order"
                  className="btn"
                  style={{ background: "var(--c-cream)", color: "var(--c-ink)" }}
                >
                  Email Andrew →
                </a>
              </div>
            </div>
          </div>
        </div>
        <style>{`
          @media (max-width: 720px) {
            .andrew-card { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </section>

      {/* Sticky cart button + drawer */}
      {cart.length > 0 && (
        <CartFloater
          cart={cart}
          subtotalCents={subtotalCents}
          open={cartOpen}
          setOpen={setCartOpen}
          updateQty={updateQty}
          removeLine={removeLine}
          checkout={checkout}
          checkingOut={checkingOut}
          checkoutError={checkoutError}
        />
      )}
    </div>
  );
}

function ProductCard({ product, onAdd }) {
  const sizes = (product.sizes || "").split(",").map(s => s.trim()).filter(Boolean);
  const [size, setSize] = React.useState(sizes[0] || "");
  const swatch = SWATCH_FOR_SLUG[product.slug] || "var(--c-cream-deep)";
  return (
    <div className="card" style={{ padding: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
      <div style={{ background: swatch, aspectRatio: "1/1", display: "flex", alignItems: "center", justifyContent: "center", padding: 24, borderBottom: "2px solid var(--c-ink)" }}>
        {product.image_url
          ? <img src={product.image_url} alt={product.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} loading="lazy" />
          : (SHOP_DESIGNS[product.slug] || <div style={{ color: "var(--c-ink-soft)", fontSize: 12 }}>{product.name}</div>)}
      </div>
      <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 12, flex: 1 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12 }}>
          <div className="display" style={{ fontSize: 22, lineHeight: 1.1 }}>{product.name}</div>
          <div className="display" style={{ fontSize: 22, color: "var(--c-primary)" }}>{fmtUsd(product.price_cents)}</div>
        </div>
        {product.blurb && (
          <p style={{ fontSize: 14, lineHeight: 1.55, color: "var(--c-ink)", margin: 0 }}>{product.blurb}</p>
        )}
        {sizes.length > 1 && (
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {sizes.map(s => (
              <button
                key={s}
                type="button"
                onClick={() => setSize(s)}
                className="chip"
                style={{
                  cursor: "pointer",
                  background: size === s ? "var(--c-ink)" : "var(--c-paper)",
                  color: size === s ? "var(--c-cream)" : "var(--c-ink)",
                  border: "1px solid var(--c-ink)",
                }}
              >{s}</button>
            ))}
          </div>
        )}
        {sizes.length === 1 && (
          <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--c-ink-soft)" }}>{sizes[0]}</div>
        )}
        <button
          type="button"
          className="btn small"
          style={{ marginTop: "auto", width: "100%", justifyContent: "center" }}
          onClick={() => onAdd(product, size)}
        >
          Add to cart →
        </button>
      </div>
    </div>
  );
}

function CartFloater({ cart, subtotalCents, open, setOpen, updateQty, removeLine, checkout, checkingOut, checkoutError }) {
  const totalQty = cart.reduce((n, i) => n + i.qty, 0);
  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        style={{
          position: "fixed", right: 24, bottom: 24, zIndex: 90,
          background: "var(--c-ink)", color: "var(--c-cream)",
          padding: "14px 22px", borderRadius: 999, border: "2px solid var(--c-ink)",
          cursor: "pointer", fontWeight: 600, boxShadow: "var(--shadow-lift)",
          display: "flex", alignItems: "center", gap: 10,
        }}
      >
        🛍 {totalQty} {totalQty === 1 ? "item" : "items"} · {fmtUsd(subtotalCents)}
      </button>
      {open && (
        <div
          onClick={() => setOpen(false)}
          style={{
            position: "fixed", inset: 0, zIndex: 91,
            background: "rgba(42,24,32,0.55)",
            display: "flex", justifyContent: "flex-end",
          }}
        >
          <div
            onClick={e => e.stopPropagation()}
            style={{
              background: "var(--c-paper)", width: "100%", maxWidth: 440,
              borderLeft: "2px solid var(--c-ink)",
              display: "flex", flexDirection: "column", height: "100vh",
            }}
          >
            <div style={{ padding: 24, borderBottom: "2px solid var(--c-ink)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div className="display" style={{ fontSize: 24 }}>Cart</div>
              <button onClick={() => setOpen(false)} className="pill" style={{ cursor: "pointer" }}>close</button>
            </div>
            <div style={{ flex: 1, overflowY: "auto", padding: 16 }}>
              {cart.map((i, idx) => (
                <div key={`${i.slug}-${i.size}-${idx}`} style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 12, padding: "12px 8px", borderBottom: "1px solid var(--c-ink-soft)" }}>
                  <div>
                    <div style={{ fontWeight: 600 }}>{i.name}</div>
                    {i.size && <div style={{ fontSize: 12, color: "var(--c-ink-soft)" }}>{i.size}</div>}
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8 }}>
                      <button type="button" onClick={() => updateQty(idx, i.qty - 1)} className="pill" style={{ cursor: "pointer", padding: "2px 10px" }}>−</button>
                      <span style={{ minWidth: 24, textAlign: "center" }}>{i.qty}</span>
                      <button type="button" onClick={() => updateQty(idx, i.qty + 1)} className="pill" style={{ cursor: "pointer", padding: "2px 10px" }}>+</button>
                      <button type="button" onClick={() => removeLine(idx)} style={{ background: "none", border: "none", color: "var(--c-primary-deep)", cursor: "pointer", fontSize: 12, marginLeft: 6 }}>remove</button>
                    </div>
                  </div>
                  <div style={{ textAlign: "right", fontWeight: 600 }}>{fmtUsd(i.price_cents * i.qty)}</div>
                </div>
              ))}
            </div>
            <div style={{ padding: 20, borderTop: "2px solid var(--c-ink)", background: "var(--c-cream)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                <span>Subtotal</span><span style={{ fontWeight: 600 }}>{fmtUsd(subtotalCents)}</span>
              </div>
              <div style={{ fontSize: 12, color: "var(--c-ink-soft)", marginBottom: 14 }}>Shipping and tax calculated at checkout.</div>
              {checkoutError && (
                <div style={{ fontSize: 13, color: "var(--c-primary-deep)", marginBottom: 10, padding: 10, background: "var(--c-paper)", border: "1px solid var(--c-primary)", borderRadius: 6 }}>
                  {checkoutError}
                </div>
              )}
              <button
                type="button"
                onClick={checkout}
                disabled={checkingOut || cart.length === 0}
                className="btn"
                style={{ width: "100%", justifyContent: "center", cursor: checkingOut ? "wait" : "pointer", opacity: checkingOut ? 0.7 : 1 }}
              >
                {checkingOut ? "Starting checkout…" : "Check out →"}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

/* Success screen rendered when Stripe redirects back to /#shop-success?ref=... */
function ShopSuccessPage() {
  const params = new URLSearchParams(window.location.hash.split("?")[1] || "");
  const ref = params.get("ref") || "";
  return (
    <section className="section" style={{ background: "var(--c-cream)", minHeight: "60vh", display: "flex", alignItems: "center" }}>
      <div className="container" style={{ maxWidth: 720, textAlign: "center" }}>
        <div style={{ fontSize: 80, marginBottom: 18 }}>✦</div>
        <h2 className="display" style={{ fontSize: "clamp(40px, 7vw, 80px)", marginBottom: 18 }}>
          Order placed.
        </h2>
        <p style={{ fontSize: 18, color: "var(--c-ink-soft)", lineHeight: 1.55, maxWidth: 560, margin: "0 auto 16px" }}>
          {ref ? <>Reference <strong>{ref}</strong>. </> : null}
          We've emailed you a confirmation. JJ will follow up when your order ships.
        </p>
        <p style={{ fontSize: 14, color: "var(--c-ink-soft)", margin: "0 auto 28px" }}>
          Thank you for supporting Love Park programming.
        </p>
        <a href="#shop" className="btn">Back to shop</a>
      </div>
    </section>
  );
}

Object.assign(window, { ShopPage, ShopSuccessPage });
