const { Button, Divider } = window.TheMahjClubsDesignSystem_b7bc49;

const tmcEyebrow = { fontFamily: "var(--font-body)", fontSize: 10, fontWeight: 500, letterSpacing: "var(--tracking-caps)", textTransform: "uppercase" };
const tmcDisplay = { fontFamily: "var(--font-display)", fontWeight: 300, letterSpacing: "var(--tracking-display)" };

/* ---- Site-wide shopping cart (Shopify Storefront Cart API). Cart lives on
   the site; the final Checkout click hands off to her branded Shopify
   checkout (shop.phoenixmahjongclub.com) in the SAME tab. ---- */
const TMC_SHOP = { domain: "0vxpjt-eh.myshopify.com", token: "e6911869fe328fbdea5ab478f13e1e7c" };
const CART_FRAGMENT = "id checkoutUrl totalQuantity cost { subtotalAmount { amount } } lines(first: 50) { nodes { id quantity merchandise { ... on ProductVariant { id title price { amount } product { title featuredImage { url } } } } } }";
function shopGql(query, variables) {
  return fetch("https://" + TMC_SHOP.domain + "/api/2024-07/graphql.json", {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-Shopify-Storefront-Access-Token": TMC_SHOP.token },
    body: JSON.stringify({ query: query, variables: variables }),
  }).then(r => r.json());
}
const TmcCartStore = {
  state: { cart: null, open: false, busy: false },
  listeners: [],
  set(patch) { this.state = Object.assign({}, this.state, patch); this.listeners.forEach(l => l(this.state)); },
  subscribe(l) { this.listeners.push(l); const self = this; return () => { self.listeners = self.listeners.filter(x => x !== l); }; },
};
function useTmcCart() {
  const [s, setS] = React.useState(TmcCartStore.state);
  React.useEffect(() => TmcCartStore.subscribe(setS), []);
  return s;
}
async function tmcEnsureCart() {
  const st = TmcCartStore.state;
  if (st.cart && st.cart.id) return st.cart;
  const saved = localStorage.getItem("tmc-cart-id");
  if (saved) {
    const j = await shopGql("query($id: ID!) { cart(id: $id) { " + CART_FRAGMENT + " } }", { id: saved });
    if (j.data && j.data.cart) { TmcCartStore.set({ cart: j.data.cart }); return j.data.cart; }
  }
  const j = await shopGql("mutation { cartCreate(input: {}) { cart { " + CART_FRAGMENT + " } } }");
  const cart = j.data.cartCreate.cart;
  localStorage.setItem("tmc-cart-id", cart.id);
  TmcCartStore.set({ cart: cart });
  return cart;
}
const TmcCart = {
  toggle(open) { TmcCartStore.set({ open: open === undefined ? !TmcCartStore.state.open : open }); },
  async add(variantId, qty) {
    try {
      TmcCartStore.set({ busy: true });
      const cart = await tmcEnsureCart();
      const j = await shopGql("mutation($cartId: ID!, $lines: [CartLineInput!]!) { cartLinesAdd(cartId: $cartId, lines: $lines) { cart { " + CART_FRAGMENT + " } } }", { cartId: cart.id, lines: [{ merchandiseId: variantId, quantity: qty || 1 }] });
      TmcCartStore.set({ cart: j.data.cartLinesAdd.cart, open: true, busy: false });
      return true;
    } catch (e) {
      TmcCartStore.set({ busy: false });
      window.location.href = "https://" + TMC_SHOP.domain + "/cart/" + String(variantId).split("/").pop() + ":" + (qty || 1);
      return false;
    }
  },
  async setQty(lineId, qty) {
    const cart = TmcCartStore.state.cart; if (!cart) return;
    let next;
    if (qty <= 0) {
      const j = await shopGql("mutation($cartId: ID!, $ids: [ID!]!) { cartLinesRemove(cartId: $cartId, lineIds: $ids) { cart { " + CART_FRAGMENT + " } } }", { cartId: cart.id, ids: [lineId] });
      next = j.data.cartLinesRemove.cart;
    } else {
      const j = await shopGql("mutation($cartId: ID!, $lines: [CartLineUpdateInput!]!) { cartLinesUpdate(cartId: $cartId, lines: $lines) { cart { " + CART_FRAGMENT + " } } }", { cartId: cart.id, lines: [{ id: lineId, quantity: qty }] });
      next = j.data.cartLinesUpdate.cart;
    }
    TmcCartStore.set({ cart: next });
  },
};

