-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjs.html
More file actions
1815 lines (1514 loc) · 79.3 KB
/
Copy pathjs.html
File metadata and controls
1815 lines (1514 loc) · 79.3 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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<script>
/**
* Global State
*/
let PRODUCT_CATALOG = [];
let CURRENT_CLIENT = null;
let IS_ADMIN = false;
let ADMIN_KEY = ""; // Fetched from server via ADMIN_LOGIN named range
const CLIENT_ID = window.initialClientId; // Defined in index.html
/**
* Global Failure Handler for google.script.run calls
*/
function onFailure(error) {
console.error("[onFailure] Server error:", error);
showToast("Server Error: " + (error.message || error), 'error');
}
/**
* Show Toast/Snackbar Notification (replaces alert())
* @param {string} message - The message to display
* @param {string} type - 'success', 'error', or '' for default
* @param {number} duration - How long to show (ms), default 4000
*/
function showToast(message, type = '', duration = 4000) {
const snackbar = document.getElementById('snackbar');
if (!snackbar) {
// Fallback to alert if snackbar element not found
alert(message);
return;
}
snackbar.textContent = message;
snackbar.className = 'md3-snackbar';
if (type) snackbar.classList.add(type);
// Show
setTimeout(() => snackbar.classList.add('show'), 10);
// Hide after duration
setTimeout(() => {
snackbar.classList.remove('show');
}, duration);
}
/**
* Helper: Normalize category names to match server-side logic
* Must match superNormalize in Config.gs
*/
function superNormalize(s) {
return String(s || "").toLowerCase().replace(/[^a-z0-9]/g, '').replace(/s$/, '');
}
/**
* Helper: Convert string to safe CSS Class
*/
function toCssClass(str) {
if (!str) return 'cat-unknown';
// USE superNormalize to ensure plural versions (Darts) match singular keys (Dart)
const norm = superNormalize(str);
return 'cat-' + norm;
}
/**
* Helper: Escape Regex Characters
*/
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Helper: Calculate Contrast Color (Black or White) from Hex
*/
function getContrastYIQ(hexcolor) {
hexcolor = hexcolor.replace("#", "");
var r = parseInt(hexcolor.substr(0, 2), 16);
var g = parseInt(hexcolor.substr(2, 2), 16);
var b = parseInt(hexcolor.substr(4, 2), 16);
var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
// Reverted to 190 per user request to prefer White text
return (yiq >= 190) ? 'black' : 'white';
}
/**
* Initialize
*/
window.onload = function () {
// Apply branding immediately (Login screen needs it too)
applyCategoryColorsVisuals();
if (!CLIENT_ID) {
// No ID in URL -> Show Login View
document.getElementById('loading').classList.add('hidden');
document.getElementById('login-view').classList.remove('hidden');
return;
}
// DEBUG: Alert to confirm we are starting
// alert("App Loaded. Client ID: " + CLIENT_ID);
document.getElementById('header-total').classList.remove('hidden'); // Show Subtotal
// Scroll Shadow for App Bar
window.addEventListener('scroll', () => {
const appBar = document.querySelector('.md3-top-app-bar');
if (window.scrollY > 0) {
appBar.classList.add('scrolled-header');
} else {
appBar.classList.remove('scrolled-header');
}
}, { passive: true });
// 2. Fetch Client Data
fetchClientData(CLIENT_ID);
};
function handleManualLogin() {
const input = document.getElementById('manual-client-id');
const id = input.value.trim();
if (!id) {
showLoginError("Please enter a Client ID.");
return;
}
// Check for Admin Key (from ADMIN_LOGIN named range via appConfig)
const adminKey = (window.appConfig && window.appConfig.ADMIN_KEY) || "ADMIN123";
if (id.toUpperCase() === adminKey.toUpperCase()) {
IS_ADMIN = true;
document.getElementById('login-view').classList.add('hidden');
document.getElementById('loading').classList.remove('hidden');
// Admins don't have a specific client record initially
onAdminLoginSuccess();
return;
}
// Hide Login, Show Loading
document.getElementById('login-view').classList.add('hidden');
document.getElementById('loading').classList.remove('hidden');
// Update Global and Fetch
fetchClientData(id);
}
function onAdminLoginSuccess() {
IS_ADMIN = true;
document.getElementById('nav-tabs').classList.remove('hidden');
// Show Admin Tab
document.getElementById('admin-tab').classList.remove('hidden');
document.getElementById('loading').classList.add('hidden');
showView('history-view'); // Default to history for admins
// 1. Fetch Products for Admin (to populate "New Order" tab)
google.script.run
.withSuccessHandler(onProductsSuccess)
.withFailureHandler(onFailure)
.getProductCatalog();
// 2. Fetch all orders for admin
google.script.run
.withSuccessHandler(renderOrderHistory)
.withFailureHandler(onFailure)
.getOrdersByClient('');
// 3. Init Admin Form (Lazy load or eager?)
if (typeof initAdminModule === 'function') {
initAdminModule();
}
}
function showLoginError(msg) {
const el = document.getElementById('login-error-msg');
el.textContent = msg;
el.classList.remove('hidden');
document.getElementById('manual-client-id').classList.add('error-state'); // Optional: shake or red border
}
function clearLoginError() {
document.getElementById('login-error-msg').classList.add('hidden');
}
function fetchClientData(id) {
google.script.run
.withSuccessHandler(onClientDataSuccess)
.withFailureHandler(onLoginFailure)
.getClientById(id);
}
function onLoginFailure(error) {
// If specific login fail
showError("Invalid Client ID or System Error.");
// DEBUG: Fetch and show debug info to help user
const input = document.getElementById('manual-client-id');
const id = input ? input.value : (CLIENT_ID || "Unknown");
google.script.run
.withSuccessHandler(info => {
const msg = `DEBUG RAW DATA:\nSheet: ${info.sheetName}\nTotal Rows: ${info.totalSheetRows}\nRaw Headers (Row 1): ${info.rawHeaders}\nFirst Data (Row 2): ${info.rawFirstRowData}\nParsed Keys: ${info.parsedObjectKeys}`;
alert(msg);
})
.debugClientLookup(id);
document.getElementById('error').innerHTML += `<br><button class="md3-btn-filled" onclick="location.reload()">Try Again</button>`;
}
function onClientDataSuccess(client) {
// alert("Client Data Success: " + (client ? client.Name : "null"));
if (!client) {
showError("Client not found in database.");
return;
}
CURRENT_CLIENT = client;
document.getElementById('client-name-input').value = client['Name'] || "";
document.getElementById('client-address-input').value = client['Address'] || "";
// Client View: No Tabs, just the form
document.getElementById('nav-tabs').classList.add('hidden');
IS_ADMIN = false;
// 2. Fetch Products
// alert("Fetching Products...");
google.script.run
.withSuccessHandler(onProductsSuccess)
.withFailureHandler(onFailure)
.getProductCatalog();
}
/**
* View Management
*/
function showView(viewId) {
// Toggle Active Views
document.querySelectorAll('.state-view, form').forEach(el => {
if (el.id === 'loading' || el.id === 'error' || el.id === 'bubble-overlay' || el.id === 'details-bubble' || el.id === 'success') return;
el.classList.add('hidden');
});
const target = document.getElementById(viewId);
if (target) target.classList.remove('hidden');
// Toggle Tab States
document.querySelectorAll('.md3-tab').forEach(tab => {
const onClick = tab.getAttribute('onclick');
if (onClick && onClick.includes(viewId)) {
tab.classList.add('active');
} else {
tab.classList.remove('active');
}
});
// Specific View Logic
if (viewId === 'order-form') {
document.getElementById('collapse-fab').classList.remove('hidden');
document.getElementById('header-total').classList.remove('hidden');
} else {
document.getElementById('collapse-fab').classList.add('hidden');
document.getElementById('header-total').classList.add('hidden');
}
// Recalculate sticky header offsets whenever the view/tabs change
if (typeof updateStickyOffsets === 'function') updateStickyOffsets();
}
/**
* History Logic
*/
function fetchOrderHistory(clientName) {
if (!clientName) return;
google.script.run
.withSuccessHandler(renderOrderHistory)
.getOrdersByClient(clientName);
}
function renderOrderHistory(orders) {
let selector = document.getElementById('order-selector');
let status = document.getElementById('history-status');
// Retry once if selector not found (timing issue)
if (!selector) {
console.warn("[renderOrderHistory] Selector not found, retrying in 500ms...");
setTimeout(() => {
selector = document.getElementById('order-selector');
status = document.getElementById('history-status');
if (selector) {
populateOrderDropdown(selector, status, orders);
} else {
console.error("[renderOrderHistory] Retry failed. #order-selector does not exist.");
alert("Error: Order selector element not found. Please refresh.");
}
}, 500);
return;
}
populateOrderDropdown(selector, status, orders);
}
function populateOrderDropdown(selector, status, orders) {
// Reset
selector.innerHTML = '<option value="">-- Choose an Order --</option>';
if (!orders || orders.length === 0) {
if (status) status.textContent = "No previous orders found.";
return;
}
if (status) status.textContent = `Found ${orders.length} orders.`;
orders.forEach(order => {
const dateStr = new Date(order.timestamp).toLocaleDateString(undefined, {
year: 'numeric', month: 'short', day: 'numeric'
});
const clientInfo = IS_ADMIN ? `(${order.clientName}) ` : '';
const option = document.createElement('option');
option.value = order.id;
const stateLabel = order.state ? ` [${order.state.toUpperCase()}]` : '';
option.textContent = `${clientInfo}${order.id}${stateLabel} - ${dateStr} - $${Number(order.total || 0).toFixed(2)}`;
selector.appendChild(option);
});
}
function handleOrderSelection(orderId) {
if (!orderId) return;
editHistoricalOrder(orderId);
}
function editHistoricalOrder(orderId) {
// Show Loading
const loader = document.getElementById('loading');
const loadText = document.getElementById('loading-text');
if (loadText) loadText.textContent = "Loading Order Details...";
loader.classList.remove('hidden');
google.script.run
.withSuccessHandler(data => {
console.log("[editHistoricalOrder] Received data:", data);
if (!data) {
alert("Order data not found or row is empty. (v1.8.51)");
loader.classList.add('hidden');
return;
}
window.prefillData = data;
window.editOrderId = data.id;
const existingInputs = document.querySelectorAll('input.qty-input');
if (existingInputs.length > 0) {
// Products already rendered, prefill now
prefillOrderForm(data);
} else {
// Products not yet rendered, onProductsSuccess will handle prefill
}
showView('order-form');
loader.classList.add('hidden');
})
.withFailureHandler(err => {
alert("Error loading order: " + err.message);
loader.classList.add('hidden');
})
.getOrderById(orderId);
}
function onProductsSuccess(products) {
PRODUCT_CATALOG = products;
// Fetch Admin Key from config if available (Prioritize appConfig over categorySettings)
window.ADMIN_KEY = (window.appConfig && window.appConfig.ADMIN_KEY) ||
(window.categorySettings?.main?.adminKey) ||
"ADMIN123";
// Filter products based on client section permissions (non-admins only)
let filteredProducts = products;
if (!IS_ADMIN && CURRENT_CLIENT && CURRENT_CLIENT.allowedSections) {
const allowedSections = CURRENT_CLIENT.allowedSections;
console.log('[ProductFilter] Client allowed sections:', allowedSections);
filteredProducts = products.filter(product => {
const productCategory = superNormalize(product.category || '');
const catSettings = window.categorySettings ? window.categorySettings[productCategory] : null;
const productSection = catSettings ? (catSettings.section || '').toUpperCase() : '';
if (!productSection) return true;
return allowedSections.includes(productSection);
});
}
try {
renderProducts(filteredProducts);
if (window.prefillData) {
prefillOrderForm(window.prefillData);
}
} catch (e) {
console.error("Render Error:", e);
}
document.getElementById('loading').classList.add('hidden');
// v1.8.31 FIX: Only show the form if we aren't an admin (direct entry)
// OR if we are explicitly on the form view.
const currentView = document.querySelector('.md3-tab.active')?.getAttribute('onclick');
const isOnForm = currentView ? currentView.includes('order-form') : true;
if (!IS_ADMIN || isOnForm) {
document.getElementById('order-form').classList.remove('hidden');
document.getElementById('collapse-fab').classList.remove('hidden');
}
}
/**
* Prefill Order Form from Data
*/
function prefillOrderForm(data) {
if (!data || !data.items) {
console.warn("[prefillOrderForm] No items to prefill.");
return;
}
// 2. Populate Quantities
// 1. Populate Client Info
if (data.clientName) document.getElementById('client-name-input').value = data.clientName;
if (data.clientComments) document.getElementById('client-comments-input').value = data.clientComments;
// 2. Populate Quantities
Object.keys(data.items).forEach(sku => {
const item = data.items[sku];
// FIX v1.8.45: Strip @ prefix, input IDs are just the SKU (no qty- prefix)
const normalizedSku = sku.replace(/^@/, '');
const input = document.getElementById(normalizedSku);
if (input) {
input.value = item.qty;
// Dispatch input event to trigger any listeners
input.dispatchEvent(new Event('input', { bubbles: true }));
}
});
// 3. Recalculate Totals
if (typeof calculateTotal === 'function') {
calculateTotal();
}
}
/**
* Collapse All Categories
*/
function collapseAllCats() {
const details = document.querySelectorAll('details');
details.forEach(d => d.open = false);
}
/**
* Helper: Apply Category Colors and Visuals based on settings
*/
function applyCategoryColorsVisuals() {
if (!window.categorySettings) return;
const styleId = 'dynamic-cat-syles';
let styleBlock = document.getElementById(styleId);
if (!styleBlock) {
styleBlock = document.createElement('style');
styleBlock.id = styleId;
document.head.appendChild(styleBlock);
}
let cssRules = "";
// App Theme Override from APP_STYLES named ranges
const styles = window.appStyles || {};
if (styles.primaryColor) {
// Core theme variables
cssRules += `:root { \n`;
cssRules += ` --md-sys-color-primary: ${styles.primaryColor} !important; \n`;
cssRules += ` --md-sys-color-on-primary: ${styles.primaryTextColor || '#ffffff'} !important; \n`;
cssRules += ` --md-sys-color-secondary: ${styles.secondaryColor || '#625b71'} !important; \n`;
cssRules += ` --md-sys-color-on-secondary: ${styles.secondaryTextColor || '#ffffff'} !important; \n`;
cssRules += `} \n`;
// Forced styles for headers and primary buttons
cssRules += `.app-header, .md3-top-app-bar, .md3-title-large, .total-amount { color: var(--md-sys-color-on-primary) !important; } \n`;
cssRules += `.primary-btn { background-color: var(--md-sys-color-primary) !important; color: var(--md-sys-color-on-primary) !important; } \n`;
// Forced styles for FAB button (secondary color)
cssRules += `.md3-fab-fixed { background-color: ${styles.secondaryColor || '#625b71'} !important; color: ${styles.secondaryTextColor || '#ffffff'} !important; } \n`;
cssRules += `.md3-fab-fixed .material-symbols-outlined { color: ${styles.secondaryTextColor || '#ffffff'} !important; } \n`;
// Header Layout Spacing Fix
cssRules += `.app-header-content { display: flex; align-items: center; justify-content: space-between; padding: 0 16px; } \n`;
cssRules += `#header-total { margin-left: auto; margin-right: 32px; font-variant-numeric: tabular-nums; } \n`;
}
Object.keys(window.categorySettings).forEach(normalizedKey => {
const setting = window.categorySettings[normalizedKey];
const color = (typeof setting === 'object' && setting.color) ? setting.color : (typeof setting === 'string' ? setting : null);
const cleanClass = 'cat-' + normalizedKey;
if (cleanClass && color) {
const textColor = (typeof setting === 'object' && setting.textColor) ? setting.textColor : getContrastYIQ(color);
// Color ONLY in OPEN state
cssRules += `.${cleanClass} [open] > .category-summary { background-color: ${color} !important; color: ${textColor} !important; } \n`;
// Border/Radius logic for Open State
cssRules += `.${cleanClass} [open] > .category-summary { border-top-left-radius: 12px; border-top-right-radius: 12px; border-bottom-left-radius: 0; border-bottom-right-radius: 0; } \n`;
cssRules += `.${cleanClass}:not([open]) > .category-summary { border-radius: 12px; transition: border-radius 0.2s ease; } \n`;
// Content elements
cssRules += `.${cleanClass} .matrix-header-row { background-color: ${color} !important; color: ${textColor} !important; } \n`;
cssRules += `.${cleanClass} { --category-color: ${color}; } \n`;
}
});
if (styleBlock) styleBlock.textContent = cssRules;
}
/**
* Render Product List grouped by Category
* Supports:
* 1. Matrix Groups (e.g. SODA SQ)
* 2. Compact Tables (Standard items)
*/
function renderProducts(products) {
// DEBUG: Check if product exists in raw list
console.log(`[DEBUG] renderProducts received ${products.length} items`);
const debugProd = products.find(p => String(p.name).toLowerCase().includes("pulse x") || String(p.variation).toLowerCase().includes("pulse x"));
console.log("[DEBUG] Searching for 'Pulse X' in raw list:", debugProd);
applyCategoryColorsVisuals(); // Apply styles first
const container = document.getElementById('product-list');
container.innerHTML = "";
// 0. Normalize Data
const normalizedProducts = products.map(p => {
let name = String(p.name).trim();
let varName = String(p.variation || "").trim();
const nameIsSize = /^\d+(\.\d+)?\s*([a-zA-Z%]+)?$/.test(name);
const varIsName = varName && /[a-zA-Z]/.test(varName) && varName.length > 2;
if (nameIsSize && varIsName) {
return { ...p, name: varName, variation: name };
}
return p;
});
// 1. Group by Category
const groupedByCat = {};
normalizedProducts.forEach(p => {
const cat = p.category || "Uncategorized";
if (!groupedByCat[cat]) groupedByCat[cat] = [];
groupedByCat[cat].push(p);
});
// 2. Filter and Sort Categories
let categories = Object.keys(groupedByCat).filter(cat => {
const lowCat = cat.toLowerCase();
return lowCat !== "main" && lowCat !== "category" && lowCat !== "category name";
});
categories.sort((a, b) => {
// Normalize category names to match keys in categorySettings
const normalizedA = superNormalize(a);
const normalizedB = superNormalize(b);
const setA = window.categorySettings && window.categorySettings[normalizedA];
const setB = window.categorySettings && window.categorySettings[normalizedB];
// Default to 999 if no order set
const orderA = (setA && typeof setA.order === 'number') ? setA.order : 999;
const orderB = (setB && typeof setB.order === 'number') ? setB.order : 999;
if (orderA !== orderB) {
return orderA - orderB;
}
// Tie-break: Alphabetical
return a.localeCompare(b);
});
categories.forEach(cat => {
const catDetails = document.createElement('details');
catDetails.open = false; // Default closed
// Add dynamic class using normalization to ensure it matches Settings
const catClass = toCssClass(cat);
catDetails.className = `category-details ${catClass}`;
const catSummary = document.createElement('summary');
catSummary.className = "md3-headline-medium category-summary";
const catHasSale = (groupedByCat[cat] || []).some(p => p.onSale);
catSummary.innerHTML = `
<div style="flex: 1; display: flex; align-items: center;">
<!-- Left placeholder for balance -->
<span class="cat-subtotal-left" style="font-size:0.8em; opacity:0; visibility:hidden;">$0.00</span>
</div>
<span style="flex: 0 1 auto; text-align: center; white-space: nowrap;">
${cat}
</span>
<div style="flex: 1; display: flex; justify-content: flex-end; align-items: center; gap: 12px;">
${catHasSale ? '<span class="sale-badge">SALE</span>' : ''}
<span class="cat-subtotal" style="font-size:0.8em; opacity:0.9; font-weight:bold; display:none;">$0.00</span>
</div>
`;
// Ensure Flex display for spacing
catSummary.style.display = "flex";
catSummary.style.justifyContent = "space-between";
catSummary.style.alignItems = "center";
catSummary.style.textAlign = "center";
catDetails.appendChild(catSummary);
const catContent = document.createElement('div');
catContent.className = "category-content";
const groups = groupProductsDynamically(groupedByCat[cat]);
const groupNames = Object.keys(groups); // NO SORT to keep sheet order
groupNames.forEach(baseName => {
const group = groups[baseName];
const isMatrix = checkMatrixEligibility(group, baseName);
// --- BUILD DYNAMIC HEADER COLUMNS ---
let headerColsHtml = "";
let colDefs = [];
if (isMatrix) {
const hasVar2 = group.some(p => p.variation2);
if (hasVar2) {
// Logic for Variation 2 Columns - NO SORT to keep sheet order
const uniqueVar2 = [...new Set(group.map(p => p.variation2).filter(v => v))];
colDefs = uniqueVar2.map(v2Name => {
return { label: v2Name || "Std", price: "", name: v2Name, isVar2: true };
});
} else {
// Classic Logic (Name-based Columns) - NO SORT to keep sheet order
const allNames = [...new Set(group.map(p => p.name))];
colDefs = allNames.map(name => {
const regex = new RegExp("^" + escapeRegex(baseName), "i");
let label = name.replace(regex, "").trim();
label = label.replace(/^[\s\-\&]+/, "").trim(); // Clean prefix
if (!label) label = "Std";
const p = group.find(prod => prod.name === name);
const price = p ? Number(p.price).toFixed(2) : "0.00";
return { label: label, price: price, name: name, isVar2: false };
});
}
// POPULATE STICKY HEADERS FOR MATRIX
headerColsHtml = colDefs.map(col => `
<div style="width:48px !important; max-width:48px !important; min-width:48px !important;
flex:0 0 48px !important; overflow:hidden; text-align:center;">
<span class="qty-header-label" style="font-size:10px; font-weight:bold; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; display:block;">${col.label}</span>
</div>
`).join("");
} else {
// Standard / Compact Logic
const caseProducts = group.filter(p => p.hasCase);
const showCase = caseProducts.length > 0;
// Identify common spec (e.g. "50mg") to display in header
const uniqueSpecs = [...new Set(group.map(p => String(p.variation2 || "").trim()).filter(v => v && v.toLowerCase() !== "undefined"))];
const commonSpec = uniqueSpecs.length === 1 ? uniqueSpecs[0] : "";
if (commonSpec) {
headerColsHtml += `<div class="col-data" style="margin-right:auto; padding-left:12px; color:inherit; font-size:12px; font-weight:900; opacity:0.9;">${commonSpec}</div>`;
}
let caseHeaderLabel = "Case";
// Check if all cases have same size
if (showCase) {
const firstSize = parseInt(caseProducts[0].unitsPerCase) || 1;
const allSame = caseProducts.every(p => (parseInt(p.unitsPerCase) || 1) === firstSize);
if (allSame) {
caseHeaderLabel += `<br><span style="font-size:10px; opacity:0.8;">(Box ${firstSize})</span>`;
}
}
// NEW: Prices Aligned Above Columns
const leaderP = group.find(p => Number(p.price) > 0) || group[0];
const pSingleLeader = group.find(p => !p.hasCase && Number(p.price) > 0) || group.find(p => !p.hasCase) || leaderP;
const buildPriceHeader = (p, subLabel) => {
const isSaleOn = !!p.onSale;
const hasDisc = isSaleOn && (Number(p.salePrice) > 0 && Number(p.salePrice) < Number(p.price));
const reg = Number(p.price).toFixed(2);
const sale = Number(p.salePrice).toFixed(2);
let cell = `<div class="col-data">`;
if (hasDisc) {
cell += `<span class="price-header-label strikethrough" style="text-decoration:line-through; font-size:9px; opacity:0.7;">$${reg}</span>`;
cell += `<span class="price-header-label sale-price-highlight" style="font-weight:900;">$${sale}</span>`;
} else {
const displayP = isSaleOn ? p.salePrice : p.price;
cell += `<span class="price-header-label">$${Number(displayP).toFixed(2)}</span>`;
}
if (subLabel) {
cell += `<div style="font-size:9px; opacity:0.6; line-height:1; margin-top:2px;">${subLabel}</div>`;
}
cell += `</div>`;
return cell;
};
// Only show Single header when the group actually has non-case products.
// If ALL products are cases (e.g. Master Case only), skip the empty Single column.
const showSingle = group.some(p => !p.hasCase);
if (showSingle) {
headerColsHtml += buildPriceHeader(pSingleLeader, "Single");
}
// 2. Case Price Column Header (if applicable)
if (showCase) {
const pCaseLeader = group.find(p => p.hasCase && Number(p.price) > 0) || group.find(p => p.hasCase) || leaderP;
const caseSubLabel = showSingle ? caseHeaderLabel : "";
headerColsHtml += buildPriceHeader(pCaseLeader, caseSubLabel);
}
}
// Determine Sticky
const isSticky = group.length > 2;
const prodDetails = document.createElement('details');
prodDetails.open = false; // Default closed
// ASSIGN DYNAMIC CATEGORY CLASS
const catClass = toCssClass(cat);
prodDetails.className = `product-group-details mb-3 ${catClass}`;
const prodSummary = document.createElement('summary');
prodSummary.className = "product-group-header";
if (!isSticky) prodSummary.classList.add('no-sticky');
// MAIN FLEX HEADER
// Determine Header Color (Directive v1.8.17: Comprehensive White Filtering)
const leader = group[0];
const gColor = String(leader.groupColor || "").trim().toLowerCase();
const bColor = String(leader.backgroundColor || "").trim().toLowerCase();
const isWhite = (c) => (c === "#ffffff" || c === "#fff" || c === "white" || c === "transparent");
let headerColor = "";
if (gColor && !isWhite(gColor)) headerColor = leader.groupColor;
else if (bColor && !isWhite(bColor)) headerColor = leader.backgroundColor;
const headerTextColor = String(leader.groupTextColor || leader.textColor || "").trim();
// Final Header Color: 1. Group Override, 2. Category Color, 3. Neutral Default
const catSet = window.categorySettings ? window.categorySettings[superNormalize(cat)] : null;
const finalHeaderColor = headerColor || (catSet ? catSet.color.trim() : "#f8f9fa");
const groupClass = 'prod-' + escapeRegex(baseName).replace(/[^a-zA-Z0-9-]/g, '-').toLowerCase();
prodDetails.classList.add(groupClass);
const dynamicStyle = document.getElementById('dynamic-cat-syles');
if (dynamicStyle) {
const textColor = (headerTextColor && headerTextColor !== '#000000') ? headerTextColor : getContrastYIQ(finalHeaderColor);
// Color ONLY when the group is open (expanded). Closed = white/default.
const openRule = `.${groupClass}[open] > summary { background-color: ${finalHeaderColor} !important; color: ${textColor} !important; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2) !important; }`;
dynamicStyle.textContent += openRule + '\n';
dynamicStyle.textContent += `.${groupClass}[open] > summary.header-content { color: ${textColor} !important; } \n`;
dynamicStyle.textContent += `.${groupClass}[open] > summary.header-content a { color: ${textColor} !important; } \n`;
}
// --- DATA INTEGRITY CHECK ---
const varCounts = group.map(p => [p.variation, p.variation2, p.variation3, p.variation4].filter(v => v && String(v).trim() !== "").length);
const isConsistent = varCounts.every(v => v === varCounts[0]);
let integrityWarning = "";
if (!isConsistent) {
integrityWarning = `<span class="material-symbols-outlined" style="color:#D32F2F; font-size:16px; vertical-align:middle; cursor:help;" title="Data Inconsistency Detected: Variations are not uniform across this group. Contact Admin.">warning</span>`;
}
prodSummary.innerHTML = `
<div class="header-content grid-header-row">
<span class="prod-title col-name" style="font-size: 1.1em; font-weight: 700; font-family: var(--md-ref-typeface-brand), sans-serif;">
${integrityWarning}
${baseName}
${group.some(p => p.onSale) ? '<span class="sale-badge">SALE</span>' : ''}
${(group[0].image || group[0].description) ?
`<a href="#" onclick="showDetails(event, '${group[0].name}', '${(group[0].description || "").replace(/'/g, "\\'")}', '${(group[0].image || "").replace(/'/g, "\\'")}', '${Number(group[0].salePrice || 0)}', '${Number(group[0].price || 0)}')"
style="font-size:11px; margin-left:8px; color:inherit; text-decoration:underline; opacity:0.9;">Details</a>`
: ""}
</span>
<!--Subtotal Span-->
<span class="prod-subtotal" style="font-size:0.9em; font-weight:bold; margin-right: 12px; display:none;">$0.00</span>
<!--Header Cols for Alignment when open-->
<div class="header-expanded-content" style="display:flex; flex:1; justify-content: flex-end;">
${headerColsHtml}
</div>
</div>`;
prodDetails.appendChild(prodSummary);
const prodContent = document.createElement('div');
prodContent.className = "product-content details-animation-wrapper"; // Added wrapper class
if (isMatrix) {
// Pass dynamic colors from the group representative
const sample = group[0];
const matBg = sample.backgroundColor || "var(--md-sys-color-primary)";
const matTx = sample.textColor || "var(--md-sys-color-on-primary)";
prodContent.innerHTML = renderMatrixGroupFlex(baseName, group, colDefs, matBg, matTx);
} else {
prodContent.innerHTML = renderCompactTableFlex(baseName, group);
}
prodDetails.appendChild(prodContent);
catContent.appendChild(prodDetails);
});
// Wrap category content as well for animation
const catWrapper = document.createElement('div');
catWrapper.className = "details-animation-wrapper";
catWrapper.appendChild(catContent);
catDetails.appendChild(catWrapper);
container.appendChild(catDetails);
});
attachInputListeners();
setupStickyObservers();
// Initialize Accordion Animation Logic
initAccordionAnimation();
// Set sticky top offsets based on real measured heights
updateStickyOffsets();
}
// --- STICKY OFFSET CALCULATOR ---
// Measures the bottom edge of the whole sticky app-bar block in one shot
// so we don't need to track tabs separately (on mobile the tabs live inside
// the app bar, so a single getBoundingClientRect().bottom already includes them).
function updateStickyOffsets() {
const appBar = document.querySelector('.md3-top-app-bar');
if (!appBar) return;
// Force a synchronous layout flush so we read post-resize values
appBar.getBoundingClientRect(); // trigger reflow
// bottom of app bar relative to the document (includes any OS banner above)
const appBarBottom = Math.round(appBar.getBoundingClientRect().bottom + window.scrollY);
// On mobile, tabs are inside the app bar, so appBarBottom already
// accounts for them. On desktop, nav-tabs live outside the bar:
// add their height only when they are NOT inside the bar.
const tabs = document.getElementById('nav-tabs');
let extraTabsH = 0;
if (tabs && !tabs.classList.contains('hidden') && !appBar.contains(tabs)) {
extraTabsH = tabs.offsetHeight;
}
const catTop = appBarBottom + extraTabsH;
const catSummaryH = Math.round(
(document.querySelector('.category-details>summary') || { offsetHeight: 52 }).offsetHeight
);
const prodTop = catTop + catSummaryH;
document.documentElement.style.setProperty('--cat-sticky-top', catTop + 'px');
document.documentElement.style.setProperty('--prod-sticky-top', prodTop + 'px');
}
// Watch for layout shifts (e.g. Google security banner dismissed) and
// recalculate sticky offsets. Only set up once.
(function initStickyObserver() {
if (window._stickyObserverReady) return;
window._stickyObserverReady = true;
// ResizeObserver fires whenever the body size changes (banner dismissal
// makes the iframe taller, shifting everything up).
if (window.ResizeObserver) {
new ResizeObserver(() => {
if (typeof updateStickyOffsets === 'function') updateStickyOffsets();
}).observe(document.body);
}
// Fallback: also recalculate on window resize
window.addEventListener('resize', () => {
if (typeof updateStickyOffsets === 'function') updateStickyOffsets();
}, { passive: true });
})();
// --- ACCORDION ANIMATION HELPER ---
function initAccordionAnimation() {
if (window._accordionInitialized) return;
window._accordionInitialized = true;
// Exclusive accordion — only one item open at each level at a time.
// Category level: opening a category closes every other category.
// Product level: opening a product group closes every other product
// group WITHIN the same parent category.
//
// NO forced scroll on click — CSS position:sticky handles pinning
// the header to the top of the screen naturally as the user scrolls.
// Forcing a scroll when clicking caused the header to jump away from
// its natural position in the list.
document.addEventListener('toggle', function (e) {
const details = e.target;
if (!details || details.tagName !== 'DETAILS' || !details.open) return;
if (details.classList.contains('category-details')) {
// Close all OTHER category accordions
document.querySelectorAll('.category-details').forEach(d => {
if (d !== details && d.open) d.open = false;
});
} else if (details.classList.contains('product-group-details')) {
// Close all OTHER product groups inside the same category
const parentCat = details.closest('.category-details');
if (parentCat) {
parentCat.querySelectorAll('.product-group-details').forEach(d => {
if (d !== details && d.open) d.open = false;
});
}
}
}, true); // capture phase — fires before child toggle events bubble
}
// --- FLEX RENDER FUNCTIONS ---
// --- DETAILS BUBBLE LOGIC ---
// --- DETAILS BUBBLE LOGIC ---
function showDetails(event, name, desc, img, salePrice, regPrice) {
if (event) event.stopPropagation();
const overlay = document.getElementById('bubble-overlay');
const bubble = document.getElementById('details-bubble');
const titleEl = document.getElementById('bubble-title');
const descEl = document.getElementById('bubble-desc');
const imgContainer = document.getElementById('bubble-img-container');
titleEl.textContent = name;
// Price Logic in Bubble
let priceHtml = "";
const sPrice = Number(salePrice);
const rPrice = Number(regPrice);
if (sPrice > 0) {
priceHtml = `<div style="margin-bottom:8px;">
<span style="text-decoration:line-through; color:#999; margin-right:8px;">$${rPrice.toFixed(2)}</span>
<span style="color:inherit; font-weight:900; font-size:1.1em;">$${sPrice.toFixed(2)}</span>
</div>`;
} else {
priceHtml = `<div style="margin-bottom:8px; font-weight:bold;">$${rPrice.toFixed(2)}</div>`;
}
descEl.innerHTML = priceHtml + (desc || "No description available.");
imgContainer.innerHTML = "";
if (img) {
const image = document.createElement('img');
image.src = img;
image.className = "details-img";
image.onerror = function () { this.style.display = 'none'; imgContainer.innerHTML = '<span style="color:#aaa">Image failed to load</span>'; };
imgContainer.appendChild(image);
imgContainer.style.display = 'flex';
} else {
imgContainer.style.display = 'none';
}
overlay.style.display = 'block';
bubble.style.display = 'block';
}
function closeDetails() {
document.getElementById('bubble-overlay').style.display = 'none';
document.getElementById('details-bubble').style.display = 'none';
}
// --- FLEX RENDER FUNCTIONS ---
function renderMatrixGroupFlex(title, products, colDefs, bgColor, txtColor) {
// rowLabels based on first appearance (Sheet Order)
const rowLabels = [...new Set(products.map(p => p.variation || "Standard"))];
// Default colors if missing
const headerBg = bgColor || "var(--md-sys-color-primary)";
const headerTx = txtColor || "var(--md-sys-color-on-primary)";
// Add 'matrix-scroll-view' class for CSS targeting
let html = `<div class="table-container matrix-scroll-view">`;
// 2. Data Rows
rowLabels.forEach(rowLabel => {
const rowProducts = products.filter(p => (p.variation || "Standard") === rowLabel);
const rowIsSale = rowProducts.some(p => p.onSale);
const rowAvailable = rowProducts.some(p => p.isAvailable);
// Matrix body row — flex-start so columns pack tight at declared widths,