Jake Vanderwerf
2026-01-01 3acb42faee66868a76e653a34ef35de13ddf734f
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
// FilterPanel.js - Handles UI for filtering feed content
import cache from '../utils/cache';
 
import { debounce } from '../utils/formatters';
class FilterPanel {
    constructor(container, options = {}) {
        this.container = container;
        this.options = {
            taxonomies: [],
            contentTypes: [],
            onChange: null,
            taxonomyFor: {},
            ...options
        };
 
        // Store references to key elements
        this.selected = {};
        this.selectedFiltersContainer = container.querySelector('.selected-items');
        this.matchAll = container.querySelector('.toggle-text');
        this.filterToggles = container.querySelectorAll('.filter-toggle');
        this.filtersContainer = container.querySelector('.filters');
        this.filterDropdowns = container.querySelectorAll('.filter-dropdown');
        this.clearFiltersButton = container.querySelector('.clear-filters');
        this.contentTypeInputs = container.querySelectorAll('input[name="content_type"]');
        this.orderInputs = container.querySelectorAll('input[name="order"]');
 
        // Local cache for terms
        this.termCache = {
            terms: new Map(),
            timestamp: Date.now()
        };
 
        // Initialize
        this.bindEvents();
    }
 
    /**
     * Initialize filter dropdowns
     */
    initSelectors() {
        this.selectors = this.container.querySelectorAll('.jvb-selector');
 
        this.selectorInstances = {};
        let type = this.getCurrentContentType();
        this.selectors.forEach(selector => {
 
            if(selector.dataset.for.includes(type)){
                const taxonomy = selector.dataset.taxonomy;
                const options = selector.querySelector('.selected-items');
 
                this.selectorInstances[taxonomy] = new TaxonomySelector(selector, {
                    multiple: true,
                    feed: true,
                    onSuccess: () => this.updateSelected(taxonomy)
                });
            }
 
        });
    }
 
    updateSelected(taxonomy){
        // selected = this.selectorInstances[taxonomy].selected;
        let selected = this.selectorInstances[taxonomy].selectedItems;
 
    }
    /**
     * New method to bind content type events
     */
    bindContentTypeEvents() {
        const contentTypeInputs = this.container.querySelectorAll('input[name="content_type"]');
 
        contentTypeInputs.forEach(input => {
            // Remove existing event listeners to prevent duplicates
            input.removeEventListener('change', this._handleContentTypeChange);
 
            // Store event handler as property so we can remove it later
            this._handleContentTypeChange = (e) => {
                if (input.checked) {
                    const contentType = input.value;
 
                    // First, directly update taxonomy and order filters UI
                    this.updateTaxonomyFilters(contentType);
                    this.updateOrderFilters(contentType);
 
                    this.handleFormChange();
                }
            };
 
            // Add the event listener
            input.addEventListener('change', this._handleContentTypeChange);
        });
    }
 