function CartDrawer() {
  const s = useTmcCart();
  React.useEffect(() => { tmcEnsureCart().catch(() => {}); }, []);
  if (!s.open) return null;
  const cart = s.cart;
  const lines = (cart && cart.lines.nodes) || [];
  const subtotal = cart ? Number(cart.cost.subtotalAmount.amount) : 0;
  const money = n => "$" + Number(n).toFixed(Number(n) % 1 ? 2 : 0);
  const qb = { width: 24, height: 24, border: "1px solid var(--tmc-olive)", background: "#fff", borderRadius: 4, cursor: "pointer", lineHeight: 1, fontFamily: "var(--font-body)" };
  return ReactDOM.createPortal(
    <div onClick={() => TmcCart.toggle(false)} style={{ position: "fixed", inset: 0, zIndex: 120, background: "rgba(30,10,14,.45)", animation: "tmc-fade-in 140ms var(--ease-out) both" }}>
      <div onClick={e => e.stopPropagation()} style={{ position: "absolute", top: 0, right: 0, height: "100%", width: "min(420px, 94vw)", background: "var(--tmc-tile-white)", boxShadow: "-14px 0 40px rgba(30,10,14,.25)", display: "flex", flexDirection: "column", animation: "tmc-drawer-in 240ms var(--ease-out) both" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 24px", borderBottom: "var(--rule)" }}>
          <div style={{ ...tmcDisplay, fontSize: 26, color: "var(--tmc-burgundy)" }}>Your cart</div>
          <button onClick={() => TmcCart.toggle(false)} aria-label="Close cart" style={{ background: "none", border: "none", fontSize: 24, cursor: "pointer", color: "var(--tmc-burgundy)" }}>×</button>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "8px 24px" }}>
          {!lines.length && (
            <div style={{ textAlign: "center", padding: "70px 10px" }}>
              <div style={{ fontFamily: "var(--font-script)", fontSize: 30, color: "var(--tmc-olive)" }}>your cart is empty</div>
              <p style={{ fontSize: 13, color: "var(--tmc-olive)", marginTop: 10 }}>Tiles, mats & gifts await in the boutique.</p>
            </div>
          )}
          {lines.map(l => (
            <div key={l.id} style={{ display: "grid", gridTemplateColumns: "64px minmax(0,1fr) auto", gap: 14, alignItems: "center", padding: "14px 0", borderBottom: "var(--rule)" }}>
              {l.merchandise.product.featuredImage
                ? <img src={l.merchandise.product.featuredImage.url} alt={l.merchandise.product.title} style={{ width: 64, height: 64, objectFit: "cover", borderRadius: 4 }} />
                : <div style={{ width: 64, height: 64, background: "var(--tmc-cream)", borderRadius: 4 }}></div>}
              <div>
                <div style={{ ...tmcDisplay, fontSize: 16, color: "var(--tmc-burgundy)", lineHeight: 1.2 }}>{l.merchandise.product.title}</div>
                {l.merchandise.title !== "Default Title" && <div style={{ fontSize: 14, color: "var(--tmc-olive)", marginTop: 2 }}>{l.merchandise.title}</div>}
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8 }}>
                  <button onClick={() => TmcCart.setQty(l.id, l.quantity - 1)} style={qb}>−</button>
                  <span style={{ fontSize: 13, minWidth: 16, textAlign: "center", fontFamily: "var(--font-body)" }}>{l.quantity}</span>
                  <button onClick={() => TmcCart.setQty(l.id, l.quantity + 1)} style={qb}>+</button>
                  <button onClick={() => TmcCart.setQty(l.id, 0)} style={{ background: "none", border: "none", fontSize: 11, color: "var(--tmc-raspberry)", cursor: "pointer", marginLeft: 4, fontFamily: "var(--font-body)" }}>remove</button>
                </div>
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-body)", fontFamily: "var(--font-body)" }}>{money(Number(l.merchandise.price.amount) * l.quantity)}</div>
            </div>
          ))}
        </div>
        {lines.length > 0 && (
          <div style={{ padding: "18px 24px 22px", borderTop: "var(--rule)", background: "var(--tmc-cream)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 14, alignItems: "baseline" }}>
              <span style={{ ...tmcEyebrow, fontSize: 10 }}>Subtotal</span>
              <span style={{ ...tmcDisplay, fontSize: 20, color: "var(--tmc-burgundy)" }}>{money(subtotal)}</span>
            </div>
            <Button fullWidth size="lg" onClick={() => { if (cart) window.location.href = cart.checkoutUrl; }}>Checkout</Button>
            <div style={{ fontSize: 13, color: "var(--tmc-olive)", textAlign: "center", marginTop: 8, fontFamily: "var(--font-body)" }}>Taxes & shipping calculated at secure checkout.</div>
          </div>
        )}
      </div>
    </div>, document.body);
}

