/* eslint-disable */
// tienda.jsx — Casa M Spice Co. inline shop on casam.me.
//
// Pulls the live product catalog from casamspice.com/products.json
// (Shopify's public Storefront JSON — no token needed, CORS-friendly),
// renders a multi-select grid with per-product qty +/- controls, and
// builds a Shopify cart-permalink for direct checkout when the user
// is done. Permalink shape:
//   https://casamspice.com/cart/{variantId}:{qty},{variantId}:{qty}
// Cart permalinks land users on the cart page with the items already
// in the cart, ready to check out — no add-to-cart roundtrip.
//
// DrMike 2026-05-27: "WHERE is our SHOP room that is a native SHOP
// interface where you can multi-select a full selection of products
// that are displayed, and go directly to the checkout. Yes please on
// this very page. It's PRIME for that."
//
// Mounted into #tienda-mount when the Tienda card is clicked.
(function () {
  const { useState, useEffect, useMemo } = React;
  const SHOP_BASE = "https://casamspice.com";

  // ─── shopify product loader ──────────────────────────────────────
  // We can't hit casamspice.com/products.json directly from casam.me
  // because Shopify doesn't ship CORS headers on that endpoint. The
  // casam-landing Fastify backend proxies it at /api/shop/products
  // with a 5-min in-memory cache. Same shape comes back.
  async function loadProducts() {
    const r = await fetch(`/api/shop/products`, {
      credentials: "omit",
      headers: { "Accept": "application/json" },
    });
    if (!r.ok) throw new Error(`shop proxy HTTP ${r.status}`);
    const data = await r.json();
    return (data.products || []).filter(p =>
      p.variants?.length > 0 && Number(p.variants[0].price) > 0 &&
      p.published_at && !(p.tags || "").toLowerCase().includes("hidden")
    );
  }

  // ─── price helpers ───────────────────────────────────────────────
  function money(usd) {
    const n = typeof usd === "string" ? Number(usd) : usd;
    if (!isFinite(n)) return "";
    return `$${n.toFixed(2)}`;
  }

  // ─── Tienda component ────────────────────────────────────────────
  function Tienda() {
    const [products, setProducts] = useState(null); // null = loading
    const [error, setError]       = useState(null);
    const [qty, setQty]           = useState({});   // { variantId: number }
    const [busy, setBusy]         = useState(false);

    useEffect(() => {
      loadProducts()
        .then((rows) => setProducts(rows))
        .catch((e) => setError(e.message || "load failed"));
    }, []);

    const itemsInCart = useMemo(
      () => Object.values(qty).reduce((a, b) => a + (Number(b) || 0), 0),
      [qty]
    );
    const subtotal = useMemo(() => {
      if (!products) return 0;
      let t = 0;
      for (const p of products) {
        const v = p.variants[0];
        const q = Number(qty[v.id] || 0);
        if (q > 0) t += q * Number(v.price);
      }
      return t;
    }, [qty, products]);

    function setProductQty(variantId, next) {
      setQty(prev => {
        const v = Math.max(0, Math.min(99, Number(next) || 0));
        const out = { ...prev };
        if (v === 0) delete out[variantId];
        else out[variantId] = v;
        return out;
      });
    }

    function checkout() {
      const entries = Object.entries(qty).filter(([, q]) => q > 0);
      if (!entries.length) return;
      const path = entries.map(([id, q]) => `${id}:${q}`).join(",");
      const url = `${SHOP_BASE}/cart/${path}`;
      setBusy(true);
      window.open(url, "_blank", "noopener");
      setBusy(false);
    }

    // ─── render states ──────────────────────────────────────────
    if (error) {
      return (
        <div style={S.errorBox}>
          Couldn't load the shop right now — {error}.{" "}
          <a href={SHOP_BASE} target="_blank" rel="noopener"
             style={{ color: "var(--gold)" }}>Open casamspice.com →</a>
        </div>
      );
    }
    if (!products) {
      return <div style={S.loading}>Loading the spice rack…</div>;
    }
    if (products.length === 0) {
      return <div style={S.loading}>No products available right now.</div>;
    }

    return (
      <div style={S.wrap}>
        <div style={S.heading}>
          <div>
            <div style={S.titleEs}>La Tienda</div>
            <div style={S.titleEn}>Casa M Spice Co. · {products.length} products</div>
          </div>
          <button type="button" onClick={() => {
            const node = document.getElementById("tienda-mount");
            const arrow = document.getElementById("tienda-arrow");
            if (node) node.hidden = true;
            if (arrow) arrow.textContent = "↓";
          }} style={S.closeBtn} aria-label="Close shop">×</button>
        </div>

        <div style={S.grid}>
          {products.map((p) => {
            const v   = p.variants[0];
            const img = p.images?.[0]?.src || null;
            const q   = Number(qty[v.id] || 0);
            const active = q > 0;
            return (
              <div key={p.id} style={{
                ...S.card,
                borderColor: active ? "var(--tienda)" : "var(--line-soft)",
                background: active ? "rgba(192,74,42,0.07)" : "rgba(0,0,0,0.18)",
              }}>
                {img ? (
                  <div style={S.imgBox}>
                    <img src={img} alt="" loading="lazy" style={S.img} />
                  </div>
                ) : (
                  <div style={{ ...S.imgBox, background: "rgba(255,255,255,0.04)" }} />
                )}
                <div style={S.cardBody}>
                  <div style={S.name}>{p.title.replace(/®/g, "®")}</div>
                  <div style={S.price}>{money(v.price)}</div>
                </div>
                <div style={S.qtyRow}>
                  <button type="button"
                    onClick={() => setProductQty(v.id, q - 1)}
                    disabled={q === 0}
                    style={{ ...S.qtyBtn, opacity: q === 0 ? 0.3 : 1 }}
                    aria-label={`Decrease ${p.title}`}>−</button>
                  <span style={S.qtyVal}>{q}</span>
                  <button type="button"
                    onClick={() => setProductQty(v.id, q + 1)}
                    style={S.qtyBtn}
                    aria-label={`Increase ${p.title}`}>+</button>
                </div>
              </div>
            );
          })}
        </div>

        <div style={S.footer}>
          <div style={S.totals}>
            <span style={S.totalsLabel}>
              {itemsInCart === 0 ? "Nothing selected"
                : itemsInCart === 1 ? "1 item"
                : `${itemsInCart} items`}
            </span>
            <span style={S.totalsValue}>{money(subtotal)}</span>
          </div>
          <button type="button"
            onClick={checkout}
            disabled={itemsInCart === 0 || busy}
            style={{
              ...S.checkout,
              opacity: itemsInCart === 0 ? 0.4 : 1,
              cursor:  itemsInCart === 0 ? "not-allowed" : "pointer",
            }}>
            Checkout on casamspice.com →
          </button>
        </div>
        <div style={S.footnote}>
          Shipping &amp; tax calculated at checkout. Your cart opens at
          casamspice.com with the selected items already in it.
        </div>
      </div>
    );
  }

  // ─── styles (inline so we don't have to touch the global CSS) ────
  const S = {
    wrap: {
      marginTop: 18, padding: 22,
      border: "1px solid var(--line-soft)",
      borderTop: "4px solid var(--tienda)",
      borderRadius: 6, background: "rgba(0,0,0,0.22)",
    },
    heading: {
      display: "flex", justifyContent: "space-between", alignItems: "flex-start",
      gap: 12, marginBottom: 18,
    },
    titleEs: {
      fontFamily: "var(--serif)", fontStyle: "italic",
      fontSize: 24, color: "var(--tienda)",
    },
    titleEn: {
      fontFamily: "var(--sans)", fontSize: 11, letterSpacing: 2,
      textTransform: "uppercase", color: "var(--ink-mid)", marginTop: 4,
    },
    closeBtn: {
      all: "unset", cursor: "pointer", fontFamily: "var(--serif)",
      fontSize: 24, lineHeight: "24px", color: "var(--ink-mid)",
      padding: "0 6px",
    },
    grid: {
      display: "grid", gap: 12,
      gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))",
    },
    card: {
      display: "flex", flexDirection: "column", gap: 8,
      border: "1px solid var(--line-soft)", borderRadius: 6,
      padding: 10, transition: "background 120ms ease, border-color 120ms ease",
    },
    imgBox: {
      width: "100%", aspectRatio: "1 / 1", borderRadius: 4,
      overflow: "hidden", display: "flex", alignItems: "center",
      justifyContent: "center",
    },
    img: { width: "100%", height: "100%", objectFit: "cover" },
    cardBody: { display: "flex", flexDirection: "column", gap: 2, minHeight: 44 },
    name: {
      fontFamily: "var(--serif)", fontStyle: "italic",
      fontSize: 14, color: "var(--ink)", lineHeight: 1.25,
    },
    price: {
      fontFamily: "var(--sans)", fontSize: 12, letterSpacing: 1,
      color: "var(--gold)", fontWeight: 700,
    },
    qtyRow: {
      display: "flex", alignItems: "center", justifyContent: "space-between",
      gap: 8, marginTop: 4, padding: "6px 4px",
      borderTop: "1px solid var(--line-soft)",
    },
    qtyBtn: {
      all: "unset", cursor: "pointer", width: 28, height: 28,
      borderRadius: 4, background: "rgba(212,176,122,0.14)",
      color: "var(--gold)", fontFamily: "var(--sans)", fontSize: 16,
      fontWeight: 700, textAlign: "center",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
    },
    qtyVal: {
      fontFamily: "var(--mono, var(--sans))", fontSize: 13, color: "var(--ink)",
      minWidth: 20, textAlign: "center",
    },
    footer: {
      display: "flex", alignItems: "center", justifyContent: "space-between",
      gap: 12, marginTop: 18, paddingTop: 14,
      borderTop: "1px solid var(--line-soft)",
    },
    totals: { display: "flex", flexDirection: "column", gap: 2 },
    totalsLabel: {
      fontFamily: "var(--sans)", fontSize: 10, letterSpacing: 2,
      textTransform: "uppercase", color: "var(--ink-mid)",
    },
    totalsValue: {
      fontFamily: "var(--serif)", fontStyle: "italic",
      fontSize: 22, color: "var(--ink)",
    },
    checkout: {
      all: "unset", padding: "12px 18px", borderRadius: 4,
      background: "var(--tienda)", color: "#fff",
      fontFamily: "var(--sans)", fontSize: 11, letterSpacing: 1.8,
      fontWeight: 700, textTransform: "uppercase",
      transition: "filter 120ms ease",
    },
    footnote: {
      marginTop: 10, fontFamily: "var(--sans)", fontSize: 10,
      color: "var(--ink-faint)", textAlign: "right",
    },
    errorBox: {
      padding: 22, border: "1px solid var(--line-soft)",
      borderRadius: 6, background: "rgba(192,74,42,0.08)",
      color: "var(--ink-mid)", fontFamily: "var(--sans)", fontSize: 13,
      marginTop: 18,
    },
    loading: {
      padding: 32, textAlign: "center", color: "var(--ink-mid)",
      fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 14,
      marginTop: 18,
    },
  };

  // ─── mount/unmount wiring ────────────────────────────────────────
  // The Tienda card in index.html (#tienda-toggle) flips #tienda-mount
  // visibility and asks us to render. We mount once on first open and
  // toggle the wrapper's hidden flag on subsequent toggles so the
  // user's cart state survives a close/reopen.
  let root = null;
  function openTienda() {
    const mount = document.getElementById("tienda-mount");
    if (!mount) return;
    mount.hidden = false;
    if (!root) {
      root = ReactDOM.createRoot(mount);
      root.render(<Tienda />);
    }
    const arrow = document.getElementById("tienda-arrow");
    if (arrow) arrow.textContent = "↑";
    // Smooth-scroll the shop into view.
    requestAnimationFrame(() => {
      mount.scrollIntoView({ behavior: "smooth", block: "start" });
    });
  }
  function closeTienda() {
    const mount = document.getElementById("tienda-mount");
    if (mount) mount.hidden = true;
    const arrow = document.getElementById("tienda-arrow");
    if (arrow) arrow.textContent = "↓";
  }

  document.addEventListener("DOMContentLoaded", () => {
    const btn = document.getElementById("tienda-toggle");
    if (!btn) return;
    btn.addEventListener("click", (e) => {
      e.preventDefault(); // we're an <a> for .room styling — stop the # nav
      const mount = document.getElementById("tienda-mount");
      const opening = mount && mount.hidden;
      if (opening) openTienda();
      else closeTienda();
      btn.setAttribute("aria-expanded", opening ? "true" : "false");
    });
  });
})();
