Jake Vanderwerf
2026-01-05 9f86429a1252b45c95b7c62fbaa1b82de3723997
assets/js/concise/TaxonomySelector.js
@@ -1,1201 +1,992 @@
/**
 * Centralized Taxonomy Selector with DataStore Integration
 * Handles all taxonomy selection fields using DataStore for state management
 */
class TaxonomySelector {
   constructor() {
      this.container = document.querySelector('dialog#jvb-selector');
      if (!this.container) return;
      this.a11y = window.jvbA11y;
      this.error = window.jvbError;
      this.index = -1;
      this.store = new window.jvbStore({
         name: `taxonomies`,
         storeName: `terms`,
         keyPath: 'id',
         indexes: [
            {name: 'taxonomy', keyPath: 'taxonomy'},
            {name: 'parent', keyPath: 'parent'},
            {name: 'slug', keyPath: 'slug', unique: true},
            {name: 'count', keyPath: 'count'},
         ],
         endpoint: 'terms',
         TTL: 7200000, //2 hours
         filters: {
            taxonomy: '',
            page: 1,
            search: '',
            parent: 0
         }
      });
      // Central field management
      this.subscribers = new Set();
      this.fields = new Map();
      this.selectedTerms = new Map();    // Current modal selection
      this.selectedTerms = new Map();  // a map of fieldId => Set of selected term Ids
      this.loadedTaxonomies = new Set(); // a set of taxonomies, to know whether we should preload a newly registered field
      this.batchFetch = new Set();
      // Current modal context
      this.activeField = null;
      this.currentConfig = null;
      this.currentSingular = null;
      this.currentPlural = null;
      this.activeStore = null;
      // Modal state
      this.disabled = false;
      // Search debouncing
      this.searchHandler = null;
      this.isInitializing = true;
      this.init();
   }
   /**
    * Initialize the selector
    */
   init() {
      this.initStore();
      this.initElements();
      this.initModal();
      this.scanExistingFields();
      this.initGlobalListeners();
      this.initListeners();
      if (this.needsCreator() && window.jvbTaxCreator) {
         this.creator = new window.jvbTaxCreator(this);
      }
      this.isInitializing = false
      this.batchFetchTaxonomies().then(()=> {});
   }
   initStore() {
      const store = window.jvbStore.register(
         'taxonomies',
         {
            storeName: 'terms',
            keyPath: 'id',
            showLoading: false,
            indexes: [
               {name: 'taxonomy', keyPath: 'taxonomy'},
               {name: 'parent', keyPath: 'parent'},
               {name: 'slug', keyPath: 'slug', unique: true},
               {name: 'count', keyPath: 'count'},
            ],
            endpoint: 'terms',
            TTL: 2 * 60 * 1000,
            filters: {
               taxonomy: '',
               page: 1,
               search: '',
               parent: 0
            },
            required: 'taxonomy',
            delayFetch: true,
         }
      );
      this.store = store.terms;
      this.store.subscribe(this.handleStoreEvent.bind(this));
   }
   /**
    * Handle DataStore events
    */
   handleStoreEvent(taxonomy, event, data) {
      // Only process events for the active taxonomy in modal
      if (this.activeStore && this.activeStore.config.name === `tax_${taxonomy}`) {
         switch (event) {
            case 'items-loaded':
            case 'data-fetched':
            case 'data-cached':
            case 'stale-cache-used':
               this.handleTermsLoaded(data);
               break;
            case 'fetch-error':
               this.handleFetchError(data.error);
               break;
            case 'filters-changed':
               // Could trigger UI updates for active filters
               break;
         }
      }
      // Handle field-specific updates outside modal
      if (event === 'items-updated' || event === 'items-loaded') {
         this.updateFieldsForTaxonomy(taxonomy, data.items);
      }
   }
   /**
    * Handle loaded terms from DataStore
    */
   handleTermsLoaded(data) {
      this.hideLoading();
      const terms = data.data?.items || [];
      const pagination = data.data?.pagination || {};
      const isSearch = data.filters?.search && data.filters.search.length > 0;
      const append = data.filters?.page > 1;
      if (terms.length === 0) {
         if (!append) {
            this.showEmptyState(isSearch ? 'No results found.' : 'No items available.');
         }
         this.observer.unobserve(this.ui.sentinel);
      } else {
         this.renderTerms(terms, append, isSearch);
         this.currentTerms = terms;
         // Handle pagination
         if (pagination.has_more) {
            this.observer.observe(this.ui.sentinel);
         } else {
            this.observer.unobserve(this.ui.sentinel);
         }
      }
      // Announce to screen readers
      this.a11y?.announce(terms.length, append);
   }
   /**
    * Handle fetch errors
    */
   handleFetchError(error) {
      console.error('Taxonomy fetch error:', error);
      this.hideLoading();
      if (this.error?.log) {
         this.error.log(error, {
            component: 'TaxonomySelector',
            action: 'fetchTerms'
         }, () => this.fetchCurrentTerms());
      } else {
         this.showEmptyState('Error loading terms. Please try again.');
      }
   }
   /**
    * Update fields when taxonomy items are updated
    */
   updateFieldsForTaxonomy(taxonomy, items) {
      this.fields.forEach(field => {
         if (field.taxonomy === taxonomy && field.selectedTerms.size > 0) {
            // Update display with fresh term data
            field.selectedTerms.forEach(termId => {
               const term = items.find(item => item.id === termId);
               if (term) {
                  const selectedItem = field.selectedContainer.querySelector(`[data-id="${termId}"]`);
                  if (selectedItem) {
                     selectedItem.dataset.path = term.path;
                     selectedItem.querySelector('span').textContent = term.path;
                  }
               }
            });
         }
      });
   }
   /**
    * Scan page for existing taxonomy fields and register them
    */
   scanExistingFields() {
      const selectors = document.querySelectorAll('.field.taxonomy, .field.post');
      selectors.forEach(selector => {
         try {
            this.registerField(selector);
         } catch (error) {
            this.error.log(error, {
               component: 'TaxonomySelector',
               action: 'scanExistingFields',
               container: selector.dataset.name
            });
         }
      });
   }
   /**
    * Register a taxonomy field
    */
   registerField(field, options = {}) {
      let input = field.querySelector('input[type=hidden]');
      if (!input) {
         return;
      }
      if (!('fieldId' in field.dataset)) {
         field.dataset.fieldId = this.createFieldId(field);
      }
      let fieldId = field.dataset.fieldId;
      let button = field.querySelector('button.taxonomy-toggle');
      let config = {
         id: fieldId,
         input: input,
         container: field,
         taxonomy: button.dataset.taxonomy,
         name: field.dataset.field,
         maxSelection: parseInt(button.dataset.max) || 0,
         canSearch: 'search' in button.dataset,
         canCreate: 'creatable' in button.dataset,
         isRequired: 'required' in button.dataset,
         selectedTerms: new Set(),
         toggle: button,
         selectedContainer: field.querySelector('.selected-items'),
         ...options
      };
      // Parse initial selected values
      const value = input.value.trim();
      if (value !== '') {
         const selectedIds = value.split(',')
            .map(id => parseInt(id.trim()))
            .filter(id => !isNaN(id));
         selectedIds.forEach(id => config.selectedTerms.add(id));
      }
      this.fields.set(fieldId, config);
      // Ensure store exists for this taxonomy
      this.store.setFilter('taxonomy', config.taxonomy);
      // Initialize display for any pre-selected values
      if (config.selectedTerms.size > 0) {
         this.initFieldDisplay(fieldId);
      }
      return fieldId;
   }
   /**
    * Create unique field ID
    */
   createFieldId(field) {
      this.index++;
      return 'selector-' + this.index;
   }
   /**
    * Initialize display for a field with existing values
    */
   async initFieldDisplay(fieldId) {
      const field = this.fields.get(fieldId);
      if (!field || field.selectedTerms.size === 0) return;
      const selectedIds = Array.from(field.selectedTerms);
      // Check store for cached terms first
      const cachedTerms = [];
      const needsFetch = [];
      selectedIds.forEach(termId => {
         const term = this.store.getItem(termId);
         if (term) {
            cachedTerms.push(term);
         } else {
            needsFetch.push(termId);
         }
      });
      // Display cached terms immediately
      cachedTerms.forEach(term => {
         this.addTermToDisplay(fieldId, term.id, term.name, term.path);
      });
      // Fetch missing terms if needed
      if (needsFetch.length > 0) {
         try {
            const response = await this.store.fetch({
               filters: {
                  taxonomy: field.taxonomy,
                  termIDs: needsFetch.join(',')
               }
            });
            if (response.terms) {
               response.terms.forEach(term => {
                  this.store.setItem(term.id, term);
                  this.addTermToDisplay(fieldId, term.id, term.name, term.path);
               });
            }
         } catch (error) {
            console.error('Failed to fetch missing terms:', error);
         }
      }
   }
   /**
    * Initialize modal elements
    */
   initModal() {
      this.modalID = 'dialog#jvb-selector';
      this.modal = document.querySelector(this.modalID);
      if (!this.modal) {
         console.warn('Taxonomy selector modal not found');
         return;
      }
      this.initModalElements();
      // Initialize modal instance
      this.modalInstance = new window.jvbModal(this.modal, {
         handleForm: false,
         save: null,
         open: null
      });
      this.modalInstance.subscribe((event, data) => {
         switch (event) {
            case 'modal-open':
               console.log(data);
               this.openModal(data);
               break;
            case 'modal-close':
               this.closeModal(data);
               break;
         }
      });
   }
   /**
    * Initialize modal element references
    */
   initModalElements() {
   /******************************************************************
    ELEMENTS
    ******************************************************************/
   initElements() {
      this.selectors = {
         search: {
            input: '[type=search]',
            clear: '.clear-search',
            container: '.search-wrapper'
            container: '.search-wrapper',
            results: '.search-results'
         },
         termsList:  '.items-container',
         termsWrap:  '.items-wrap',
         breadcrumbs: {
         terms: {
            list: '.items-container',
            wrap: '.items-wrap',
            sentinel: '.scroll-sentinel',
         },
         nav: {
            nav: 'nav.term-navigation',
            back: '.back-to-parent',
            child: '.toggle-children',
            pathLevel: '.path-level',
         },
         loading: {
            loading: '.loading',
            text: '.loading span'
            text: '.loading span',
         },
         selectedTerms: '.selected-items',
         sentinel: '.scroll-sentinel',
         selected: '.selected-items',
         modal: {
            title: '#modal-title',
            content: '.modal-content'
            content: '.modal-content',
            count: '.selection-count'
         },
         create: {
            details: '.create-new-term',
            parent: '#select_parent',
            summary: '.create-new-term summary',
            name: '#term_name',
            button: '.submit-term',
            label: {
               name: '[for=term_name]',
               parent: '[for=select_parent]'
            }
         },
         favouriteTerms: '.favourite-terms'
         favourites: '.favourite-terms',
         field: {
            toggle: 'button.taxonomy-toggle',
            value: 'input[type="hidden"]',
            selected: '.selected-items',
            dropdown: '.search-results',
            search: '[data-autocomplete]',
         }
      }
      this.ui = window.uiFromSelectors(this.selectors);
   }
      // Initialize intersection observer for infinite scroll
   initListeners() {
      this.observer = new IntersectionObserver((entries) => {
         entries.forEach(entry => {
            if (entry.isIntersecting && this.activeStore) {
               this.loadMoreTerms();
            if (entry.isIntersecting) {
               this.nextPage();
            }
         });
      }, {
         root: this.ui.termsWrap,
         root: this.ui.terms.sentinel,
         threshold: 0.5
      });
      this.clickHandler = this.handleClick.bind(this);
      this.changeHandler = this.handleChange.bind(this);
      this.inputHandler = this.handleInput.bind(this);
      this.focusHandler = this.handleFocus.bind(this);
      this.blurHandler = this.handleBlur.bind(this);
      document.addEventListener('click', this.clickHandler);
      document.addEventListener('change', this.changeHandler);
      document.addEventListener('input', this.inputHandler);
      document.addEventListener('focus', this.focusHandler, true);
      document.addEventListener('blur', this.blurHandler, true);
   }
   /**
    * Set up global event delegation
    */
   initGlobalListeners() {
      document.addEventListener('click', this.handleClick.bind(this));
      document.addEventListener('change', this.handleChange.bind(this));
   }
   /**
    * Handle global click events
    */
   handleClick(e) {
      // Handle taxonomy toggle buttons
      const toggleButton = window.targetCheck(e, '.taxonomy-toggle');
      const fieldId = this.getFieldId(e.target);
      const field = this.fields.get(fieldId);
      if (!fieldId || !field) return;
      const autoComplete = window.targetCheck(e, '[data-autocomplete-select]');
      if (autoComplete) {
         let termId = parseInt(autoComplete.dataset.id);
         this.addSelected(termId, fieldId);
         if (field.ui.dropdown) {
            field.ui.dropdown.hidden = true;
         }
         if (field.ui.search) {
            field.ui.search.value = '';
         }
      }
      const toggleButton = window.targetCheck(e, field.ui.toggle);
      if (toggleButton) {
         e.preventDefault();
         this.handleToggleClick(toggleButton);
         this.openModal(fieldId);
         return;
      }
      // Handle remove selected term buttons
      const removeButton = window.targetCheck(e, 'button.remove-item');
      if (removeButton && e.target.closest('.jvb-selector')) {
      if (removeButton) {
         const fieldId = this.getFieldId(removeButton);
         const termId = removeButton.closest('.selected-item').dataset.id;
         this.removeSelectedTerm(fieldId, termId);
         const termId = removeButton.closest('.selected-item').dataset.id??false;
         if (fieldId && termId) {
            this.removeSelected(termId, fieldId);
         }
         return;
      }
      // Handle modal close button
      if (e.target.matches('.modal-close')) {
         if (this.modalInstance) {
            this.modalInstance.handleClose();
         this.modal?.handleClose();
         return;
      }
      const backToParent = window.targetCheck(e, this.selectors.nav.back);
      if (backToParent) {
         this.navigateToParent();
         return;
      }
      const toChild = window.targetCheck(e, this.selectors.nav.child);
      if (toChild) {
         const termItem = e.target.closest('li');
         const termId = parseInt(termItem.dataset.id);
         if (termId) {
            this.navigateTo(termId);
         }
         return;
      }
      // Handle clicks within the modal
      if (this.modal && this.modal.contains(e.target)) {
         this.handleModalClick(e);
      const pathLevel = window.targetCheck(e, this.selectors.nav.pathLevel);
      if (pathLevel) {
         const termId = parseInt(pathLevel.dataset.id)??0;
         this.navigateTo(termId);
      }
   }
   /**
    * Handle global change events
    */
   handleChange(e) {
      // Handle hidden input changes for taxonomy fields
      const taxonomyField = window.targetCheck(e, '.taxonomy.field, .post.field');
      if (taxonomyField && e.target.type === 'hidden') {
         const fieldId = this.getFieldId(e.target);
         this.updateFieldFromInput(fieldId);
      const dropdown = window.targetCheck(e, field.selectors.dropdown);
      if (dropdown) {
         // reset the timer for hiding the dropdown
         this.scheduleHideDropdown(fieldId);
         return;
      }
      // Handle modal changes
      if (this.modal && this.modal.contains(e.target)) {
         this.handleModalChange(e);
      }
   }
   /**
    * Handle toggle button click
    */
   handleToggleClick(toggle) {
      try {
         const fieldId = this.getFieldId(toggle);
         const field = this.fields.get(fieldId);
         if (!field) {
            console.error('Field not found for toggle:', fieldId);
            return;
         }
         this.setActiveField(fieldId);
         this.modalInstance.handleOpen();
      } catch (error) {
         console.error('Error handling toggle click:', error);
         this.error?.handleError(error, {
            component: 'TaxonomySelector',
            action: 'handleToggleClick'
         });
      }
   }
   /**
    * Set the active field for modal operations
    */
   setActiveField(fieldId) {
      this.activeField = fieldId;
      this.currentConfig = this.fields.get(fieldId);
      console.log('Current Taxonomy:',this.currentConfig.taxonomy);
      console.log('Labels: ',jvbSettings.labels[this.currentConfig.taxonomy]);
      this.currentSingular = jvbSettings.labels[this.currentConfig.taxonomy].single;
      this.currentPlural = jvbSettings.labels[this.currentConfig.taxonomy].plural;
      // Get or create store for this taxonomy
      this.store.setFilter('taxonomy', this.currentConfig.taxonomy);
      // Clear modal selection state
      this.selectedTerms.clear();
      // Copy field's current selections to modal state
      if (this.currentConfig.selectedTerms) {
         let termsToFetch = [];
         this.currentConfig.selectedTerms.forEach(termId => {
            const term = this.store.getItem(termId);
            if (term) {
               this.selectedTerms.set(termId, {
                  id: termId,
                  name: term.name,
                  path: term.path
               });
            } else {
               termsToFetch.push(termId);
            }
         });
         if (termsToFetch.length > 0) {
            let terms = this.fetchSpecificTerms(termsToFetch);
            terms.forEach(term => {
               this.selectedTerms.set(term.id, {
                  id: term.id,
                  name: term.name,
                  path: term.path
               });
      const clearSearch = window.targetCheck(e, this.selectors.search.clear);
      if (clearSearch) {
         const field = this.currentField();
         if (field && field.ui.search) {
            field.ui.search.value = '';
            this.store.setFilters({
               search: '',
               page: 1,
               parent: this.store.filters.parent || 0
            });
         }
      }
   }
   fetchSpecificTerms(terms) {
      return [];
   }
   /**
    * Handle clicks within modal
    */
   handleModalClick(e) {
      if (window.targetCheck(e, '.remove-item')) {
         let selectedItem = window.targetCheck(e, '.selected-item');
         if (selectedItem) {
            this.removeSelectedTermFromModal(selectedItem.dataset.id);
         }
      } else if (window.targetCheck(e, '.back-to-parent')) {
         this.navigateToParent();
      } else if (window.targetCheck(e, '.toggle-children')) {
         let termItem = e.target.closest('li');
         this.navigateToChild(
            parseInt(termItem.dataset.id),
            termItem.querySelector('.term-name').textContent
         );
      } else if (window.targetCheck(e, '.path-level')) {
         let pathLevel = window.targetCheck(e, '.path-level');
         this.navigateToPath(pathLevel);
      }
   }
   /**
    * Handle changes within modal (checkboxes)
    */
   handleModalChange(e) {
      if (window.targetCheck(e, this.modalID) && e.target.type === 'checkbox') {
         e.preventDefault();
         e.stopPropagation();
         const termId = parseInt(e.target.closest('li').dataset.id);
         const label = e.target.closest('li').querySelector('label');
         if (e.target.checked) {
            this.addSelectedTermToModal(termId, label.title, label.dataset.path);
         } else {
            this.removeSelectedTermFromModal(termId);
         if (this.ui.search.input) {
            this.ui.search.input.value = '';
         }
      }
   }
   /**
    * Open modal for filtering (without a field)
    * @param {string} taxonomy - The taxonomy to filter by
    * @param {Function} callback - Callback when terms are selected
    * @param {Array} preselected - Array of term IDs already selected
    */
   openForFilter(taxonomy, callback, preselected = []) {
      // Create a temporary virtual field config
      const virtualFieldId = `filter-${taxonomy}-${Date.now()}`;
      this.fields.set(virtualFieldId, {
         id: virtualFieldId,
         input: null, // No input for filter mode
         container: null,
         taxonomy: taxonomy,
         name: `filter_${taxonomy}`,
         maxSelection: 0, // No limit for filters
         canSearch: true,
         canCreate: false, // Disable creation for filters
         isRequired: false,
         selectedTerms: new Set(preselected),
         toggle: null,
         selectedContainer: null,
         isFilterMode: true, // Flag for filter mode
         filterCallback: callback // Store the callback
      });
      this.setActiveField(virtualFieldId);
      this.modalInstance.handleOpen();
   }
   /**
    * Open modal and initialize
    */
   openModal() {
      if (!this.activeField || !this.currentConfig) {
         console.error('No active field set for modal');
   handleChange(e) {
      if (!this.container.contains(e.target)) {
         return;
      }
      if (e.target.type !== 'checkbox') return;
      e.preventDefault();
      e.stopPropagation();
      this.resetModalState();
      this.updateModalForTaxonomy();
      const termId = parseInt(e.target.dataset.id);
      let fieldId = this.getFieldId(e.target);
      if (e.target.checked) {
         this.addSelected(termId, fieldId);
      } else {
         this.removeSelected(termId, fieldId);
      }
   }
   //For search in modal or field autocomplete
   handleInput(e) {
      let fieldId = this.getFieldId(e.target)??this.activeField;
      if (!fieldId) return;
      const field = this.fields.get(fieldId);
      if (!field) return;
      // Reset store filters to default state
      this.activeStore.clearFilters();
      // Set up search if enabled
      if (this.currentConfig.canSearch) {
         this.ui.search.input.focus();
         this.searchHandler = window.debounce(() => this.handleSearch(), 300);
         this.ui.search.input.addEventListener('input', this.searchHandler);
      if (!this.container.open) {
         this.activeField = fieldId;
      }
      // Initialize creator if available
      if (this.currentConfig.canCreate && 'jvbTaxCreator' in window) {
         this.creator = new window.jvbTaxCreator(this);
      }
      // Display current selections
      this.updateModalSelections();
      // Start observing for infinite scroll
      this.observer.observe(this.ui.sentinel);
      // Fetch initial terms
      this.fetchCurrentTerms();
      const query = e.target.value.trim();
      window.debouncer.schedule(
         `${fieldId}-search`,
         async () => {
            await this.store.setFilters({
               taxonomy: field.taxonomy,
               search: query,
               page: 1,
               parent: query ? 0 : (this.store.filters.parent || 0)
            });
            if (this.container.open) {
               window.removeChildren(this.ui.terms.list);
            }
         },
         100
      );
   }
   /**
    * Close modal and save selections
    */
   closeModal() {
      this.observer.unobserve(this.ui.sentinel);
      window.removeChildren(this.ui.termsList);
   handleFocus(e) {
      const fieldId = this.getFieldId(e.target);
      const field = this.fields.get(fieldId);
      if (!fieldId || !field) return;
      if (!field.hasAutocomplete && !field.hasSearch) return;
      if (this.currentConfig?.isFilterMode) {
         // Call the filter callback with selected terms
         if (this.currentConfig.filterCallback) {
            const selectedIds = Array.from(this.selectedTerms.keys());
            this.currentConfig.filterCallback(selectedIds, this.currentConfig.taxonomy);
      window.debouncer.cancel(`${fieldId}-search-results`);
      if (!this.container.open){
         this.activeField = fieldId;
         this.preloadTaxonomy(field.taxonomy);
      }
   }
   //Hide autocomplete dropdown on blur
   handleBlur(e) {
      const fieldId = this.getFieldId(e.target);
      const field = this.fields.get(fieldId);
      if (!fieldId || ! field) return;
      if (!field.hasAutocomplete) return;
      this.scheduleHideDropdown(fieldId);
   }
   scheduleHideDropdown(fieldId){
      const field = this.fields.get(fieldId);
      if (!field) return;
      window.debouncer.schedule(
         `${fieldId}-search-results`,
         () => {
            this.activeField = null;
            field.ui.dropdown.hidden = true;
         },
         1500
      );
   }
   /******************************************************************
    MODAL
    ******************************************************************/
   initModal() {
      this.modalID = 'dialog#jvb-selector';
      this.container = document.querySelector(this.modalID);
      this.modal = new window.jvbModal(
         this.container,
         {
            handleForm: false,
            save: null,
            open: null
         }
      );
      this.modal.subscribe((event, data) => {
         switch (event) {
         // Clean up the virtual field
         this.fields.delete(this.activeField);
      } else if (this.activeField) {
         this.saveSelectionsToField(this.activeField);
      }
      // Cleanup
      if (this.currentConfig?.canSearch && this.searchHandler) {
         this.ui.search.input.removeEventListener('input', this.searchHandler);
      }
      if (this.creator) {
         delete this.creator;
      }
      this.activeStore = null;
      this.activeField = null;
      this.currentConfig = null;
         }
      });
   }
   /**
    * Reset modal state
    */
   resetModalState() {
      this.disabled = false;
   toggleModal(fieldId, open = true) {
      const field = this.fields.get(fieldId);
      if (!field) return;
      window.removeChildren(this.ui.termsList);
      window.removeChildren(this.ui.selectedTerms);
      this.ui.search.input.value = '';
      // Clear navigation breadcrumbs
      window.removeChildren(this.ui.breadcrumbs.nav);
      this.ui.breadcrumbs.nav.appendChild(this.ui.breadcrumbs.back);
      this.ui.breadcrumbs.back.hidden = true;
      if (open) {
         this.openModal(fieldId);
      } else {
         this.closeModal();
      }
   }
   /**
    * Update modal content for current taxonomy
    */
   updateModalForTaxonomy() {
      if (!this.currentConfig) return;
   openModal(fieldId) {
      const field = this.fields.get(fieldId);
      if (!field) return;
      this.ui.modal.title.textContent = `Select ${this.currentPlural}`;
      this.activeField = fieldId;
      this.ui.modal.title.textContent = `Select ${field.plural}`;
      if (this.ui.search.container) {
         this.ui.search.container.style.display = this.currentConfig.canSearch ? 'block' : 'none';
         this.ui.search.container.hidden = !field.canSearch;
      }
      if (this.ui.create.details) {
         this.ui.create.details.style.display = this.currentConfig.canCreate ? 'block' : 'none';
         this.ui.create.details.hidden = !this.currentConfig.canCreate;
         this.ui.create.details.hidden = !field.canCreate;
         if (this.ui.create.summary) {
            this.ui.create.summary.textContent = `Add new ${this.currentSingular}`;
            this.ui.create.summary.textContent = `Add new ${field.singular}`;
         }
         if (this.ui.create.label.name) {
            this.ui.create.label.name.textContent = `Name this ${this.currentSingular}`;
            this.ui.create.label.name.textContent = `Name this ${field.singular}`;
         }
         if (this.ui.create.label.parent) {
            this.ui.create.label.parent.textContent = `Nest it under`;
         }
         if (this.ui.create.parent) {
         }
      }
      let message = `Opened ${field.singular} selection. Choose from checkboxes, or search to filter results.`;
      const openMessage = `Opened ${this.currentSingular} selection. Choose from checkboxes or search to filter results.`;
      this.a11y?.announce(openMessage);
   }
      window.removeChildren(this.ui.terms.list);
      this.modal.handleOpen();
      this.setLoading();
   /**
    * Update modal selections display
    */
   updateModalSelections() {
      window.removeChildren(this.ui.selectedTerms);
      this.selectedTerms.forEach((termData, id) => {
         this.addTermToModalDisplay(id, termData.name, termData.path);
      this.store.setFilters({
         taxonomy: field.taxonomy,
         page: 1,
         search: '',
         parent: 0,
      });
      this.checkSelectionLimits();
      this.a11y.announce(message);
   }
   /**
    * Add selected term to modal
    */
   addSelectedTermToModal(id, name, path) {
      this.selectedTerms.set(id, {
         id: id,
         name: name,
         path: path
   closeModal() {
      this.modal.handleClose();
      const field = this.fields.get(this.activeField);
      if (!field) return;
      this.observer.unobserve(this.ui.terms.sentinel);
      window.removeChildren(this.ui.terms.list);
      this.notify('selected-terms', {
         terms: this.selectedTerms.get(this.activeField),
         taxonomy: field.taxonomy
      });
      this.addTermToModalDisplay(id, name, path);
      this.checkSelectionLimits();
      this.activeField = null;
      // Check the corresponding checkbox
      const checkbox = this.ui.termsList.querySelector(`input[value="${id}"]`);
      if (checkbox) {
         checkbox.checked = true;
      }
      let message = `Closed ${field.singular} selector.`;
      this.a11y.announce(message);
   }
   /**
    * Remove selected term from modal
    */
   removeSelectedTermFromModal(id) {
      this.selectedTerms.delete(parseInt(id));
      // Remove from modal display
      const selectedItem = this.ui.selectedTerms.querySelector(`[data-id="${id}"]`);
      if (selectedItem) {
         selectedItem.remove();
      }
      // Uncheck the corresponding checkbox
      const checkbox = this.ui.termsList.querySelector(`input[value="${id}"]`);
      if (checkbox) {
         checkbox.checked = false;
      }
      this.checkSelectionLimits();
   navigateToParent() {
      const current = this.store.filters.parent;
      if (current === 0) return;
      let term = this.store.get(parseInt(current));
      if (!term) return;
      let parent = term.parent;
      this.navigateTo(parseInt(parent));
   }
   navigateTo(termId = 0) {
      termId = parseInt(termId)??0;
      this.store.setFilters({parent: termId, page: 1});
      window.removeChildren(this.ui.terms.list);
      this.updateBreadcrumbs(termId);
   }
   /**
    * Add term to modal display
    */
   addTermToModalDisplay(id, name, path) {
      const item = window.getTemplate('selectedTerm').cloneNode(true);
      item.dataset.id = id;
      item.dataset.path = path;
      item.dataset.name = name;
      item.dataset.taxonomy = this.currentConfig.taxonomy;
      item.querySelector('span').textContent = path;
   nextPage() {
      let current = this.store.filters.page;
      let page = Math.min(current++, this.store.lastResponse.total);
      this.store.setFilters({page:page});
   }
   prevPage() {
      let current = this.store.filters.page;
      let page = Math.max(current - 1, 1);
      this.store.setFilters({page:page});
   }
   addTermToModal(termId) {
      const term = this.store.get(termId);
      if (!term) return;
      const item = window.getTemplate('selectedTerm');
      item.dataset.id = termId;
      item.querySelector('span').textContent = term.path;
      item.querySelector('button').title = `Remove ${name}`;
      this.ui.selectedTerms.appendChild(item);
      this.ui.selected.append(item);
   }
   /******************************************************************
    FIELDS
    ******************************************************************/
   scanExistingFields(container = document.body) {
      container.querySelectorAll('[data-type="selector"]').forEach(
         selector => {
            try {
               this.registerField(selector);
            } catch (error) {
               this.error.log(error, {
                  component: 'TaxonomySelector',
                  action: 'scanExistingFields',
                  container: selector.dataset.name
               });
            }
         }
      );
   }
   /**
    * Check selection limits and disable/enable checkboxes
    */
   checkSelectionLimits() {
      if (!this.currentConfig || this.currentConfig.maxSelection === 0) {
   registerField(element, options = {}) {
      let input = element.querySelector('input[type="hidden"]');
      if (!input) {
         console.warn('TaxonomySelector: No hidden input found for field', element);
         return;
      }
      this.disabled = this.selectedTerms.size >= this.currentConfig.maxSelection;
      this.setCheckboxes(this.disabled);
      if (!('fieldId' in element.dataset)) {
         element.dataset.fieldId = window.generateID('selector');
      }
      const fieldId = element.dataset.fieldId;
      let selectors = this.selectors.field;
      let button = element.querySelector('button.taxonomy-toggle');
      if (options.size === 0){
         if (!button) return;
         options = button.dataset;
         if (options.size === 0) return;
      } else if (Object.hasOwn(options, 'toggle')) {
         button = document.querySelector(options.toggle);
         selectors.toggle = options.toggle;
      }
      const config = {
         id: fieldId,
         value: input,
         element: element,
         taxonomy: options.taxonomy??false,
         singular: options.single??'',
         plural: options.plural??'',
         name: element.dataset.field,
         canSearch: Object.hasOwn(options, 'search'),
         limit: options.limit??0,
         hasAutocomplete: Object.hasOwn(options, 'autocomplete'),
         canCreate: Object.hasOwn(options, 'creatable'),
         isRequired: Object.hasOwn(options, 'required'),
         toggle: button,
         selectors: selectors,
         ui: window.uiFromSelectors(selectors, element),
         checked: false,
      };
      if (!config.taxonomy) return;
      this.fields.set(fieldId, config);
      //Check for stored selected terms in hidden input
      let selected = new Set();
      input.value.value.trim()
         .split(',')
         .map(id => parseInt(id.trim()))
         .filter(id => !isNaN(id))
         .forEach(id => selected.add(id));
      this.selectedTerms.set(fieldId, selected);
      if (this.isInitializing) {
         this.batchFetch.add(config.taxonomy);
      }
      this.updateFieldUI(fieldId);
      return fieldId;
   }
   addSelected(termId, fieldId = null) {
      if (!fieldId) fieldId = this.activeField;
      const field = this.fields.get(fieldId);
      const term = this.store.get(termId);
      if (!field || !term) return;
      const selected = this.selectedTerms.get(fieldId);
      if (field.limit !== 0 && selected.size >= field.limit) return;
      selected.add(parseInt(termId));
      this.addTermToDisplay(termId, fieldId);
      this.updateFieldValue(fieldId);
      this.checkLimits(fieldId);
   }
   removeSelected(termId, fieldId = null) {
      if (!fieldId) fieldId = this.activeField;
      const field = this.fields.get(fieldId);
      const term = this.store.get(termId);
      if (!field || !term) return;
      this.selectedTerms.get(fieldId).delete(parseInt(termId));
      const selectedItem = field.ui.selected.querySelector(`[data-i"${termId}"]`);
      if (selectedItem) selectedItem.remove();
      if (this.container.open) {
         let item = this.ui.selected.querySelector(`[data-id="${termId}"]`);
         if (item) item.remove();
      }
      this.updateFieldValue(fieldId);
      this.checkLimits(fieldId);
   }
   updateFieldValue(fieldId) {
      const field = this.fields.get(fieldId);
      if (!field) return;
      let selected = Array.from(this.selectedTerms.get(fieldId));
      field.ui.value = selected.join(',');
   }
   checkLimits(fieldId) {
      if (!this.container.open) return;
      const field = this.fields.get(fieldId);
      if (!field || field.limit === 0) return;
      const disabled = this.selectedTerms.get(fieldId).size >= field.limit;
      this.setCheckboxes(disabled);
   }
   updateFieldUI(fieldId) {
      const field = this.fields.get(fieldId);
      let selected = this.selectedTerms.get(fieldId);
      if (!field || selected.size === 0) return;
      Array.from(selected).forEach(termId => {
         this.addTermToDisplay(termId, fieldId);
      });
   }
   updateFieldsForTaxonomy(taxonomy) {
      let fields = Array.from(this.fields.values())
         .filter(field => !field.checked && field.taxonomy === taxonomy);
      const hasItems = Array.from(this.store.data.values())
         .some(term=>term.taxonomy === taxonomy);
      fields.forEach(field => {
         field.ui.toggle.disabled = !hasItems && !field.canCreate;
         field.ui.toggle.title = !hasItems
            ? `No ${field.singular} available`
            : `Select ${field.plural}`;
         field.checked = true;
      });
   }
   showModalTerms(append = true, showPath = false) {
      const terms = this.store.getFiltered();
      if (terms.size === 0) return;
      if (!append) {
         window.removeChildren(this.ui.terms.list);
      }
      const currentParent = this.store.filters.parent??0;
      this.ui.nav.back.hidden = currentParent === 0;
      const fragment = document.createDocumentFragment();
      terms.forEach(term => {
         const element = this.createTermElement({
            show: showPath,
            ... term
         });
         if (element) {
            fragment.appendChild(element);
         }
      });
      this.ui.terms.list.append(fragment);
   }
   createTermElement(term) {
      if (!term || !term.name) return null;
      const item = window.getTemplate('termListItem');
      item.dataset.id = term.id;
      const isSelected = this.selectedTerms.get(this.activeField).has(term.id);
      let [
         checkbox,
         label,
         nameSpan
      ] = [
         item.querySelector('input'),
         item.querySelector('label'),
         item.querySelector('span, .term-name')
      ];
      let field = this.currentField();
      let limitReached = field.limit > 0 && this.selectedTerms.get(this.activeField).size >= field.limit;
      if (checkbox && label && nameSpan) {
         [
            checkbox.id,
            checkbox.name,
            checkbox.value,
            checkbox.disabled,
            checkbox.checked,
            label.htmlFor,
            label.title,
            label.dataset.path,
            nameSpan.textContent
         ] = [
            `${field.element.id}-${term.id}`,
            `${field.container.id}-${field.taxonomy}-select`,
            term.id,
            !isSelected && limitReached,
            isSelected,
            `${field.element.id}-${term.id}`,
            term.path??term.name,
            term.path,
            term.show ? term.path : term.name
         ];
         if (term.hasChildren) {
            const toggle = window.getTemplate('termChildrenToggle');
            if (toggle) {
               toggle.ariaLabel = `View ${field.plural} nested under ${term.name}`;
               item.append(toggle);
            }
         }
      }
      return item;
   }
   showAutocompleteTerms() {
      const field = this.currentField();
      const terms = this.currentTerms();
      if (!field || terms.size ===0) return;
      const dropdown = field.ui.dropdown;
      window.removeChildren(dropdown);
      if (terms.length === 0) {
         this.showEmptyState(`No ${field.plural} found.`, dropdown);
      } else {
         terms.forEach(term => {
            const item = this.createAutocompleteTerm(term);
            if (item) {
               dropdown.append(item);
            }
         })
      }
      const query = field.ui.search?.value;
      if (field.canCreate && query.length >= 2 && this.creator) {
         const createButton = this.createTermButton(query);
         if (createButton) {
            dropdown.append(createButton);
         }
      }
      dropdown.hidden = false;
   }
   createAutocompleteTerm(term) {
      const item = window.getTemplate('autocompleteItem');
      if (!item) return;
      item.dataset.id = term.id;
      item.textContent = term.path || term.name;
      return item;
   }
   /******************************************************************
    UI
    ******************************************************************/
   addTermToDisplay(termId, fieldId) {
      const term = this.store.get(termId);
      const field = this.fields.get(fieldId);
      if (!term || !field) return;
      //if the term already exists in the selected items, bail early
      if (field.ui.selected.querySelector(`[data-id="${termId}"]`)) return;
      const item = window.getTemplate('selectedTerm');
      if (!item) return;
      item.dataset.id = termId;
      item.dataset.taxonomy = field.taxonomy;
      item.querySelector('.item-name').textContent = term.path;
      item.querySelector('button').title = `Remove ${term.name}`;
      field.ui.selected.append(item);
      if (this.container.open) {
         this.addTermToModal(termId);
         const checkbox = this.ui.terms.list.querySelector(`input[value="${termId}"]`);
         if (checkbox) checkbox.checked = true;
      }
   }
   createTermButton(query) {
      const button = window.getTemplate('autocompleteButton');
      if(!button) return;
      let queryEl = button.querySelector('span');
      queryEl.textContent = `"${query}"`;
      return button;
   }
   updateBreadcrumbs(termId) {
      const nav = this.ui.nav.nav;
      if (!nav) return;
      const existingCrumb = Array.from(nav.children)
         .find(crumb => parseInt(crumb.dataset.id) === termId);
      if (existingCrumb) {
         // Remove all siblings after this crumb
         let nextSibling = existingCrumb.nextElementSibling;
         while (nextSibling) {
            const toRemove = nextSibling;
            nextSibling = nextSibling.nextElementSibling;
            toRemove.remove();
         }
      } else {
         // Add new breadcrumb
         const term = this.store.get(termId);
         if (!term) return;
         const crumb = window.getTemplate('termBreadcrumb');
         if (!crumb) return;
         crumb.dataset.id = termId;
         crumb.textContent = term.name;
         crumb.title = term.name;
         nav.append(crumb);
      }
   }
   updateSelectionCount() {
      if (!this.container.open) return;
      const field = this.fields.get(this.activeField);
      if (!field) return;
      if (this.ui.modal.count) {
         const total = this.selectedTerms.get(this.activeField).size;
         this.ui.modal.count.textContent = field.limit > 0
            ? `${total} of ${field.limit} ${field.plural} selected`
            : `${total} ${field.plural} selected`;
      }
   }
   /******************************************************************
    UTILITY
    ******************************************************************/
   currentField() {
      return this.fields.get(this.activeField)??false;
   }
   currentTerms() {
      return this.store.getFiltered();
   }
   needsCreator() {
      return Array.from(this.fields.values()).some(field =>
         field.canCreate || field.hasAutocomplete
      );
   }
   getFieldId(element) {
      if (element.dataset.fieldId) return element.dataset.fieldId;
      const fieldContainer = element.closest('[data-field-id]');
      return fieldContainer?.dataset.fieldId || null;
   }
   /**
    * Set checkbox disabled state
    * Sets all checkbox disabled (or not)
    * @param {Boolean} disabled
    */
   setCheckboxes(disabled) {
      this.ui.termsList.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
      this.ui.terms.list.querySelectorAll('input[type=checkbox]').forEach(checkbox => {
         if (!checkbox.checked) {
            checkbox.disabled = disabled;
         }
      });
   }
   /**
    * Save modal selections to field
    */
   saveSelectionsToField(fieldId) {
      const field = this.fields.get(fieldId);
      if (!field) return;
   /******************************************************************
    DATASTORE HELPERS
   ******************************************************************/
   handleStoreEvent(event, data) {
      const handlers = {
         'data-loaded': () => this.handleDataLoaded(),
         'filters-changed': () => this.handleFiltersChanged(),
         'fetch-error': () => this.handleFetchError()
      };
      // Clear current field selections
      field.selectedTerms.clear();
      window.removeChildren(field.selectedContainer);
      handlers[event]?.();
   }
   handleDataLoaded() {
      const taxonomy = this.store.filters.taxonomy;
      if (taxonomy?.includes(',')) {
         const taxonomies = taxonomy.split(',').map(t => t.trim());
         taxonomies.forEach(tax => this.updateFieldsForTaxonomy(tax));
      }
      // Add modal selections to field
      this.selectedTerms.forEach((termData, id) => {
         field.selectedTerms.add(id);
         this.addTermToDisplay(fieldId, id, termData.name, termData.path);
      if (this.container.open) {
         this.showResults();
         return;
      }
      if (this.activeField) {
         this.showResults(true);
      }
   }
   showResults(isAutoComplete = false) {
      this.setLoading(false);
      const terms = this.store.getFiltered();
      const filters = this.store.filters;
      const response = this.store.lastResponse?.page || {};
      const isSearch = filters.search && filters.search.length > 0;
      const append = filters.page > 1;
      const field = this.currentField();
      this.notify('terms-loaded', {
         terms,
         filters
      });
      // Update hidden input
      const selectedIds = Array.from(field.selectedTerms);
      field.input.value = selectedIds.join(',');
      field.input.dispatchEvent(new Event('change', { bubbles: true }));
   }
   /**
    * Remove selected term from field
    */
   removeSelectedTerm(fieldId, termId) {
      const field = this.fields.get(fieldId);
      if (!field) return;
      const id = parseInt(termId);
      field.selectedTerms.delete(id);
      // Remove from display
      const selectedItem = field.selectedContainer.querySelector(`[data-id="${id}"]`);
      if (selectedItem) {
         selectedItem.remove();
      }
      // Update hidden input
      const selectedIds = Array.from(field.selectedTerms);
      field.input.value = selectedIds.join(',');
      field.input.dispatchEvent(new Event('change', { bubbles: true }));
   }
   /**
    * Add term to field display
    */
   addTermToDisplay(fieldId, id, name, path) {
      const field = this.fields.get(fieldId);
      if (!field || field.selectedContainer.querySelector(`[data-id="${id}"]`)) {
         return; // Already displayed
      }
      const item = window.getTemplate('selectedTerm').cloneNode(true);
      item.dataset.id = id;
      item.dataset.path = path;
      item.dataset.name = name;
      item.dataset.taxonomy = field.taxonomy;
      item.querySelector('span').textContent = path;
      item.querySelector('button').title = `Remove ${name}`;
      field.selectedContainer.appendChild(item);
   }
   /**
    * Update field from hidden input value
    */
   updateFieldFromInput(fieldId) {
      const field = this.fields.get(fieldId);
      if (!field) return;
      const value = field.input.value.trim();
      field.selectedTerms.clear();
      window.removeChildren(field.selectedContainer);
      if (value !== '') {
         const selectedIds = value.split(',')
            .map(id => parseInt(id.trim()))
            .filter(id => !isNaN(id));
         selectedIds.forEach(id => field.selectedTerms.add(id));
         this.initFieldDisplay(fieldId);
      }
   }
   /**
    * Handle search input
    */
   handleSearch() {
      const query = this.ui.searchInput.value.trim();
      if (query.length >= 2 || query.length === 0) {
         // Reset pagination when searching
         this.activeStore.setFilter('page', 1);
         this.activeStore.setFilter('search', query);
         window.removeChildren(this.ui.termsList);
         if (query.length >= 2) {
            this.showLoading();
            this.fetchCurrentTerms();
         } else if (query.length === 0) {
            // Clear search and reload
            this.showLoading();
            this.fetchCurrentTerms();
         }
      } else {
         this.hideLoading();
         this.showEmptyState('Enter at least 2 characters to search.');
      }
   }
   /**
    * Navigate to parent term
    */
   navigateToParent() {
      const currentParent = this.activeStore.filters.parent || 0;
      // Find parent of current parent (could enhance this with breadcrumb tracking)
      this.activeStore.setFilter('parent', 0);
      this.activeStore.setFilter('page', 1);
      window.removeChildren(this.ui.termsList);
      this.showLoading();
      this.fetchCurrentTerms();
      // Update breadcrumbs
      this.ui.breadcrumbs.back.hidden = true;
   }
   /**
    * Navigate to child term
    */
   navigateToChild(termId, termName) {
      this.activeStore.setFilter('parent', termId);
      this.activeStore.setFilter('page', 1);
      window.removeChildren(this.ui.termsList);
      this.showLoading();
      this.fetchCurrentTerms();
      // Update breadcrumbs
      this.updateBreadcrumbs(termId, termName);
      this.ui.breadcrumbs.back.hidden = false;
   }
   /**
    * Navigate to specific path level
    */
   navigateToPath(pathLevel) {
      const parentId = parseInt(pathLevel.dataset.id) || 0;
      this.activeStore.setFilter('parent', parentId);
      this.activeStore.setFilter('page', 1);
      window.removeChildren(this.ui.termsList);
      this.showLoading();
      this.fetchCurrentTerms();
      // Update breadcrumbs to this level
      // You'd need to track the full path to properly implement this
      this.ui.breadcrumbs.back.hidden = parentId === 0;
   }
   /**
    * Fetch terms using current store filters
    */
   fetchCurrentTerms() {
      if (!this.activeStore) return;
      this.showLoading();
      this.activeStore.fetch();
   }
   /**
    * Load more terms (pagination)
    */
   loadMoreTerms() {
      if (!this.activeStore) return;
      const currentPage = this.activeStore.filters.page || 1;
      this.activeStore.setFilter('page', currentPage + 1);
      // fetch() will be called automatically by setFilter
   }
   /**
    * Render terms list
    */
   renderTerms(terms, append = false, showPath = false) {
      if (!append) {
         window.removeChildren(this.ui.termsList);
      }
      if (terms.length === 0) {
         if (!append) {
            this.showEmptyState();
            this.showEmptyState(isSearch ? `No matching ${field.plural}.` : `No ${field.plural} available.`);
         }
         return;
         this.observer.unobserve(this.ui.terms.sentinel);
      } else {
         if (!isAutoComplete) {
            this.showModalTerms(append, isSearch);
            if (response.has_more) {
               this.observer.observe(this.ui.terms.sentinel);
            } else {
               this.observer.unobserve(this.ui.terms.sentinel);
            }
         } else {
            this.showAutocompleteTerms()
         }
      }
      // Update breadcrumbs if needed
      const currentParent = this.activeStore.filters.parent || 0;
      this.ui.breadcrumbs.back.hidden = currentParent === 0;
      this.a11y.announce(terms.length, append);
   }
   handleFiltersChanged() {
      // if (this.modal?.open) {
      //    this.setLoading();
      // }
   }
      terms.forEach(term => {
         // Check if we have a cached DOM element
         const cachedElement = this.activeStore.getDOMElement(term.id, 'list-item');
   handleFetchError(error) {
      this.setLoading(false);
   }
   async batchFetchTaxonomies() {
      if (this.batchFetch.size === 0) return;
         if (cachedElement) {
            // Update checkbox state if needed
            const checkbox = cachedElement.querySelector('input[type="checkbox"]');
            if (checkbox) {
               checkbox.checked = this.selectedTerms.has(term.id);
               checkbox.disabled = !checkbox.checked && this.disabled;
            }
            this.ui.termsList.appendChild(cachedElement);
      const taxonomies = Array.from(this.batchFetch);
      taxonomies.forEach(tax => this.loadedTaxonomies.add(tax));
      this.batchFetch.clear();
      try {
         taxonomies.forEach(tax => this.loadedTaxonomies.add(tax));
         await this.store.setFilters({
            taxonomy: taxonomies.join(','),
            page: 1,
            search: '',
            parent: 0
         });
      } catch (error) {
         console.error('Failed to batch fetch taxonomies:', error);
      }
   }
   preloadTaxonomy(taxonomy) {
      if (this.loadedTaxonomies.has(taxonomy)) return;
      this.store.setFilters( {
         taxonomy: taxonomy,
         page: 1,
         search: '',
         parent: 0
      });
      this.loadedTaxonomies.add(taxonomy);
   }
   /**************************************************
    LOADING
   **************************************************/
   setLoading(on = true) {
      this.ui.loading.loading.hidden = on;
      this.modal.classList.toggle('loading', on);
      if (on) {
         let searchQuery = this.store.filters.search || '';
         searchQuery = searchQuery === '' ? false : searchQuery;
         const currentParent = this.store.filters.parent || 0;
         const message = searchQuery
            ? `Searching for "${searchQuery} items` :
            currentParent === 0
               ? 'loading items'
               : 'loading child items';
         if (window.typeLoop && this.ui.loading.text) {
            this.stopTyping = window.typeLoop(this.ui.loading.text, message);
         } else {
            // Create new element and cache it
            const element = this.createTermElement({
               id: parseInt(term.id),
               name: term.name,
               hasChildren: term.hasChildren,
               path: term.path || null,
               show: showPath
            });
            if (element) {
               this.activeStore.storeDOMElement(term.id, 'list-item', element);
               this.ui.termsList.appendChild(element);
            }
            this.ui.loading.text.textContenet = message;
         }
      } else {
         if (this.stopTyping) {
            this.stopTyping();
            this.stopTyping = null;
         }
      }
   }
   showEmptyState(message = 'No items found.', container = null) {
      if (!container) container = this.ui.terms.list;
      const emptyElement = window.getTemplate('noTermResults');
      const span = emptyElement.querySelector('span');
      if (message && span) {
         span.textContent = message;
      }
      container.append(emptyElement);
   }
   /**************************************************
    SUBSCRIBERS
   **************************************************/
   subscribe(callback) {
      this.subscribers.add(callback);
      return () => this.subscribers.delete(callback);
   }
   notify(event, data={}) {
      this.subscribers.forEach(callback => {
         try {
            callback(event, data);
         } catch (error) {
            console.error('Subscriber error:', error);
         }
      });
   }
   /**
    * Create individual term element
    */
   createTermElement(termData) {
      if (!termData || !termData.name) return null;
      const listItem = window.getTemplate('termListItem').cloneNode(true);
      listItem.dataset.id = termData.id;
      const isSelected = this.selectedTerms.has(termData.id);
      const checkbox = listItem.querySelector('input');
      const label = listItem.querySelector('label');
      const nameSpan = listItem.querySelector('span, .term-name');
      if (checkbox && label && nameSpan) {
         checkbox.id = `${this.currentConfig.container.id}${termData.id}`;
         checkbox.name = `${this.currentConfig.container.id}${this.currentConfig.taxonomy}-select`;
         checkbox.value = termData.id;
         checkbox.disabled = !isSelected && this.disabled;
         checkbox.checked = isSelected;
         label.htmlFor = checkbox.id;
         label.title = termData.path || termData.name;
         label.dataset.path = termData.path;
         nameSpan.textContent = termData.show ? termData.path : termData.name;
      }
      if (termData.hasChildren) {
         const childrenToggle = window.getTemplate ?
            window.getTemplate('termChildrenToggle') :
            this.createChildrenToggle();
         if (childrenToggle) {
            childrenToggle.ariaLabel = `View sub-terms of ${termData.name}`;
            listItem.appendChild(childrenToggle);
         }
      }
      return listItem;
   }
   /**
    * Create children toggle button
    */
   createChildrenToggle() {
      const button = document.createElement('button');
      button.type = 'button';
      button.className = 'toggle-children';
      button.innerHTML = '→';
      return button;
   }
   /**
    * Update breadcrumb navigation
    */
   updateBreadcrumbs(termId, termName) {
      // This is a simplified version - you'd want to maintain a proper breadcrumb trail
      const breadcrumb = window.getTemplate('termBreadcrumb').cloneNode(true);
      breadcrumb.dataset.id = termId;
      breadcrumb.textContent = termName;
      breadcrumb.title = termName;
      // Remove any existing breadcrumbs after this level
      const existingCrumb = this.ui.breadcrumbs.nav.querySelector(`[data-id="${termId}"]`);
      if (existingCrumb) {
         // Remove all breadcrumbs after this one
         while (existingCrumb.nextElementSibling) {
            existingCrumb.nextElementSibling.remove();
         }
      } else {
         this.ui.breadcrumbs.nav.appendChild(breadcrumb);
      }
   }
   /**
    * Show loading state
    */
   showLoading() {
      this.ui.loading.loading.hidden = false;
      this.modal.classList.add('loading');
      const searchQuery = this.activeStore?.filters?.search || '';
      const currentParent = this.activeStore?.filters?.parent || 0;
      let message = searchQuery !== '' ?
         `searching for "${searchQuery}" items` :
         currentParent === 0 ?
            'loading items' :
            `loading child items`;
      if (window.typeLoop) {
         this.stopTyping = window.typeLoop(this.ui.loading.text, message);
      } else {
         this.ui.loading.text.textContent = message;
      }
   }
   /**
    * Hide loading state
    */
   hideLoading() {
      this.ui.loading.loading.hidden = true;
      this.modal.classList.remove('loading');
      if (this.stopTyping) {
         this.stopTyping();
      }
   }
   /**
    * Show empty state message
    */
   showEmptyState(message = 'No items found.') {
      const emptyElement = window.getTemplate('noResults').cloneNode(true);
      if (message && emptyElement.querySelector('span')) {
         emptyElement.querySelector('span').textContent = message;
      }
      this.ui.termsList.appendChild(emptyElement);
   }
   /**
    * Get field ID from any element within the field
    */
   getFieldId(element) {
      if (element.dataset.fieldId) {
         return element.dataset.fieldId;
      }
      const fieldContainer = element.closest('[data-field-id]');
      if (fieldContainer) {
         return fieldContainer.dataset.fieldId;
      }
      return null;
   }
   /**
    * Clean up
    */
   /******************************************************
    CLEANUP
   ******************************************************/
   destroy() {
      // Remove event listeners
      document.removeEventListener('click', this.handleClick);
      document.removeEventListener('change', this.handleChange);
      document.removeEventListener('click', this.clickHandler);
      document.removeEventListener('change', this.changeHandler);
      document.removeEventListener('input', this.inputHandler);
      document.removeEventListener('focus', this.focusHandler);
      document.removeEventListener('blur', this.blurHandler);
      // Clear intervals and cleanup
      this.observer?.disconnect();
      // Destroy all stores
      this.store.destroy();
      // Clear all maps
      this.subscribers.clear();
      this.fields.clear();
      this.selectedTerms.clear();
   }
}
/**
 * Initialize singleton
 */
document.addEventListener('DOMContentLoaded', function() {
   if (!window.jvbSelector) {
      window.jvbSelector = new TaxonomySelector();
   }
   window.auth.subscribe((event) => {
      if (event === 'auth-loaded') {
         window.jvbSelector = new TaxonomySelector();
      }
   });
});