function CartButton() {
  const s = useTmcCart();
  const count = s.cart ? s.cart.totalQuantity : 0;
  return (
    <button onClick={() => TmcCart.toggle()} aria-label="Cart" style={{ position: "relative", background: "none", border: "none", cursor: "pointer", padding: 6, lineHeight: 0 }}>
      <svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="var(--tmc-cream)" strokeWidth="1.5"><path d="M6 8h12l-1.2 12.2a1.5 1.5 0 0 1-1.5 1.3H8.7a1.5 1.5 0 0 1-1.5-1.3L6 8z"/><path d="M9 10V6a3 3 0 0 1 6 0v4"/></svg>
      {count > 0 && <span style={{ position: "absolute", top: -2, right: -4, background: "var(--tmc-raspberry)", color: "var(--tmc-cream)", fontSize: 10, fontFamily: "var(--font-body)", fontWeight: 600, borderRadius: 999, minWidth: 16, height: 16, display: "flex", alignItems: "center", justifyContent: "center", padding: "0 3px" }}>{count}</span>}
    </button>
  );
}


const NAV = [["calendar","Calendar"],["lessons","Lessons"],["membership","Membership"],["league","League"],["private","Private Events"],["shop","Shop"],["contact","Contact"]];
const NAV_BAR = NAV; // Membership rides in the regular nav now
const MEMBER_HUB_URL = "https://www.heylo.com/login?redirect=https%3A%2F%2Fwww.heylo.com%2FmyEvents";

function RollText({ label }) {
  return (
    <span className="tmc-roll"><span>{label}</span><span aria-hidden="true">{label}</span></span>
  );
}