    /**
     * Replace the existing bindEvents method in FilterPanel
     */
    bindEvents() {
        // Form change events
        this.container.addEventListener('submit', e => e.preventDefault());
        this.container.addEventListener('change', this.handleFormChanges.bind(this));
        this.container.addEventListener('click', this.handleToggleClick.bind(this));
 
        // Add global keydown listener for Escape key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeAllDropdowns();
            }
        });
 
        // Dialog close events
        this.filterDropdowns.forEach(dialog => {
            dialog.addEventListener('close', this.handleDialogClose.bind(this));
            dialog.addEventListener('click', (e) => {
                // Check if click was directly on the dialog element (backdrop)
                // and not on any of its children
                if (e.target === dialog) {
                    dialog.close();
                }
            });
            // Set up search inputs
            const search = dialog.querySelector('input[type="search"]');
            if (search) {
                search.addEventListener('input', debounce(e => {
                    const taxonomy = dialog.dataset.taxonomy;
                    const query = e.target.value;
                    const container = dialog.querySelector('.options-container');
                    this.handleSearch(taxonomy, query, container);
                }, 300));
            }
        });
 
        // Clear filters button
        if (this.clearFiltersButton) {
            this.clearFiltersButton.addEventListener('click', this.clearFilters.bind(this));
        }
    }
    /**
     * Handle form change events
     */
    handleFormChanges(e) {
        const target = e.target;
 
        // Skip changes in dialogs (handled separately)
        if (target.closest('dialog')) return;
 
        // Handle content type changes
        if (target.name === 'content_type' && target.checked) {
            const contentType = target.value;
            this.updateTaxonomyFilters(contentType);
            this.updateOrderFilters(contentType);
        }
 
        // Handle order type changes
        if (target.name === 'order') {
            this.handleOrderChange(target);
        }
 
        // For all changes, trigger form update
        this.handleFormChange();
    }
    handleToggleClick(e) {
        const toggle = e.target.closest('.filter-toggle');
        if (!toggle) return;
 
        e.preventDefault();
 
        const wasExpanded = toggle.getAttribute('aria-expanded') === 'true';
        this.closeAllDropdowns();
 
        const taxonomyFilter = toggle.closest('[data-taxonomy]');
        if (!taxonomyFilter) return;
 
        const taxonomy = taxonomyFilter.dataset.taxonomy;
        const dropdown = this.container.querySelector(
            `.filter-dropdown[data-taxonomy="${taxonomy}"]`
        );
 
        if (!dropdown) return;
 
        toggle.setAttribute('aria-expanded', !wasExpanded);
        dropdown.showModal();
 
        if (!wasExpanded) {
            const search = dropdown.querySelector('input[type="search"]');
            if (search) search.focus();
 
            const options = dropdown.querySelector('.options-container');
            if (options && options.children.length === 1) {
                this.loadTaxonomyOptions(taxonomy, options);
            }
        }
    }
 
    /**
     * Handle dialog close events
     */
    handleDialogClose(e) {
 
        const dialog = e.target;
        const taxonomy = dialog.dataset.taxonomy;
        const selected = this.selectorInstances[taxonomy].selectedItems;
        if (Object.keys(selected).length > 0) {
            this.updateFilters(taxonomy, selected);
        }
    }
 
    /**
     * Handle order type changes
     */
    handleOrderChange(target) {
        const orderDirection = this.container.querySelector('.order-direction');
 
        if (target.value === 'random') {
            orderDirection.hidden = true;
            // Reset direction to default
            this.container.querySelector('#order-desc').checked = true;
        } else if (target.value === 'title') {
            this.container.querySelector('#order-asc').checked = true;
            orderDirection.hidden = false;
        } else {
            orderDirection.hidden = false;
        }
    }
 
    /**
     * Handle search input in taxonomy dialogs
     */
    handleSearch(taxonomy, query, container) {
        if (!container) return;
 
        // Clear existing options
        container.innerHTML = '';
        container.setAttribute('data-loading', 'true');
 
        // Debounced search function
        if (this.searchDebounce) {
            clearTimeout(this.searchDebounce);
        }
 
        this.searchDebounce = setTimeout(async () => {
            try {
                // Get terms - either from cache or API
                let terms;
 
                if (query) {
                    // Create cache key for search
                    const cacheKey = `terms_${taxonomy}_search_${query}`;
                    terms = cache.get(cacheKey);
 
                    if (!terms) {
                        // For search, always fetch from API if not cached
                        const response = await fetch(
                            `${window.feedSettings.apiUrl}terms/${taxonomy}?search=${encodeURIComponent(query)}`,
                            {
                                headers: {
                                    'X-WP-Nonce': window.feedSettings.nonce
                                }
                            }
                        );
 
                        if (!response.ok) {
                            throw new Error('Failed to fetch terms');
                        }
 
                        const data = await response.json();
                        terms = data.terms;
 
                        // Cache search results for 5 minutes
                        cache.set(cacheKey, terms, 300000);
                    }
                } else if (this.termCache.terms.has(taxonomy)) {
                    // Use cached terms if available
                    terms = this.termCache.terms.get(taxonomy);
                } else {
                    // Fetch from API
                    const response = await fetch(
                        `${window.feedSettings.apiUrl}terms/${taxonomy}`,
                        {
                            headers: {
                                'X-WP-Nonce': window.feedSettings.nonce
                            }
                        }
                    );
 
                    if (!response.ok) {
                        throw new Error('Failed to fetch terms');
                    }
 
                    const data = await response.json();
                    terms = data.terms;
 
                    // Update cache
                    this.termCache.terms.set(taxonomy, terms);
                    this.termCache.timestamp = Date.now();
                }
 
                // Render terms
                this.renderTermOptions(container, terms);
 
            } catch (error) {
                console.error('Error fetching terms:', error);
                container.innerHTML = '<div class="error">Failed to load options</div>';
            } finally {
                container.removeAttribute('data-loading');
            }
        }, 300);
    }
 
    /**
     * Handle form change events
     */
    handleFormChange() {
        // Get current form data
        const formData = this.getFormData();
 
        // Update URL
        this.updateURL(formData);
 
        // Call change handler if available
        if (typeof this.options.onChange === 'function') {
            this.options.onChange(formData);
        }
    }
 
    /**
     * Get current form data
     */
    getFormData() {
        if (!this.container) return {};
 
        const formData = new FormData(this.container);
 
        // Get content type - explicitly check the checked radio button
        const contentTypeInput = this.container.querySelector('input[name="content_type"]:checked');
        const contentType = contentTypeInput ? contentTypeInput.value : this.options.defaultContent;
 
        const filters = {
            content: contentType,
            order: formData.get('order') || 'date',
            direction: formData.get('direction') || 'desc',
            match: formData.get('match') || 'any',
        };
 
 
        for (const [taxonomy, selector] of Object.entries(this.selectorInstances)) {
            if(Object.keys(selector.selectedItems).length > 0){
                filters[taxonomy] = Object.keys(selector.selectedItems);
            }
        }
 
 
        // Add favourites flag if present
        if (formData.get('favourites_only')) {
            filters.favouritesOnly = true;
        }
 
        return filters;
    }
 
    /**
     * Update taxonomy filters based on content type
     */
    updateTaxonomyFilters(contentType) {
        if (!contentType) {
            contentType = this.options.defaultContent || 'tattoo';
        }
        // Show/hide taxonomy filters based on content type
        const filters = this.container.querySelectorAll('.taxonomy-filter');
 
        filters.forEach(filter => {
            const applicableTypes = filter.dataset.for.split(',');
            const isVisible = applicableTypes.includes(contentType);
            filter.hidden = !isVisible;
 
            // Update content type for visible selectors
            if (isVisible) {
                const taxonomy = filter.dataset.taxonomy;
                if (this.taxonomySelectors && this.taxonomySelectors[taxonomy]) {
                    this.taxonomySelectors[taxonomy].setContentType(contentType);
                }
            }
        });
 
        // Remove selected filters for hidden taxonomies
        const hiddenFilters = this.container.querySelectorAll('.taxonomy-filter[hidden]');
        hiddenFilters.forEach(filter => {
            const taxonomy = filter.dataset.taxonomy;
            const selectedItems = this.selectedFiltersContainer.querySelectorAll(
                `.selected-item[data-taxonomy="${taxonomy}"]`
            );
 
            if (selectedItems.length > 0) {
                selectedItems.forEach(item => item.remove());
            }
        });
        this.initSelectors();
        // Update clear filters button visibility
        this.updateClearFiltersButton();
    }
 
    /**
     * Get current content type
     */
    getCurrentContentType() {
        const contentTypeInput = this.container.querySelector('input[name="content_type"]:checked');
        return contentTypeInput ? contentTypeInput.value : this.options.defaultContent;
    }
 
    /**
     * Update order filters based on content type
     */
    updateOrderFilters(contentType) {
        if (!contentType) return;
 
        const orderFilters = this.container.querySelectorAll('input[name="order"]');
 
        orderFilters.forEach(filter => {
            const applicableTypes = filter.dataset.for;
 
            if (applicableTypes) {
                const types = applicableTypes.split(',');
                filter.hidden = !types.includes(contentType);
 
                if (filter.hidden && filter.checked) {
                    // Reset to default
                    this.container.querySelector('input#order-date').checked = true;
                    this.container.querySelector('input[name="direction"][value="desc"]').checked = true;
                }
            }
        });
    }
 
    /**
     * Close all open dropdowns
     */
    closeAllDropdowns() {
        this.filterToggles.forEach(toggle => {
            toggle.setAttribute('aria-expanded', 'false');
        });
 
        this.filterDropdowns.forEach(dialog => {
            if (dialog.open) {
                dialog.close();
            }
        });
    }
 
    /**
     * Update URL parameters based on filters
     */
    updateURL(filters) {
        const params = new URLSearchParams();
 
        // Add content type
        if (filters.content && filters.content !== 'all') {
            params.set('f_content', filters.content);
        }
 
        // Add order and direction
        if (filters.order) {
            params.set('f_order', filters.order);
            if (filters.direction) {
                params.set('f_direction', filters.direction);
            }
        }
 
        // Add taxonomy filters
 
        for (const [key, value] of Object.entries(filters)) {
            if (Array.isArray(value) && value.length > 0) {
                value.forEach(v => params.append('f_'+key, v));
            }
        }
 
        // Add favourites filter
        if (filters.favouritesOnly) {
            params.set('f_favourites', '1');
        }
        // if(filters.match){
        //  params.set('f_match', filters.match);
        // }
 
        // Update URL without reloading page
        const newUrl = `${window.location.pathname}${params.toString() ? '?' + params.toString() : ''}`;
        history.pushState({ filters }, '', newUrl);
    }
 
    /**
     * Update filters for a taxonomy
     */
    updateFilters(taxonomy, values) {
        this.selected[taxonomy] = Object.keys(values);
        // Remove existing selected items for this taxonomy
        const existingItems = this.selectedFiltersContainer.querySelectorAll(
            `.selected-item[data-taxonomy="${taxonomy}"]`
        );
        existingItems.forEach(item => item.remove());
 
        for (const [id, name] of Object.entries(values)) {
            const filterTag = this.createFilterTag(taxonomy, id, name);
            this.selectedFiltersContainer.appendChild(filterTag);
        }
 
        // Update clear filters button visibility
        this.updateClearFiltersButton();
 
        // Trigger form change
        this.handleFormChange();
    }
 
    /**
     * Create a filter tag element
     */
    createFilterTag(taxonomy, id, name) {
        const tag = document.createElement('span');
        tag.className = 'selected-item';
        tag.dataset.taxonomy = taxonomy;
        tag.dataset.id = id;
 
        const icon = feedSettings?.icons?.[taxonomy] || '';
 
        tag.innerHTML = `
            ${icon}
            <span class="filter-name">${this.escapeHtml(name)}</span>
            <button type="button" aria-label="Remove ${name}" class="remove-item">
                ${window.feedSettings?.icons?.close || '×'}
            </button>
        `;
 
        // Add click handler for remove button
        tag.querySelector('.remove-item').addEventListener('click', () => {
            // Uncheck checkbox if it exists
            let taxonomy = tag.dataset.taxonomy;
            delete this.selectorInstances[taxonomy].selectedItems[id];
 
            // Remove tag
            tag.remove();
 
            // Update clear filters button visibility
            this.updateClearFiltersButton();
 
            // Trigger form change
            this.handleFormChange();
        });
 
        return tag;
    }
 
    /**
     * Update clear filters button visibility
     */
    updateClearFiltersButton() {
        if (!this.clearFiltersButton) return;
 
        let filters = this.selectedFiltersContainer.children.length;
 
        const hasFilters = filters > 0;
 
        const hasMultiple = filters > 1;
 
        this.clearFiltersButton.hidden = !hasFilters;
 
        this.filtersContainer.classList.toggle('has-filters', hasFilters);
 
        this.matchAll.hidden = !hasMultiple;
    }
 
    /**
     * Clear all filters
     */
    clearFilters() {
        // Reset form
        if (this.container) {
            this.container.reset();
        }
 
        // Clear selected items
        if (this.selectedFiltersContainer) {
            this.selectedFiltersContainer.innerHTML = '';
        }
 
        // Uncheck all checkboxes in dropdowns
        this.filterDropdowns.forEach(dialog => {
            dialog.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = false;
            });
        });
 
        // Update clear filters button visibility
        this.updateClearFiltersButton();
 
        // Trigger form change
        this.handleFormChange();
    }
 
    /**
     * Load taxonomy options
     */
    async loadTaxonomyOptions(taxonomy, container, page = 1) {
        if (!container) return;
 
        container.setAttribute('data-loading', 'true');
 
        try {
            // Check cache first (if first page and no search)
            if (page === 1 && this.termCache.terms.has(taxonomy)) {
                this.renderTermOptions(container, this.termCache.terms.get(taxonomy));
                return;
            }
 
            // Create cache key
            const cacheKey = `terms_${taxonomy}_page_${page}`;
            let terms = cache.get(cacheKey);
 
            if (!terms) {
                // Fetch from API
                const response = await fetch(
                    `${window.feedSettings.apiUrl}terms/${taxonomy}?page=${page}`,
                    {
                        headers: {
                            'X-WP-Nonce': window.feedSettings.nonce
                        }
                    }
                );
 
                if (!response.ok) {
                    throw new Error('Failed to fetch terms');
                }
 
                const data = await response.json();
                terms = data.terms;
 
                // Cache for 5 minutes
                cache.set(cacheKey, terms, 300000);
 
                // Update local cache if first page
                if (page === 1) {
                    this.termCache.terms.set(taxonomy, terms);
                    this.termCache.timestamp = Date.now();
                }
            }
 
            // Render terms
            this.renderTermOptions(container, terms, page > 1);
 
        } catch (error) {
            console.error('Error fetching terms:', error);
            if (container.children.length === 0) {
                container.innerHTML = '<div class="error">Failed to load options</div>';
            }
        } finally {
            container.removeAttribute('data-loading');
        }
    }
 
    /**
     * Render term options in a dropdown
     */
    renderTermOptions(container, terms = [], append = false) {
        if (!container) return;
 
        const termsArray = Array.isArray(terms) ? terms : Object.values(terms);
 
        // Get the relevant taxonomy
        const taxonomy = container.closest('.filter-dropdown')?.dataset.taxonomy;
        if (!taxonomy) return;
 
        // Get selected values
        const selectedValues = this.getSelectedValues(taxonomy);
 
        // Create HTML
        const html = termsArray.map(term => {
            const isChecked = selectedValues.includes(term.id.toString());
            const displayName = term.display_name || term.name;
            const inputId = `${taxonomy}-${term.id}`;
 
            return `
                <input type="checkbox"
                    id="${inputId}"
                    name="${taxonomy}"
                    value="${term.id}"
                    data-umami-event="toggle_taxonomy"
                    data-umami-taxonomy="${taxonomy}"
                    data-umami-term="${term.name}"
                    data-umami-term-id="${term.id}"
                    data-umami-action="${isChecked ? 'remove' : 'add'}"
                    ${isChecked ? 'checked' : ''}>
                <label for="${inputId}" class="filter-option">
                    <span>${this.escapeHtml(displayName)}</span>
                    ${term.count ? `<span class="count">(${term.count})</span>` : ''}
                </label>
            `;
        }).join('');
 
        // Insert HTML
        if (append) {
            container.insertAdjacentHTML('beforeend', html);
        } else {
            container.innerHTML = html;
        }
    }
 
    /**
     * Get selected values for a taxonomy
     */
    getSelectedValues(taxonomy) {
        const selectedItems = this.selectedFiltersContainer.querySelectorAll(
            `.selected-item[data-taxonomy="${taxonomy}"]`
        );
 
        return Array.from(selectedItems).map(item => item.dataset.id);
    }
 
    /**
     * Get term details from cache
     */
    getTermDetails(taxonomy, id) {
        if (!this.termCache.terms.has(taxonomy)) return null;
 
        const terms = this.termCache.terms.get(taxonomy);
        return terms[id] || null;
    }
 
    /**
     * Load form state from URL parameters
     */
    loadFromURL() {
        const params = new URLSearchParams(window.location.search);
 
        // Reset form state
        if (this.container) {
            this.container.reset();
        }
 
        // Clear selected filters
        if (this.selectedFiltersContainer) {
            this.selectedFiltersContainer.innerHTML = '';
        }
 
        // Set content type
        const contentType = params.get('f_content');
        if (contentType) {
            const contentTypeInput = this.container.querySelector(
                `input[name="content_type"][value="${contentType}"]`
            );
            if (contentTypeInput) {
                contentTypeInput.checked = true;
                // Update visible taxonomies based on content type
                this.updateTaxonomyFilters(contentType);
            }
        }
 
        // Set order and direction
        const order = params.get('f_order');
        if (order) {
            const orderInput = this.container.querySelector(`input[name="order"][value="${order}"]`);
            if (orderInput) {
                orderInput.checked = true;
                this.updateOrderFilters(contentType || this.options.defaultContent);
            }
        }
 
        const direction = params.get('f_direction');
        if (direction) {
            const directionInput = this.container.querySelector(`input[name="direction"][value="${direction}"]`);
            if (directionInput) {
                directionInput.checked = true;
            }
        }
 
        // Set favourites filter
        if (params.get('f_favourites') === '1') {
            const favouritesCheckbox = this.container.querySelector('input[name="favourites_only"]');
            if (favouritesCheckbox) {
                favouritesCheckbox.checked = true;
            }
        }
 
        // Find and set taxonomy filters
        const taxonomyPromises = {};
 
        // Process all potential taxonomy parameters
        for (const [key, value] of params.entries()) {
            if (key.startsWith('f_') && key !== 'f_content' &&
                key !== 'f_order' && key !== 'f_direction' &&
                key !== 'f_favourites' && key !== 'f_match') {
 
                const taxName = key.replace('f_', '');
                const termId = value;
 
                // Create a promise to fetch term details and create a filter tag
                if(!Object.hasOwnProperty(taxName)){
                    taxonomyPromises[taxName] = [];
                }
                taxonomyPromises[taxName].push(termId);
            }
        }
        //Check all terms at once
        this.fetchTermDetails(taxonomyPromises).then(()=>{
            this.updateClearFiltersButton();
        });
    }
 
    async fetchTermDetails(terms) {
        for(const [taxonomy, termIds] of Object.entries(terms)){
 
            termIds.forEach(termId => {
                if(this.termCache.terms.has(taxonomy) && this.termCache.terms.get(taxonomy)[termId]){
                    //add to Selected from cache.
 
                    let name = this.termCache.terms.get(taxonomy)[termId].name;
                    const filterTag = this.createFilterTag(taxonomy, termId, name);
                    this.selectedFiltersContainer.appendChild(filterTag);
                    //remove any terms we already have
                    terms[taxonomy] = terms[taxonomy].filter(function(item) {
                        return item !== termId;
                    });
                }
            });
        }
        let params = new URLSearchParams(terms);
 
        // Otherwise fetch the term details
        try {
            // Format the URL - might need to adjust based on your API structure
            const url = `${window.feedSettings?.apiUrl}terms/check?`+params.toString();
 
            const response = await fetch(url, {
                headers: {
                    'X-WP-Nonce': window.feedSettings?.nonce || ''
                }
            });
 
            if (!response.ok) {
                throw new Error('Failed to fetch term details');
            }
 
            const termData = await response.json();
 
            for(const [taxonomy, termIds] of Object.entries(termData.terms)){
                if(!this.termCache.terms.has(taxonomy)){
                    this.termCache.terms.set(taxonomy, new Map());
                }
 
                for(const [termId, termData] of Object.entries(termIds)){
                    const filterTag = this.createFilterTag(taxonomy, termId, termData.name);
                    this.selectedFiltersContainer.appendChild(filterTag);
 
                    this.termCache.terms.get(taxonomy).set(parseInt(termId), termData);
                }
 
            }
 
 
            return true;
        } catch (error) {
            console.error(`Error fetching term details for ${taxonomy}/${termId}:`, error);
            return null;
        }
    }
    /**
     * Safe HTML escaping
     */
    escapeHtml(text) {
        if (!text) return '';
 
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
 
    /**
     * Set up focus traps for modals
     */
    setupFocusTraps() {
        this.filterDropdowns.forEach(dialog => {
            dialog.addEventListener('show', () => {
                // Store current focus to restore later
                this._previouslyFocused = document.activeElement;
 
                // Focus first focusable element
                const focusable = dialog.querySelectorAll(
                    'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
                );
                if (focusable.length) {
                    focusable[0].focus();
                }
 
                // Trap focus in modal
                this.trapFocus(dialog);
            });
 
            dialog.addEventListener('close', () => {
                // Restore focus
                if (this._previouslyFocused) {
                    this._previouslyFocused.focus();
                }
            });
        });
    }
 
    /**
     * Trap focus within an element
     */
    trapFocus(element) {
        const focusableElements = element.querySelectorAll(
            'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
        );
        if (!focusableElements.length) return;
 
        const firstFocusable = focusableElements[0];
        const lastFocusable = focusableElements[focusableElements.length - 1];
 
        const trapHandler = function(e) {
            if (e.key !== 'Tab') return;
 
            if (e.shiftKey && document.activeElement === firstFocusable) {
                lastFocusable.focus();
                e.preventDefault();
            } else if (!e.shiftKey && document.activeElement === lastFocusable) {
                firstFocusable.focus();
                e.preventDefault();
            }
        };
 
        // Store the handler to remove it later
        element._trapHandler = trapHandler;
        element.addEventListener('keydown', trapHandler);
    }
}
 
export default FilterPanel;