-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshopify.js
More file actions
759 lines (675 loc) · 32.6 KB
/
shopify.js
File metadata and controls
759 lines (675 loc) · 32.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
/* ============================================================
THREAD & BONE — Shopify Storefront API Integration
Updated to use the Cart API (Checkout API deprecated April 2025)
SETUP:
1. In Shopify Admin → Settings → Apps → Develop apps → Create app
2. Configure Storefront API scopes:
unauthenticated_read_products,
unauthenticated_read_product_listings,
unauthenticated_read_cart,
unauthenticated_write_cart
3. Install the app and copy your Storefront access token
4. Update CONFIG below with your store domain and token
============================================================ */
const ShopifyStore = (function () {
'use strict';
// =====================================================
// CONFIGURATION — Replace these with your own values
// =====================================================
const CONFIG = {
storeDomain: 'thread-and-bone-2.myshopify.com', // Your Shopify store domain
storefrontAccessToken: 'c687d0fd40ae96422df926404fb99181',
apiVersion: '2026-01',
};
const ENDPOINT = `https://${CONFIG.storeDomain}/api/${CONFIG.apiVersion}/graphql.json`;
// =====================================================
// GraphQL Queries & Mutations (Cart API)
// =====================================================
// Shared cart fragment to avoid repetition
const CART_FRAGMENT = `
fragment CartFields on Cart {
id
checkoutUrl
totalQuantity
cost {
subtotalAmount {
amount
currencyCode
}
}
lines(first: 50) {
edges {
node {
id
quantity
merchandise {
... on ProductVariant {
id
title
price {
amount
currencyCode
}
image {
url
altText
}
product {
title
}
}
}
}
}
}
}
`;
const QUERIES = {
// Fetch all products
allProducts: `
query AllProducts($first: Int!) {
products(first: $first) {
edges {
node {
id
title
handle
description
productType
vendor
tags
priceRange {
minVariantPrice {
amount
currencyCode
}
}
images(first: 5) {
edges {
node {
url
altText
width
height
}
}
}
variants(first: 20) {
edges {
node {
id
title
availableForSale
price {
amount
currencyCode
}
selectedOptions {
name
value
}
image {
url
altText
}
}
}
}
availableForSale
createdAt
}
}
}
}
`,
// Create a new cart
cartCreate: `
${CART_FRAGMENT}
mutation CartCreate($input: CartInput) {
cartCreate(input: $input) {
cart {
...CartFields
}
userErrors {
field
message
}
}
}
`,
// Fetch an existing cart by ID (for persistence)
cartFetch: `
${CART_FRAGMENT}
query CartFetch($cartId: ID!) {
cart(id: $cartId) {
...CartFields
}
}
`,
// Add lines to existing cart
cartLinesAdd: `
${CART_FRAGMENT}
mutation CartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
cartLinesAdd(cartId: $cartId, lines: $lines) {
cart {
...CartFields
}
userErrors {
field
message
}
}
}
`,
// Remove lines from cart
cartLinesRemove: `
${CART_FRAGMENT}
mutation CartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {
cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
cart {
...CartFields
}
userErrors {
field
message
}
}
}
`,
// Update line quantities
cartLinesUpdate: `
${CART_FRAGMENT}
mutation CartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
cartLinesUpdate(cartId: $cartId, lines: $lines) {
cart {
...CartFields
}
userErrors {
field
message
}
}
}
`,
};
// =====================================================
// API Helper
// =====================================================
async function shopifyFetch(query, variables = {}) {
try {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': CONFIG.storefrontAccessToken,
},
body: JSON.stringify({ query, variables }),
});
if (!response.ok) {
throw new Error(`Shopify API error: ${response.status} ${response.statusText}`);
}
const json = await response.json();
if (json.errors) {
console.error('Shopify GraphQL errors:', json.errors);
throw new Error(json.errors[0].message);
}
return json.data;
} catch (error) {
console.error('Shopify fetch failed:', error);
throw error;
}
}
// =====================================================
// State
// =====================================================
let allProducts = [];
let currentFilter = 'all';
let cartId = null;
let checkoutUrl = null;
let cartLines = [];
let selectedVariantId = null;
// =====================================================
// Cart Persistence (localStorage)
// =====================================================
const CART_STORAGE_KEY = 'saltandtide_cart_id';
function saveCartId(id) {
try { localStorage.setItem(CART_STORAGE_KEY, id); } catch (e) { /* private browsing */ }
}
function loadCartId() {
try { return localStorage.getItem(CART_STORAGE_KEY); } catch (e) { return null; }
}
function clearCartId() {
try { localStorage.removeItem(CART_STORAGE_KEY); } catch (e) { /* private browsing */ }
}
async function restoreCart() {
const savedId = loadCartId();
if (!savedId || CONFIG.storefrontAccessToken === 'your-storefront-access-token') return;
try {
const data = await shopifyFetch(QUERIES.cartFetch, { cartId: savedId });
if (data.cart && data.cart.lines.edges.length > 0) {
updateCartUI(data.cart);
console.log('Cart restored from previous session');
} else {
// Cart exists but is empty, or has expired — clear it
clearCartId();
}
} catch (err) {
// Cart likely expired on Shopify's end — clear the stale ID
console.warn('Could not restore cart — it may have expired:', err.message);
clearCartId();
}
}
// =====================================================
// DOM References
// =====================================================
const productGrid = document.getElementById('productGrid');
const shopLoading = document.getElementById('shopLoading');
const shopEmpty = document.getElementById('shopEmpty');
const cartDrawer = document.getElementById('cartDrawer');
const cartOverlay = document.getElementById('cartOverlay');
const cartCloseBtn = document.getElementById('cartClose');
const cartItemsEl = document.getElementById('cartItems');
const cartFooter = document.getElementById('cartFooter');
const cartSubtotal = document.getElementById('cartSubtotal');
const cartCountEls = document.querySelectorAll('.cart-count');
const cartToggleBtn = document.getElementById('cartToggle');
const checkoutBtn = document.getElementById('checkoutBtn');
const quickViewModal = document.getElementById('quickViewModal');
const quickViewOverlay = document.getElementById('quickViewOverlay');
const quickViewCloseBtn = document.getElementById('quickViewClose');
const addToCartBtn = document.getElementById('addToCartBtn');
const filterBtns = document.querySelectorAll('.filter-btn');
const sortSelect = document.getElementById('sortSelect');
// =====================================================
// Helpers
// =====================================================
function formatPrice(amount, currency = 'USD') {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency,
}).format(parseFloat(amount));
}
function getProductCategory(product) {
const type = (product.productType || '').toLowerCase();
const tags = (product.tags || []).map((t) => t.toLowerCase());
if (type.includes('surfboard') || tags.includes('surfboards') || tags.includes('shortboard') || tags.includes('longboard') || tags.includes('funboard')) return 'surfboards';
if (type.includes('wetsuit') || tags.includes('wetsuits') || tags.includes('rashguard')) return 'wetsuits';
if (type.includes('boardshort') || tags.includes('boardshorts') || tags.includes('shorts')) return 'boardshorts';
if (type.includes('accessor') || tags.includes('accessories') || tags.includes('bag') || tags.includes('wax') || tags.includes('leash')) return 'accessories';
return 'all';
}
// =====================================================
// Product Rendering
// =====================================================
function renderProductCard(product) {
const price = product.priceRange.minVariantPrice;
const image = product.images.edges[0]?.node;
const available = product.availableForSale;
const card = document.createElement('div');
card.className = 'product-card anim-reveal visible';
card.dataset.category = getProductCategory(product);
card.dataset.price = parseFloat(price.amount);
card.dataset.date = product.createdAt || '';
card.innerHTML = `
<div class="product-img-wrap" role="button" tabindex="0" aria-label="Quick view ${product.title}">
<div class="product-img" style="${image ? '' : 'background: linear-gradient(160deg, #2c2c2c, #1a1a1a);'}">
${!available ? '<div class="product-badge">Sold Out</div>' : ''}
${
image
? `<img src="${image.url}" alt="${image.altText || product.title}" loading="lazy" style="width:100%;height:100%;object-fit:cover;">`
: `<div class="product-placeholder-icon">
<svg viewBox="0 0 60 70" fill="none"><path d="M30 5 L18 25 L10 25 L8 65 L52 65 L50 25 L42 25 Z" stroke="rgba(255,255,255,0.25)" stroke-width="0.8" fill="none"/></svg>
</div>`
}
</div>
</div>
<div class="product-info">
<h3>${product.title}</h3>
<p class="product-price">${formatPrice(price.amount, price.currencyCode)}</p>
</div>
`;
card.querySelector('.product-img-wrap').addEventListener('click', () => openQuickView(product));
return card;
}
function renderProducts(products) {
if (!productGrid) return;
productGrid.innerHTML = '';
if (!products.length) {
if (shopEmpty) shopEmpty.style.display = 'block';
return;
}
if (shopEmpty) shopEmpty.style.display = 'none';
products.forEach((p) => {
productGrid.appendChild(renderProductCard(p));
});
}
function filterAndSort() {
let filtered = allProducts;
if (currentFilter !== 'all') {
filtered = allProducts.filter((p) => getProductCategory(p) === currentFilter);
}
const sortVal = sortSelect ? sortSelect.value : 'featured';
switch (sortVal) {
case 'price-asc':
filtered.sort((a, b) => parseFloat(a.priceRange.minVariantPrice.amount) - parseFloat(b.priceRange.minVariantPrice.amount));
break;
case 'price-desc':
filtered.sort((a, b) => parseFloat(b.priceRange.minVariantPrice.amount) - parseFloat(a.priceRange.minVariantPrice.amount));
break;
case 'newest':
filtered.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
break;
}
renderProducts(filtered);
}
// =====================================================
// Quick View
// =====================================================
function openQuickView(product) {
if (!quickViewModal) return;
const images = product.images.edges.map((e) => e.node);
const variants = product.variants.edges.map((e) => e.node);
const price = product.priceRange.minVariantPrice;
document.getElementById('quickViewVendor').textContent = product.vendor || 'Thread & Bone';
document.getElementById('quickViewTitle').textContent = product.title;
document.getElementById('quickViewPrice').textContent = formatPrice(price.amount, price.currencyCode);
document.getElementById('quickViewDesc').textContent = product.description || 'Premium surf gear crafted from carefully selected materials. Designed for performance and durability.';
// Main image
const imgEl = document.getElementById('quickViewImg');
imgEl.innerHTML = images.length
? `<img src="${images[0].url}" alt="${images[0].altText || product.title}" style="width:100%;height:100%;object-fit:cover;">`
: `<div style="width:100%;height:100%;background:linear-gradient(160deg,#2c2c2c,#1a1a1a);display:flex;align-items:center;justify-content:center;">
<svg viewBox="0 0 60 70" fill="none" width="80"><path d="M30 5 L18 25 L10 25 L8 65 L52 65 L50 25 L42 25 Z" stroke="rgba(255,255,255,0.25)" stroke-width="0.8" fill="none"/></svg>
</div>`;
// Thumbnails
const thumbsEl = document.getElementById('quickViewThumbs');
thumbsEl.innerHTML = '';
images.forEach((img, i) => {
const thumb = document.createElement('img');
thumb.src = img.url;
thumb.alt = img.altText || '';
if (i === 0) thumb.classList.add('active');
thumb.addEventListener('click', () => {
imgEl.innerHTML = `<img src="${img.url}" alt="${img.altText || ''}" style="width:100%;height:100%;object-fit:cover;">`;
thumbsEl.querySelectorAll('img').forEach((t) => t.classList.remove('active'));
thumb.classList.add('active');
});
thumbsEl.appendChild(thumb);
});
// Size options
const sizesContainer = document.getElementById('sizeButtons');
const sizeGroup = document.getElementById('quickViewSizes');
sizesContainer.innerHTML = '';
selectedVariantId = null;
const sizeOptions = variants.filter((v) => v.selectedOptions.some((o) => o.name.toLowerCase() === 'size'));
if (sizeOptions.length > 0) {
sizeGroup.style.display = 'block';
sizeOptions.forEach((variant, i) => {
const sizeValue = variant.selectedOptions.find((o) => o.name.toLowerCase() === 'size')?.value || variant.title;
const btn = document.createElement('button');
btn.className = 'size-btn' + (i === 0 && variant.availableForSale ? ' selected' : '');
btn.textContent = sizeValue;
btn.disabled = !variant.availableForSale;
if (!variant.availableForSale) btn.style.opacity = '0.3';
if (i === 0 && variant.availableForSale) {
selectedVariantId = variant.id;
}
btn.addEventListener('click', () => {
sizesContainer.querySelectorAll('.size-btn').forEach((b) => b.classList.remove('selected'));
btn.classList.add('selected');
selectedVariantId = variant.id;
});
sizesContainer.appendChild(btn);
});
} else if (variants.length) {
sizeGroup.style.display = 'none';
selectedVariantId = variants[0].id;
}
if (addToCartBtn) {
addToCartBtn.disabled = !product.availableForSale;
addToCartBtn.textContent = product.availableForSale ? 'Add to Cart' : 'Sold Out';
}
quickViewModal.classList.add('open');
document.body.style.overflow = 'hidden';
}
function closeQuickView() {
if (quickViewModal) quickViewModal.classList.remove('open');
document.body.style.overflow = '';
}
// =====================================================
// Cart (using new Cart API)
// =====================================================
function openCart() {
if (cartDrawer) cartDrawer.classList.add('open');
document.body.style.overflow = 'hidden';
}
function closeCart() {
if (cartDrawer) cartDrawer.classList.remove('open');
document.body.style.overflow = '';
}
function updateCartUI(cart) {
if (!cart || !cartItemsEl) return;
cartId = cart.id;
checkoutUrl = cart.checkoutUrl;
saveCartId(cartId);
const lines = cart.lines.edges.map((e) => e.node);
cartLines = lines;
// Update count badges
const totalQty = cart.totalQuantity || lines.reduce((sum, l) => sum + l.quantity, 0);
cartCountEls.forEach((el) => (el.textContent = totalQty));
if (!lines.length) {
clearCartId();
cartItemsEl.innerHTML = `
<div class="cart-empty">
<p>Your cart is empty</p>
<span>Browse our collection to find something you love.</span>
</div>`;
if (cartFooter) cartFooter.style.display = 'none';
return;
}
cartItemsEl.innerHTML = lines
.map((line) => {
const variant = line.merchandise;
const productTitle = variant.product?.title || '';
const variantTitle = variant.title !== 'Default Title' ? variant.title : '';
return `
<div class="cart-line-item">
<div class="cart-line-img">
${variant.image ? `<img src="${variant.image.url}" alt="${variant.image.altText || productTitle}">` : ''}
</div>
<div class="cart-line-details">
<h4>${productTitle}</h4>
<p class="cart-line-variant">${variantTitle}${variantTitle ? ' · ' : ''}Qty: ${line.quantity}</p>
<p class="cart-line-price">${formatPrice(variant.price.amount, variant.price.currencyCode)}</p>
<button class="cart-line-remove" data-line-id="${line.id}">Remove</button>
</div>
</div>`;
})
.join('');
// Subtotal
if (cartSubtotal && cart.cost?.subtotalAmount) {
cartSubtotal.textContent = formatPrice(cart.cost.subtotalAmount.amount, cart.cost.subtotalAmount.currencyCode);
}
if (cartFooter) cartFooter.style.display = 'block';
// Remove button listeners
cartItemsEl.querySelectorAll('.cart-line-remove').forEach((btn) => {
btn.addEventListener('click', async () => {
await removeFromCart(btn.dataset.lineId);
});
});
}
async function addToCart(variantId, quantity = 1) {
try {
if (!cartId) {
// Create a new cart with the item
const data = await shopifyFetch(QUERIES.cartCreate, {
input: {
lines: [{ merchandiseId: variantId, quantity }],
},
});
if (data.cartCreate.userErrors.length) {
throw new Error(data.cartCreate.userErrors[0].message);
}
updateCartUI(data.cartCreate.cart);
} else {
// Add to existing cart
const data = await shopifyFetch(QUERIES.cartLinesAdd, {
cartId,
lines: [{ merchandiseId: variantId, quantity }],
});
if (data.cartLinesAdd.userErrors.length) {
throw new Error(data.cartLinesAdd.userErrors[0].message);
}
updateCartUI(data.cartLinesAdd.cart);
}
openCart();
} catch (err) {
console.error('Add to cart failed:', err);
alert('Could not add to cart. Please check your Shopify configuration.\n\n' + err.message);
}
}
async function removeFromCart(lineId) {
if (!cartId) return;
try {
const data = await shopifyFetch(QUERIES.cartLinesRemove, {
cartId,
lineIds: [lineId],
});
if (data.cartLinesRemove.userErrors.length) {
throw new Error(data.cartLinesRemove.userErrors[0].message);
}
updateCartUI(data.cartLinesRemove.cart);
} catch (err) {
console.error('Remove from cart failed:', err);
}
}
// =====================================================
// Demo / Fallback Products
// =====================================================
const DEMO_PRODUCTS = [
{ id: '1', title: "Phantom 6'2 Shortboard", handle: 'phantom-62-shortboard', description: "High-performance shortboard with a pulled-in tail and single-to-double concave. Built for fast, hollow waves. EPS/epoxy construction for lightweight speed.", productType: 'Surfboards', vendor: 'Salt & Tide', tags: ['surfboards','shortboard'], priceRange: { minVariantPrice: { amount: '685.00', currencyCode: 'USD' } }, images: { edges: [] }, variants: { edges: [
{ node: { id: 'v1-a', title: "5'10", availableForSale: true, price: { amount: '685.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "5'10" }], image: null } },
{ node: { id: 'v1-b', title: "6'0", availableForSale: true, price: { amount: '685.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "6'0" }], image: null } },
{ node: { id: 'v1-c', title: "6'2", availableForSale: true, price: { amount: '685.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "6'2" }], image: null } },
{ node: { id: 'v1-d', title: "6'4", availableForSale: true, price: { amount: '685.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "6'4" }], image: null } },
] }, availableForSale: true, createdAt: '2026-03-01' },
{ id: '2', title: 'Stealth 3/2mm Wetsuit', handle: 'stealth-32mm-wetsuit', description: 'Full-body 3/2mm wetsuit in matte black Yamamoto neoprene. Chest zip entry, sealed seams, and four-way stretch panels for unrestricted paddling.', productType: 'Wetsuits', vendor: 'Salt & Tide', tags: ['wetsuits'], priceRange: { minVariantPrice: { amount: '345.00', currencyCode: 'USD' } }, images: { edges: [] }, variants: { edges: [
{ node: { id: 'v2-s', title: 'S', availableForSale: true, price: { amount: '345.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: 'S' }], image: null } },
{ node: { id: 'v2-m', title: 'M', availableForSale: true, price: { amount: '345.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: 'M' }], image: null } },
{ node: { id: 'v2-l', title: 'L', availableForSale: true, price: { amount: '345.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: 'L' }], image: null } },
{ node: { id: 'v2-xl', title: 'XL', availableForSale: true, price: { amount: '345.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: 'XL' }], image: null } },
] }, availableForSale: true, createdAt: '2026-03-05' },
{ id: '3', title: 'Reef Runner Boardshorts', handle: 'reef-runner-boardshorts', description: '4-way stretch boardshorts with a 19" outseam. Quick-dry fabric, no-rash flatlock seams, and a secure drawcord waist. Built to perform in and out of the water.', productType: 'Boardshorts', vendor: 'Salt & Tide', tags: ['boardshorts'], priceRange: { minVariantPrice: { amount: '78.00', currencyCode: 'USD' } }, images: { edges: [] }, variants: { edges: [
{ node: { id: 'v3-30', title: '30', availableForSale: false, price: { amount: '78.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: '30' }], image: null } },
{ node: { id: 'v3-32', title: '32', availableForSale: true, price: { amount: '78.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: '32' }], image: null } },
{ node: { id: 'v3-34', title: '34', availableForSale: true, price: { amount: '78.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: '34' }], image: null } },
{ node: { id: 'v3-36', title: '36', availableForSale: true, price: { amount: '78.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: '36' }], image: null } },
] }, availableForSale: true, createdAt: '2026-02-20' },
{ id: '4', title: "Drifter 9'0 Longboard", handle: 'drifter-90-longboard', description: "Classic noserider longboard with a wide nose, rolled bottom, and single fin setup. PU/polyester for that traditional flex and glide. Smooth, effortless cruising.", productType: 'Surfboards', vendor: 'Salt & Tide', tags: ['surfboards','longboard'], priceRange: { minVariantPrice: { amount: '895.00', currencyCode: 'USD' } }, images: { edges: [] }, variants: { edges: [
{ node: { id: 'v4-a', title: "8'6", availableForSale: true, price: { amount: '895.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "8'6" }], image: null } },
{ node: { id: 'v4-b', title: "9'0", availableForSale: true, price: { amount: '895.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "9'0" }], image: null } },
{ node: { id: 'v4-c', title: "9'6", availableForSale: true, price: { amount: '895.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "9'6" }], image: null } },
] }, availableForSale: true, createdAt: '2026-03-10' },
{ id: '5', title: 'Dawn Patrol Rashguard', handle: 'dawn-patrol-rashguard', description: 'UPF 50+ long-sleeve rashguard in charcoal. Flatlock stitching, snug athletic fit, and quick-dry poly-spandex blend. Your skin will thank you.', productType: 'Wetsuits', vendor: 'Salt & Tide', tags: ['wetsuits','rashguard'], priceRange: { minVariantPrice: { amount: '58.00', currencyCode: 'USD' } }, images: { edges: [] }, variants: { edges: [
{ node: { id: 'v5-s', title: 'S', availableForSale: true, price: { amount: '58.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: 'S' }], image: null } },
{ node: { id: 'v5-m', title: 'M', availableForSale: true, price: { amount: '58.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: 'M' }], image: null } },
{ node: { id: 'v5-l', title: 'L', availableForSale: true, price: { amount: '58.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: 'L' }], image: null } },
{ node: { id: 'v5-xl', title: 'XL', availableForSale: true, price: { amount: '58.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: 'XL' }], image: null } },
] }, availableForSale: true, createdAt: '2026-03-12' },
{ id: '6', title: 'Riptide Hybrid Shorts', handle: 'riptide-hybrid-shorts', description: "Hybrid walk-to-water shorts with a 17\" outseam. Stretch twill fabric works on the beach or around town. Zip pocket keeps your keys safe in the lineup.", productType: 'Boardshorts', vendor: 'Salt & Tide', tags: ['boardshorts'], priceRange: { minVariantPrice: { amount: '68.00', currencyCode: 'USD' } }, images: { edges: [] }, variants: { edges: [
{ node: { id: 'v6-30', title: '30', availableForSale: true, price: { amount: '68.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: '30' }], image: null } },
{ node: { id: 'v6-32', title: '32', availableForSale: true, price: { amount: '68.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: '32' }], image: null } },
{ node: { id: 'v6-34', title: '34', availableForSale: true, price: { amount: '68.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: '34' }], image: null } },
] }, availableForSale: true, createdAt: '2026-02-28' },
{ id: '7', title: 'Board Bag — Shortboard', handle: 'board-bag-shortboard', description: "Day-use board bag with 5mm padding, reflective heat shield, and heavy-duty YKK zipper. Fits boards up to 6'6. Shoulder strap included.", productType: 'Accessories', vendor: 'Salt & Tide', tags: ['accessories','bag'], priceRange: { minVariantPrice: { amount: '95.00', currencyCode: 'USD' } }, images: { edges: [] }, variants: { edges: [
{ node: { id: 'v7-os', title: "Up to 6'6", availableForSale: true, price: { amount: '95.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "Up to 6'6" }], image: null } },
] }, availableForSale: true, createdAt: '2026-03-08' },
{ id: '8', title: "Cruiser 7'2 Funboard", handle: 'cruiser-72-funboard', description: "The do-everything mid-length. Wide enough for small days, refined enough for overhead surf. Thruster or quad fin setup. Perfect for progressing surfers.", productType: 'Surfboards', vendor: 'Salt & Tide', tags: ['surfboards','funboard'], priceRange: { minVariantPrice: { amount: '745.00', currencyCode: 'USD' } }, images: { edges: [] }, variants: { edges: [
{ node: { id: 'v8-a', title: "6'8", availableForSale: true, price: { amount: '745.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "6'8" }], image: null } },
{ node: { id: 'v8-b', title: "7'2", availableForSale: true, price: { amount: '745.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "7'2" }], image: null } },
{ node: { id: 'v8-c', title: "7'6", availableForSale: true, price: { amount: '745.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: "7'6" }], image: null } },
] }, availableForSale: true, createdAt: '2026-03-03' },
{ id: '9', title: 'Surf Wax Combo Pack', handle: 'surf-wax-combo-pack', description: 'Three-bar wax pack — cold, cool, and tropical temps covered. Organic coconut-based formula with great grip and a clean scent.', productType: 'Accessories', vendor: 'Salt & Tide', tags: ['accessories','wax'], priceRange: { minVariantPrice: { amount: '14.00', currencyCode: 'USD' } }, images: { edges: [] }, variants: { edges: [
{ node: { id: 'v9-os', title: 'Combo Pack', availableForSale: true, price: { amount: '14.00', currencyCode: 'USD' }, selectedOptions: [{ name: 'Size', value: 'Combo Pack' }], image: null } },
] }, availableForSale: true, createdAt: '2026-03-14' },
];
// =====================================================
// Initialization
// =====================================================
async function init() {
if (!productGrid) return;
try {
const data = await shopifyFetch(QUERIES.allProducts, { first: 50 });
allProducts = data.products.edges.map((e) => e.node);
console.log(`Loaded ${allProducts.length} products from Shopify`);
} catch (err) {
console.warn('Shopify not configured or unreachable — using demo products. Update CONFIG in shopify.js to connect.');
allProducts = DEMO_PRODUCTS;
}
if (shopLoading) shopLoading.style.display = 'none';
filterAndSort();
// Restore cart from previous session if one exists
await restoreCart();
}
// =====================================================
// Event Listeners
// =====================================================
filterBtns.forEach((btn) => {
btn.addEventListener('click', () => {
filterBtns.forEach((b) => b.classList.remove('active'));
btn.classList.add('active');
currentFilter = btn.dataset.filter;
filterAndSort();
});
});
if (sortSelect) sortSelect.addEventListener('change', filterAndSort);
if (cartToggleBtn) cartToggleBtn.addEventListener('click', openCart);
if (cartOverlay) cartOverlay.addEventListener('click', closeCart);
if (cartCloseBtn) cartCloseBtn.addEventListener('click', closeCart);
if (checkoutBtn) {
checkoutBtn.addEventListener('click', () => {
if (checkoutUrl) {
clearCartId();
window.open(checkoutUrl, '_blank');
window.location.reload();
} else {
alert('Checkout not available. Please connect your Shopify store.');
}
});
}
if (quickViewOverlay) quickViewOverlay.addEventListener('click', closeQuickView);
if (quickViewCloseBtn) quickViewCloseBtn.addEventListener('click', closeQuickView);
if (addToCartBtn) {
addToCartBtn.addEventListener('click', async () => {
if (!selectedVariantId) {
alert('Please select a size.');
return;
}
addToCartBtn.textContent = 'Adding...';
addToCartBtn.disabled = true;
// Demo mode check
if (CONFIG.storefrontAccessToken === 'your-storefront-access-token') {
setTimeout(() => {
closeQuickView();
addToCartBtn.textContent = 'Add to Cart';
addToCartBtn.disabled = false;
alert('Demo mode: Connect your Shopify store in shopify.js to enable real cart functionality.');
}, 600);
return;
}
await addToCart(selectedVariantId);
closeQuickView();
addToCartBtn.textContent = 'Add to Cart';
addToCartBtn.disabled = false;
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeQuickView();
closeCart();
}
});
// Boot
init();
return { addToCart, openCart, closeCart };
})();