function TmcNav({ go, page }) {
  const [open, setOpen] = React.useState(false);
  const [logo, setLogo] = React.useState("");
  React.useEffect(() => { fetch("assets/logos/horizontal.svg").then(r => r.text()).then(setLogo); }, []);
  const nav = id => { setOpen(false); go(id); };
  return (
    <nav style={{ background: "var(--tmc-emerald)" }}>
      <div role="note" aria-label="Formerly Phoenix Mahjong Club — phoenixmahjongclub.com"
        style={{ background: "var(--tmc-blush)", color: "var(--tmc-burgundy)", overflow: "hidden", padding: "11px 0", fontFamily: "var(--font-body)", fontSize: 13.5, fontWeight: 500, letterSpacing: ".22em", textTransform: "uppercase", whiteSpace: "nowrap" }}>
        <div className="tmc-marquee-track" aria-hidden="true" style={{ gap: 0, animationDuration: "75s" }}>
          {[0, 1].map(half => (
            <span key={half} style={{ display: "inline-flex" }}>
              {Array.from({ length: 6 }).map((_, i) => (
                <span key={i} style={{ padding: "0 30px" }}>Formerly Phoenix Mahjong Club&nbsp;&nbsp;🀄&nbsp;&nbsp;phoenixmahjongclub.com</span>
              ))}
            </span>
          ))}
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "22px 44px" }}>
        <a href="/" onClick={e => { e.preventDefault(); nav("home"); }} aria-label="The Mahj Clubs — home" style={{ lineHeight: 0, display: "inline-flex", height: 34 }}
          dangerouslySetInnerHTML={{ __html: logo.replace(/<\?xml[^>]*\?>/, "").replace("color:#184538", "color:#EEE7E0;height:34px") }}></a>
        <div style={{ flex: 1 }}></div>
        <div className="tmc-nav-links" style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: "12px 24px" }}>
          {NAV_BAR.map(([id, label]) => (
            <a key={id} href={"/" + id} onClick={e => { e.preventDefault(); nav(id); }}
              style={{ ...tmcEyebrow, fontSize: 12, letterSpacing: ".14em", whiteSpace: "nowrap", color: page === id ? "var(--tmc-blush)" : "var(--tmc-cream)", textDecoration: "none", borderBottom: page === id ? "1px solid var(--tmc-blush)" : "1px solid transparent", paddingBottom: 4 }}><RollText label={label} /></a>
          ))}
          <Button onClick={() => window.open(MEMBER_HUB_URL, "_blank")}>Member log in</Button>
        </div>
        <CartButton />
        <button className="tmc-nav-toggle" aria-label="Menu" aria-expanded={open} onClick={() => setOpen(o => !o)}>
          <span></span><span></span><span></span>
        </button>
      </div>
      {open && (
        <div className="tmc-nav-drawer">
          {NAV_BAR.map(([id, label]) => (
            <a key={id} href={"/" + id} onClick={e => { e.preventDefault(); nav(id); }}
              style={{ ...tmcEyebrow, fontSize: 15, color: page === id ? "var(--tmc-blush)" : "var(--tmc-cream)", textDecoration: "none", padding: "16px 0", borderBottom: "1px solid rgba(238,231,224,.25)" }}>{label}</a>
          ))}
          <div style={{ paddingTop: 14 }}><Button size="sm" fullWidth onClick={() => window.open(MEMBER_HUB_URL, "_blank")}>Member log in</Button></div>
        </div>
      )}
      <CartDrawer />
    </nav>
  );
}

function PageHead({ eyebrow, title, script, lede }) {
  return (
    <header style={{ textAlign: "center", padding: "64px 24px 0", maxWidth: 720, margin: "0 auto" }} className="tmc-stagger">
      {eyebrow && <div style={{ ...tmcEyebrow, color: "var(--tmc-raspberry)" }}>{eyebrow}</div>}
      <h1 style={{ ...tmcDisplay, fontSize: 56, lineHeight: .95, color: "var(--text-display)", margin: "16px 0 0" }}>{title}</h1>
      {script && <div style={{ fontFamily: "var(--font-script)", fontSize: 38, color: "var(--tmc-emerald)", marginTop: 8 }}>{script}</div>}
      {lede && <p style={{ fontFamily: "var(--font-body)", fontSize: 15, lineHeight: 1.55, margin: "18px auto 0", maxWidth: 560 }}>{lede}</p>}
    </header>
  );
}

function TmcFooter({ go }) {

  const fLink = { ...tmcEyebrow, fontSize: 11, color: "var(--tmc-cream)", opacity: .85, textDecoration: "none", padding: "7px 0", display: "block" };
  const colTitle = { ...tmcEyebrow, fontSize: 10, color: "var(--tmc-butter)", marginBottom: 14 };
  const bodyLine = { fontFamily: "var(--font-body)", fontSize: 13, lineHeight: 1.9, opacity: .85 };
  return (
    <footer style={{ backgroundColor: "var(--tmc-emerald)", backgroundImage: "linear-gradient(rgba(24,69,56,.65), rgba(24,69,56,.65)), url('assets/textures/paper-cream.png')", backgroundBlendMode: "normal, soft-light", backgroundSize: "auto, 560px auto", color: "var(--tmc-cream)", padding: "68px 64px 28px", marginTop: 0 }}>
      {/* Identity — centered, breathing */}
      <div style={{ textAlign: "center", maxWidth: 560, margin: "0 auto" }}>
        <img src="assets/logos/crest-2024-cream.png" alt="The Mahj Clubs — TMC — Scottsdale, ESTD 2024"
          style={{ height: 180, width: "auto", display: "block", margin: "0 auto" }} />
        <div style={{ fontFamily: "var(--font-script)", fontSize: 28, color: "var(--tmc-blush)", marginTop: 14 }}>the key to connection</div>
        <p style={{ fontSize: 14, lineHeight: 1.6, margin: "10px auto 0", opacity: .9, maxWidth: 380 }}>
          New friends, friendly competition, and a seat saved just for you at the table.
        </p>
        
      </div>
      {/* Four tidy columns */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,minmax(0,1fr))", gap: 40, alignItems: "start", maxWidth: 1080, margin: "56px auto 0", borderTop: "1px solid rgba(238,231,224,.22)", paddingTop: 44 }}>
        <div>
          <div style={colTitle}>Visit</div>
          <div style={bodyLine}>4821 N. Scottsdale Rd, Suite 106<br />Scottsdale, AZ 85251</div>
          <div style={{ ...bodyLine, marginTop: 10 }}>
            <a href="mailto:hello@themahjclubs.com" style={{ color: "var(--tmc-cream)", textDecoration: "none" }}>hello@themahjclubs.com</a><br />
            <a href="tel:+14809792571" style={{ color: "var(--tmc-cream)", textDecoration: "none" }}>(480) 979-2571</a>
          </div>
        </div>
        <div>
          <div style={colTitle}>Hours</div>
          <div style={bodyLine}>Tue 12–5<br />Wed 12–8<br />Thu & Fri 12–7:30<br />Sat & Sun 12–5<br />Mon · private events</div>
        </div>
        <div>
          <div style={colTitle}>Play</div>
          {[["calendar","Calendar"],["lessons","Lessons"],["league","League"],["membership","Membership"]].map(([id, label]) => (
            <a key={id} href={"/" + id} onClick={e => { e.preventDefault(); go(id); }} style={fLink}>{label}</a>
          ))}
        </div>
        <div>
          <div style={colTitle}>The club</div>
          {[["private","Private Events"],["shop","Shop"],["contact","Contact"]].map(([id, label]) => (
            <a key={id} href={"/" + id} onClick={e => { e.preventDefault(); go(id); }} style={fLink}>{label}</a>
          ))}
          <a href="https://www.heylo.com/login?redirect=https%3A%2F%2Fwww.heylo.com%2FmyEvents" target="_blank" rel="noreferrer" style={fLink}>Member Hub sign-in</a>
          <a href="https://www.instagram.com/mahjclubs/" target="_blank" rel="noreferrer" style={fLink}>Instagram</a>
        </div>
      </div>
      {/* Bottom bar */}
      <div style={{ borderTop: "1px solid rgba(238,231,224,.22)", marginTop: 48, paddingTop: 18, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
        <div style={{ ...tmcEyebrow, fontSize: 8, opacity: .6 }}>© the mahj clubs · scottsdale, arizona · established 2024</div>
        <a href="/privacy" onClick={e => { e.preventDefault(); go("privacy"); }} style={{ ...tmcEyebrow, fontSize: 8, color: "var(--tmc-cream)", opacity: .55, textDecoration: "none", marginRight: 18 }}>Privacy policy</a><a href="/returns" onClick={e => { e.preventDefault(); go("returns"); }} style={{ ...tmcEyebrow, fontSize: 8, color: "var(--tmc-cream)", opacity: .55, textDecoration: "none", marginRight: 18 }}>Return policy</a><a href="https://www.jadeleconsulting.com" target="_blank" rel="noreferrer" style={{ ...tmcEyebrow, fontSize: 8, color: "var(--tmc-cream)", opacity: .55, textDecoration: "none" }}>design by jadele®</a>
        <a href="#" onClick={e => { e.preventDefault(); window.scrollTo({ top: 0, behavior: "smooth" }); }} style={{ ...tmcEyebrow, fontSize: 8, color: "var(--tmc-cream)", opacity: .75, textDecoration: "none" }}>back to top ↑</a>
      </div>
    </footer>
  );
}

Object.assign(window, { TmcNav, TmcFooter, PageHead, tmcEyebrow, tmcDisplay, TmcCart });
