/**
 * @file
 * NodeHive DAM JavaScript for drag & drop uploads and preview.
 */

(function (Drupal) {
  'use strict';

  // Global flag to track if initial grid load has happened.
  var initialGridLoadDone = false;

  Drupal.behaviors.nodehiveDam = {
    attach: function (context) {
      this.initUpload(context);
      this.initPreview(context);
      this.initFolders(context);
      this.initFolderModal(context);
      this.initCollections(context);
      this.initCollectionModal(context);
      this.initDragDrop(context);
      this.initBulkSelection(context);
      this.initUrlHash(context);
    },

    /**
     * Show a toast notification.
     */
    showToast: function (message) {
      // Remove existing toast if any
      var existing = document.querySelector('.dam-toast');
      if (existing) {
        existing.remove();
      }

      // Create toast element
      var toast = document.createElement('div');
      toast.className = 'dam-toast';
      toast.textContent = message;
      document.body.appendChild(toast);

      // Trigger animation
      setTimeout(function () { toast.classList.add('is-visible'); }, 10);

      // Auto-hide after 2 seconds
      setTimeout(function () {
        toast.classList.remove('is-visible');
        setTimeout(function () { toast.remove(); }, 300);
      }, 2000);
    },

    // Update URL hash based on current folder/collection selection.
    // Uses replaceState to avoid triggering hashchange event.
    updateUrlHash: function (type, id) {
      var newHash = '';
      if (type && id && id !== '') {
        newHash = '#' + type + '=' + id;
      } else if (type === 'folder' && id === '_none') {
        newHash = '#folder=unfiled';
      }

      var newUrl = window.location.pathname + window.location.search + newHash;
      history.replaceState(null, '', newUrl);
    },

    // Parse URL hash and return type and id.
    parseUrlHash: function () {
      var hash = window.location.hash.substring(1);
      if (!hash) {
        return null;
      }

      var parts = hash.split('=');
      if (parts.length !== 2) {
        return null;
      }

      var type = parts[0];
      var id = parts[1];

      if (type === 'folder' && id === 'unfiled') {
        return { type: 'folder', id: '_none' };
      }

      return { type: type, id: id };
    },

    initUpload: function (context) {
      const uploadZone = context.querySelector ? context.querySelector('#dam-upload-zone') : null;
      const fileInput = context.querySelector ? context.querySelector('#dam-file-input') : null;
      const browseButton = context.querySelector ? context.querySelector('.dam-upload-zone__button') : null;
      const progress = context.querySelector ? context.querySelector('#dam-upload-progress') : null;
      const grid = context.querySelector ? context.querySelector('#dam-grid') : null;

      if (!uploadZone || uploadZone.dataset.damInitialized) {
        return;
      }
      uploadZone.dataset.damInitialized = 'true';

      // Browse button click.
      if (browseButton) {
        browseButton.addEventListener('click', function (e) {
          e.preventDefault();
          e.stopPropagation();
          fileInput.click();
        });
      }

      // File input change.
      fileInput.addEventListener('change', function () {
        if (this.files.length > 0) {
          handleFiles(this.files);
          this.value = '';
        }
      });

      // Drag & drop events for file uploads.
      // Only handle if we're dragging files, not media items.
      function isDraggingFiles(e) {
        // If we're dragging a media item, don't handle it here.
        if (window.damDragData && window.damDragData.mediaId) {
          return false;
        }
        // Check if dragging files.
        if (e.dataTransfer.types) {
          return e.dataTransfer.types.indexOf('Files') !== -1;
        }
        return true;
      }

      ['dragenter', 'dragover'].forEach(function (eventName) {
        uploadZone.addEventListener(eventName, function (e) {
          if (!isDraggingFiles(e)) {
            return;
          }
          e.preventDefault();
          e.stopPropagation();
          uploadZone.classList.add('is-dragover');
        });
      });

      ['dragleave'].forEach(function (eventName) {
        uploadZone.addEventListener(eventName, function (e) {
          if (!isDraggingFiles(e)) {
            return;
          }
          e.preventDefault();
          e.stopPropagation();
          uploadZone.classList.remove('is-dragover');
        });
      });

      uploadZone.addEventListener('drop', function (e) {
        uploadZone.classList.remove('is-dragover');
        if (!isDraggingFiles(e)) {
          return;
        }
        e.preventDefault();
        e.stopPropagation();
        const files = e.dataTransfer.files;
        if (files.length > 0) {
          handleFiles(files);
        }
      });

      function handleFiles(files) {
        const fileArray = Array.from(files);
        let completed = 0;

        progress.classList.add('is-uploading');

        fileArray.forEach(function (file) {
          uploadFile(file, function (success, html) {
            completed++;

            if (success && html && grid) {
              const gridItems = grid.querySelector('.dam-grid__items');
              if (gridItems) {
                const temp = document.createElement('div');
                temp.innerHTML = html;
                const newItem = temp.firstElementChild;
                if (newItem) {
                  newItem.classList.add('is-new');
                  gridItems.insertBefore(newItem, gridItems.firstChild);
                }
              }
            }

            if (completed === fileArray.length) {
              progress.classList.remove('is-uploading');
            }
          });
        });
      }

      function uploadFile(file, callback) {
        const formData = new FormData();
        formData.append('file', file);

        // Include selected folder if any.
        const folderInput = document.getElementById('dam-folder-input');
        if (folderInput && folderInput.value && folderInput.value !== '' && folderInput.value !== '_none') {
          formData.append('folder', folderInput.value);
        }

        fetch('/nodehive/admin/dam/upload', {
          method: 'POST',
          body: formData,
          headers: {
            'Accept': 'text/html'
          }
        })
          .then(function (response) {
            if (!response.ok) {
              throw new Error('Upload failed');
            }
            return response.text();
          })
          .then(function (html) {
            callback(true, html);
          })
          .catch(function (error) {
            console.error('Upload error:', error);
            callback(false, null);
          });
      }
    },

    initPreview: function (context) {
      // Only initialize once on document level using event delegation.
      if (context !== document) {
        return;
      }

      const preview = document.getElementById('dam-preview');
      if (!preview || preview.dataset.previewInitialized) {
        return;
      }
      preview.dataset.previewInitialized = 'true';

      const backdrop = preview.querySelector('.dam-preview__backdrop');
      const closeBtn = preview.querySelector('.dam-preview__close');
      const mediaContainer = preview.querySelector('.dam-preview__media');
      const typeEl = preview.querySelector('.dam-preview__type');
      const dateEl = preview.querySelector('.dam-preview__date');
      const nameInput = preview.querySelector('.dam-preview__name-input');
      const altField = preview.querySelector('.dam-preview__alt-field');
      const altInput = preview.querySelector('.dam-preview__alt-input');
      const saveBtn = preview.querySelector('.dam-preview__save');
      const dimensionsRow = preview.querySelector('.dam-preview__dimensions-row');
      const dimensionsEl = preview.querySelector('.dam-preview__dimensions');
      const filesizeRow = preview.querySelector('.dam-preview__filesize-row');
      const filesizeEl = preview.querySelector('.dam-preview__filesize');
      const stylesContainer = preview.querySelector('.dam-preview__styles');
      const stylesList = preview.querySelector('.dam-preview__styles-list');
      const editLink = preview.querySelector('.dam-preview__edit');

      let currentMediaId = null;
      let originalName = '';
      let originalAlt = '';
      let isImage = false;

      // Use event delegation on the grid container.
      document.addEventListener('click', function (e) {
        const btn = e.target.closest('.dam-item__preview-btn');
        if (!btn) {
          return;
        }

        e.preventDefault();
        e.stopPropagation();

        const item = btn.closest('.dam-item');
        if (item) {
          openPreview(item);
        }
      });

      function formatFileSize(bytes) {
        if (!bytes || bytes === '0') return '';
        bytes = parseInt(bytes, 10);
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
      }

      function openPreview(item) {
        const name = item.dataset.mediaName || 'Unknown';
        const type = item.dataset.mediaType || 'Unknown';
        const date = item.dataset.mediaDate || '';
        const previewUrl = item.dataset.mediaPreview || item.dataset.mediaThumbnail || '';
        const fileUrl = item.dataset.mediaFile || '';
        const mimeType = item.dataset.mediaMime || '';
        const fileSize = item.dataset.mediaFilesize || '';
        const imageWidth = item.dataset.mediaWidth || '';
        const imageHeight = item.dataset.mediaHeight || '';
        const altText = item.dataset.mediaAlt || '';
        const editUrl = item.dataset.mediaEdit || '#';

        currentMediaId = item.dataset.mediaId;
        originalName = name;
        originalAlt = altText;
        isImage = mimeType && mimeType.startsWith('image/');

        nameInput.value = name;
        typeEl.textContent = mimeType ? type + ' · ' + mimeType : type;
        dateEl.textContent = date;
        editLink.href = editUrl;

        // Show alt field for images.
        if (isImage) {
          altInput.value = altText;
          altField.style.display = '';
        } else {
          altField.style.display = 'none';
        }

        // Hide save button initially.
        saveBtn.style.display = 'none';

        // Show dimensions for images.
        if (imageWidth && imageHeight && imageWidth !== '0' && imageHeight !== '0') {
          dimensionsEl.textContent = imageWidth + ' × ' + imageHeight + ' px';
          dimensionsRow.style.display = '';
        } else {
          dimensionsRow.style.display = 'none';
        }

        // Show file size.
        const formattedSize = formatFileSize(fileSize);
        if (formattedSize) {
          filesizeEl.textContent = formattedSize;
          filesizeRow.style.display = '';
        } else {
          filesizeRow.style.display = 'none';
        }

        // Show image style URLs.
        const stylesData = item.dataset.mediaStyles || '[]';
        let styles = [];
        try {
          styles = JSON.parse(stylesData);
        } catch (e) {
          styles = [];
        }

        if (styles && styles.length > 0) {
          stylesList.innerHTML = styles.map(function(style) {
            return '<li class="dam-preview__style-item">' +
              '<span class="dam-preview__style-name">' + style.name + '</span>' +
              '<input type="text" class="dam-preview__style-url" value="' + style.url + '" readonly onclick="this.select()">' +
              '<button type="button" class="dam-preview__style-copy" data-url="' + style.url + '" title="Copy URL">📋</button>' +
              '</li>';
          }).join('');
          stylesContainer.style.display = '';
        } else {
          stylesContainer.style.display = 'none';
        }

        // Set media content based on mime type.
        if (mimeType === 'application/pdf' && fileUrl) {
          // Show PDF in iframe viewer.
          mediaContainer.innerHTML = '<iframe class="dam-preview__pdf" src="' + fileUrl + '" title="' + name + '"></iframe>';
        } else if (mimeType && mimeType.startsWith('video/') && fileUrl) {
          // Show video player.
          mediaContainer.innerHTML = '<video class="dam-preview__video" controls><source src="' + fileUrl + '" type="' + mimeType + '">Your browser does not support the video tag.</video>';
        } else if (mimeType && mimeType.startsWith('audio/') && fileUrl) {
          // Show audio player with icon.
          mediaContainer.innerHTML = '<div class="dam-preview__audio-wrapper">' +
            '<svg class="dam-preview__audio-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>' +
            '<audio class="dam-preview__audio" controls><source src="' + fileUrl + '" type="' + mimeType + '">Your browser does not support the audio tag.</audio>' +
            '</div>';
        } else if (previewUrl) {
          // Show image.
          mediaContainer.innerHTML = '<img src="' + previewUrl + '" alt="' + name + '">';
        } else {
          // Show placeholder.
          mediaContainer.innerHTML = '<div class="dam-preview__placeholder">' +
            '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">' +
            '<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/>' +
            '<polyline points="13 2 13 9 20 9"/>' +
            '</svg>' +
            '<span>' + type + '</span>' +
            '</div>';
        }

        preview.classList.add('is-open');
        document.body.style.overflow = 'hidden';
      }

      function closePreview() {
        preview.classList.remove('is-open');
        document.body.style.overflow = '';
      }

      // Copy URL button handler.
      stylesContainer.addEventListener('click', function(e) {
        const copyBtn = e.target.closest('.dam-preview__style-copy');
        if (copyBtn) {
          const url = copyBtn.dataset.url;
          navigator.clipboard.writeText(url).then(function() {
            copyBtn.textContent = '✓';
            setTimeout(function() {
              copyBtn.textContent = '📋';
            }, 1500);
          });
        }
      });

      // Check for changes and show save button.
      function checkForChanges() {
        const nameChanged = nameInput.value !== originalName;
        const altChanged = isImage && altInput.value !== originalAlt;
        if (nameChanged || altChanged) {
          saveBtn.style.display = '';
        } else {
          saveBtn.style.display = 'none';
        }
      }

      nameInput.addEventListener('input', checkForChanges);
      altInput.addEventListener('input', checkForChanges);

      // Save handler.
      saveBtn.addEventListener('click', function() {
        const data = {
          name: nameInput.value
        };
        if (isImage) {
          data.alt = altInput.value;
        }

        saveBtn.disabled = true;
        saveBtn.textContent = 'Saving...';

        fetch('/nodehive/admin/dam/save/' + currentMediaId, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        })
          .then(function(response) {
            return response.json();
          })
          .then(function(result) {
            if (result.success) {
              // Update the grid item.
              const gridItem = document.querySelector('.dam-item[data-media-id="' + currentMediaId + '"]');
              if (gridItem) {
                gridItem.dataset.mediaName = nameInput.value;
                gridItem.querySelector('.dam-item__name').textContent = nameInput.value;
                if (isImage) {
                  gridItem.dataset.mediaAlt = altInput.value;
                }
              }
              originalName = nameInput.value;
              originalAlt = altInput.value;
              saveBtn.textContent = 'Saved!';
              setTimeout(function() {
                saveBtn.style.display = 'none';
                saveBtn.textContent = 'Save changes';
              }, 1500);
            } else {
              saveBtn.textContent = 'Error!';
              setTimeout(function() {
                saveBtn.textContent = 'Save changes';
              }, 1500);
            }
            saveBtn.disabled = false;
          })
          .catch(function() {
            saveBtn.textContent = 'Error!';
            saveBtn.disabled = false;
            setTimeout(function() {
              saveBtn.textContent = 'Save changes';
            }, 1500);
          });
      });

      // Close handlers.
      closeBtn.addEventListener('click', closePreview);
      backdrop.addEventListener('click', closePreview);

      // Escape key.
      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && preview.classList.contains('is-open')) {
          closePreview();
        }
      });
    },

    initFolders: function (context) {
      const foldersList = context.querySelector ? context.querySelector('#dam-folders') : null;
      const addFolderBtn = context.querySelector ? context.querySelector('#dam-add-folder') : null;
      // Use document.getElementById as the input is outside potential HTMX swap targets.
      const folderInput = document.getElementById('dam-folder-input');

      if (!foldersList || foldersList.dataset.foldersInitialized) {
        return;
      }
      foldersList.dataset.foldersInitialized = 'true';

      // Folder selection.
      var self = this;
      foldersList.addEventListener('click', function (e) {
        const btn = e.target.closest('.dam-folders__btn');
        if (!btn) {
          return;
        }

        const item = btn.closest('.dam-folders__item');
        if (!item) {
          return;
        }

        // Update active state.
        foldersList.querySelectorAll('.dam-folders__item').forEach(function (i) {
          i.classList.remove('dam-folders__item--active');
        });
        item.classList.add('dam-folders__item--active');

        // Update hidden folder input and trigger HTMX.
        const folderId = item.dataset.folder;
        if (folderInput) {
          folderInput.value = folderId;

          // Update URL hash.
          self.updateUrlHash('folder', folderId);

          // Trigger HTMX request via the search input.
          const searchInput = document.querySelector('.dam-filters__input[name="search"]');
          if (searchInput) {
            htmx.trigger(searchInput, 'search');
          }
        }
      });

      // Add folder button - open modal in create mode.
      if (addFolderBtn) {
        addFolderBtn.addEventListener('click', function () {
          var modal = document.getElementById('dam-folder-modal');
          var titleEl = document.getElementById('dam-folder-modal-title');
          var nameInput = document.getElementById('dam-folder-name');
          var parentSelect = document.getElementById('dam-folder-parent');
          var folderIdInput = document.getElementById('dam-folder-modal-id');
          var modeInput = document.getElementById('dam-folder-modal-mode');

          titleEl.textContent = 'New Folder';
          nameInput.value = '';
          parentSelect.value = '';
          folderIdInput.value = '';
          modeInput.value = 'create';

          // Enable all options in parent select.
          Array.from(parentSelect.options).forEach(function (option) {
            option.disabled = false;
          });

          modal.classList.add('is-open');
          nameInput.focus();
        });
      }

      // Edit folder - open modal in edit mode.
      foldersList.addEventListener('click', function (e) {
        var editBtn = e.target.closest('.dam-folders__edit');
        if (!editBtn) {
          return;
        }

        e.preventDefault();
        e.stopPropagation();

        var folderItem = editBtn.closest('.dam-folders__item');
        if (!folderItem) {
          return;
        }

        var folderId = folderItem.dataset.folder;
        var currentName = folderItem.querySelector('.dam-folders__name').textContent;
        var currentParent = folderItem.dataset.folderParent || '';

        // Open the folder edit modal.
        var modal = document.getElementById('dam-folder-modal');
        var titleEl = document.getElementById('dam-folder-modal-title');
        var nameInput = document.getElementById('dam-folder-name');
        var parentSelect = document.getElementById('dam-folder-parent');
        var folderIdInput = document.getElementById('dam-folder-modal-id');
        var modeInput = document.getElementById('dam-folder-modal-mode');

        titleEl.textContent = 'Edit Folder';
        nameInput.value = currentName;
        parentSelect.value = currentParent;
        folderIdInput.value = folderId;
        modeInput.value = 'edit';

        // Disable the current folder in parent select (can't be its own parent).
        Array.from(parentSelect.options).forEach(function (option) {
          option.disabled = option.value === folderId;
        });

        modal.classList.add('is-open');
        nameInput.focus();
        nameInput.select();
      });
    },

    initFolderModal: function (context) {
      var modal = context.querySelector ? context.querySelector('#dam-folder-modal') : null;

      if (!modal || modal.dataset.modalInitialized) {
        return;
      }
      modal.dataset.modalInitialized = 'true';

      var backdrop = modal.querySelector('.dam-folder-modal__backdrop');
      var closeBtn = modal.querySelector('.dam-folder-modal__close');
      var cancelBtn = modal.querySelector('.dam-folder-modal__cancel');
      var saveBtn = modal.querySelector('.dam-folder-modal__save');
      var nameInput = document.getElementById('dam-folder-name');
      var parentSelect = document.getElementById('dam-folder-parent');
      var folderIdInput = document.getElementById('dam-folder-modal-id');
      var modeInput = document.getElementById('dam-folder-modal-mode');

      function closeModal() {
        modal.classList.remove('is-open');
      }

      function saveFolder() {
        var mode = modeInput.value;
        var folderId = folderIdInput.value;
        var newName = nameInput.value.trim();
        var newParent = parentSelect.value;

        if (!newName) {
          nameInput.focus();
          return;
        }

        saveBtn.disabled = true;
        saveBtn.textContent = 'Saving...';

        var url = mode === 'create' ? '/nodehive/admin/dam/folder/create' : '/nodehive/admin/dam/folder/rename';
        var body = mode === 'create'
          ? { name: newName, parent_id: newParent }
          : { folder_id: folderId, name: newName, parent_id: newParent };

        fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(body)
        })
          .then(function (response) {
            return response.json();
          })
          .then(function (result) {
            saveBtn.disabled = false;
            saveBtn.textContent = 'Save';

            if (result.success) {
              closeModal();
              // Reload page to reflect changes.
              window.location.reload();
            }
          })
          .catch(function () {
            saveBtn.disabled = false;
            saveBtn.textContent = 'Save';
          });
      }

      backdrop.addEventListener('click', closeModal);
      closeBtn.addEventListener('click', closeModal);
      cancelBtn.addEventListener('click', closeModal);
      saveBtn.addEventListener('click', saveFolder);

      nameInput.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          saveFolder();
        }
        if (e.key === 'Escape') {
          closeModal();
        }
      });

      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && modal.classList.contains('is-open')) {
          closeModal();
        }
      });
    },

    initCollections: function (context) {
      var collectionsList = context.querySelector ? context.querySelector('#dam-collections') : null;
      var addCollectionBtn = context.querySelector ? context.querySelector('#dam-add-collection') : null;
      // Use document.getElementById as these inputs are outside potential HTMX swap targets.
      var collectionInput = document.getElementById('dam-collection-input');
      var folderInput = document.getElementById('dam-folder-input');
      var foldersList = document.getElementById('dam-folders');

      if (!collectionsList || collectionsList.dataset.collectionsInitialized) {
        return;
      }
      collectionsList.dataset.collectionsInitialized = 'true';

      // Collection selection.
      var self = this;
      collectionsList.addEventListener('click', function (e) {
        var btn = e.target.closest('.dam-collections__btn');
        if (!btn) {
          return;
        }

        var item = btn.closest('.dam-collections__item');
        if (!item) {
          return;
        }

        var isActive = item.classList.contains('dam-collections__item--active');

        // If clicking on an active collection, deselect it.
        if (isActive) {
          item.classList.remove('dam-collections__item--active');
          if (collectionInput) {
            collectionInput.value = '';
          }
          // Clear hash.
          self.updateUrlHash(null, null);
        } else {
          // Update active state (only one collection selected at a time).
          collectionsList.querySelectorAll('.dam-collections__item').forEach(function (i) {
            i.classList.remove('dam-collections__item--active');
          });
          item.classList.add('dam-collections__item--active');

          // Clear folder selection when collection is selected.
          if (foldersList) {
            foldersList.querySelectorAll('.dam-folders__item').forEach(function (i) {
              i.classList.remove('dam-folders__item--active');
            });
            // Select "All Media" by default.
            var allMediaItem = foldersList.querySelector('.dam-folders__item[data-folder=""]');
            if (allMediaItem) {
              allMediaItem.classList.add('dam-folders__item--active');
            }
          }
          if (folderInput) {
            folderInput.value = '';
          }

          // Update hidden collection input.
          var collectionId = item.dataset.collection;
          if (collectionInput) {
            collectionInput.value = collectionId;
          }

          // Update URL hash.
          self.updateUrlHash('collection', collectionId);
        }

        // Trigger HTMX request.
        var searchInput = document.querySelector('.dam-filters__input[name="search"]');
        if (searchInput) {
          htmx.trigger(searchInput, 'search');
        }
      });

      // Add collection button - open modal in create mode.
      if (addCollectionBtn) {
        addCollectionBtn.addEventListener('click', function () {
          var modal = document.getElementById('dam-collection-modal');
          var titleEl = document.getElementById('dam-collection-modal-title');
          var nameInput = document.getElementById('dam-collection-name');
          var collectionIdInput = document.getElementById('dam-collection-modal-id');
          var modeInput = document.getElementById('dam-collection-modal-mode');
          var deleteBtn = document.getElementById('dam-collection-modal-delete');

          titleEl.textContent = 'New Collection';
          nameInput.value = '';
          collectionIdInput.value = '';
          modeInput.value = 'create';
          deleteBtn.style.display = 'none';

          modal.classList.add('is-open');
          nameInput.focus();
        });
      }

      // Edit collection - open modal in edit mode.
      collectionsList.addEventListener('click', function (e) {
        var editBtn = e.target.closest('.dam-collections__edit');
        if (!editBtn) {
          return;
        }

        e.preventDefault();
        e.stopPropagation();

        var collectionItem = editBtn.closest('.dam-collections__item');
        if (!collectionItem) {
          return;
        }

        var collectionId = collectionItem.dataset.collection;
        var currentName = collectionItem.querySelector('.dam-collections__name').textContent;

        // Open the collection edit modal.
        var modal = document.getElementById('dam-collection-modal');
        var titleEl = document.getElementById('dam-collection-modal-title');
        var nameInput = document.getElementById('dam-collection-name');
        var collectionIdInput = document.getElementById('dam-collection-modal-id');
        var modeInput = document.getElementById('dam-collection-modal-mode');
        var deleteBtn = document.getElementById('dam-collection-modal-delete');

        titleEl.textContent = 'Edit Collection';
        nameInput.value = currentName;
        collectionIdInput.value = collectionId;
        modeInput.value = 'edit';
        deleteBtn.style.display = '';

        modal.classList.add('is-open');
        nameInput.focus();
        nameInput.select();
      });

      // Clear collection selection when folder is clicked.
      if (foldersList) {
        foldersList.addEventListener('click', function (e) {
          var btn = e.target.closest('.dam-folders__btn');
          if (!btn) {
            return;
          }

          // Clear collection selection.
          collectionsList.querySelectorAll('.dam-collections__item').forEach(function (i) {
            i.classList.remove('dam-collections__item--active');
          });
          if (collectionInput) {
            collectionInput.value = '';
          }
        });
      }
    },

    initCollectionModal: function (context) {
      var modal = context.querySelector ? context.querySelector('#dam-collection-modal') : null;

      if (!modal || modal.dataset.modalInitialized) {
        return;
      }
      modal.dataset.modalInitialized = 'true';

      var backdrop = modal.querySelector('.dam-collection-modal__backdrop');
      var closeBtn = modal.querySelector('.dam-collection-modal__close');
      var cancelBtn = modal.querySelector('.dam-collection-modal__cancel');
      var saveBtn = modal.querySelector('.dam-collection-modal__save');
      var deleteBtn = document.getElementById('dam-collection-modal-delete');
      var nameInput = document.getElementById('dam-collection-name');
      var collectionIdInput = document.getElementById('dam-collection-modal-id');
      var modeInput = document.getElementById('dam-collection-modal-mode');

      function closeModal() {
        modal.classList.remove('is-open');
      }

      function saveCollection() {
        var mode = modeInput.value;
        var collectionId = collectionIdInput.value;
        var newName = nameInput.value.trim();

        if (!newName) {
          nameInput.focus();
          return;
        }

        saveBtn.disabled = true;
        saveBtn.textContent = 'Saving...';

        var url = mode === 'create' ? '/nodehive/admin/dam/collection/create' : '/nodehive/admin/dam/collection/rename';
        var body = mode === 'create'
          ? { name: newName }
          : { collection_id: collectionId, name: newName };

        fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(body)
        })
          .then(function (response) {
            return response.json();
          })
          .then(function (result) {
            saveBtn.disabled = false;
            saveBtn.textContent = 'Save';

            if (result.success) {
              closeModal();
              // Reload page to reflect changes.
              window.location.reload();
            }
          })
          .catch(function () {
            saveBtn.disabled = false;
            saveBtn.textContent = 'Save';
          });
      }

      function deleteCollection() {
        var collectionId = collectionIdInput.value;
        var collectionName = nameInput.value;

        if (!confirm('Are you sure you want to delete the collection "' + collectionName + '"? Media items will not be deleted, only removed from this collection.')) {
          return;
        }

        deleteBtn.disabled = true;
        deleteBtn.textContent = 'Deleting...';

        fetch('/nodehive/admin/dam/collection/delete', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ collection_id: collectionId })
        })
          .then(function (response) {
            return response.json();
          })
          .then(function (result) {
            deleteBtn.disabled = false;
            deleteBtn.textContent = 'Delete';

            if (result.success) {
              closeModal();
              // Reload page to reflect changes.
              window.location.reload();
            }
          })
          .catch(function () {
            deleteBtn.disabled = false;
            deleteBtn.textContent = 'Delete';
          });
      }

      backdrop.addEventListener('click', closeModal);
      closeBtn.addEventListener('click', closeModal);
      cancelBtn.addEventListener('click', closeModal);
      saveBtn.addEventListener('click', saveCollection);
      deleteBtn.addEventListener('click', deleteCollection);

      nameInput.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          saveCollection();
        }
        if (e.key === 'Escape') {
          closeModal();
        }
      });

      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && modal.classList.contains('is-open')) {
          closeModal();
        }
      });
    },

    /**
     * Initialize drag and drop functionality for media items.
     *
     * Architecture:
     * - Media items (.dam-item) are draggable sources
     * - Folders (.dam-folders__item) and Collections (.dam-collections__item) are drop targets
     * - Uses document-level event delegation for reliability
     * - All handlers are registered once on document, not on individual elements
     */
    initDragDrop: function (context) {
      // Only initialize once globally
      if (window.damDragDropInitialized) {
        return;
      }
      window.damDragDropInitialized = true;

      // Drag state stored globally
      var dragState = {
        mediaId: null,
        item: null
      };

      // ===================
      // DRAG SOURCE HANDLERS
      // ===================

      // Handle drag start on media items
      document.addEventListener('dragstart', function (e) {
        var mediaItem = e.target.closest('.dam-item');
        if (!mediaItem) return;

        dragState.mediaId = mediaItem.dataset.mediaId;
        dragState.item = mediaItem;
        mediaItem.classList.add('is-dragging');

        // Required for Firefox
        e.dataTransfer.setData('text/plain', dragState.mediaId);
        e.dataTransfer.effectAllowed = 'copyMove';
      });

      // Handle drag end - cleanup
      document.addEventListener('dragend', function (e) {
        var mediaItem = e.target.closest('.dam-item');
        if (mediaItem) {
          mediaItem.classList.remove('is-dragging');
        }

        // Clear all hover states
        document.querySelectorAll('.is-dragover').forEach(function (el) {
          el.classList.remove('is-dragover');
        });

        // Delay clearing state to let drop handler finish
        setTimeout(function () {
          dragState.mediaId = null;
          dragState.item = null;
        }, 50);
      });

      // ===================
      // DROP TARGET: FOLDERS
      // ===================

      var foldersList = document.getElementById('dam-folders');
      if (foldersList) {
        foldersList.addEventListener('dragover', function (e) {
          if (!dragState.mediaId) return;

          var folderItem = e.target.closest('.dam-folders__item');
          if (!folderItem) return;

          e.preventDefault();
          e.dataTransfer.dropEffect = 'move';

          // Update hover state
          foldersList.querySelectorAll('.dam-folders__item.is-dragover').forEach(function (el) {
            if (el !== folderItem) el.classList.remove('is-dragover');
          });
          folderItem.classList.add('is-dragover');
        });

        foldersList.addEventListener('dragleave', function (e) {
          var folderItem = e.target.closest('.dam-folders__item');
          if (folderItem && !folderItem.contains(e.relatedTarget)) {
            folderItem.classList.remove('is-dragover');
          }
        });

        foldersList.addEventListener('drop', function (e) {
          var folderItem = e.target.closest('.dam-folders__item');
          if (!folderItem || !dragState.mediaId) return;

          e.preventDefault();
          folderItem.classList.remove('is-dragover');

          var folderId = folderItem.dataset.folder;
          var mediaId = dragState.mediaId;
          var draggedItem = dragState.item;

          // API call to move media to folder
          fetch('/nodehive/admin/dam/folder/move', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ media_ids: [mediaId], folder_id: folderId })
          })
            .then(function (r) { return r.json(); })
            .then(function (result) {
              if (result.success) {
                // Visual feedback
                folderItem.classList.add('is-drop-success');
                setTimeout(function () { folderItem.classList.remove('is-drop-success'); }, 500);

                // Remove item from grid if viewing a different folder
                var folderInput = document.getElementById('dam-folder-input');
                if (folderInput && folderInput.value && folderInput.value !== folderId && draggedItem) {
                  draggedItem.remove();
                }
              }
            })
            .catch(function (err) { console.error('Move to folder failed:', err); });
        });
      }

      // ======================
      // DROP TARGET: COLLECTIONS
      // ======================

      var collectionsList = document.getElementById('dam-collections');
      if (collectionsList) {
        collectionsList.addEventListener('dragover', function (e) {
          if (!dragState.mediaId) return;

          var collectionItem = e.target.closest('.dam-collections__item');
          if (!collectionItem) return;

          e.preventDefault();
          e.dataTransfer.dropEffect = 'copy';

          // Update hover state
          collectionsList.querySelectorAll('.dam-collections__item.is-dragover').forEach(function (el) {
            if (el !== collectionItem) el.classList.remove('is-dragover');
          });
          collectionItem.classList.add('is-dragover');
        });

        collectionsList.addEventListener('dragleave', function (e) {
          var collectionItem = e.target.closest('.dam-collections__item');
          if (collectionItem && !collectionItem.contains(e.relatedTarget)) {
            collectionItem.classList.remove('is-dragover');
          }
        });

        collectionsList.addEventListener('drop', function (e) {
          var collectionItem = e.target.closest('.dam-collections__item');
          if (!collectionItem || !dragState.mediaId) return;

          e.preventDefault();
          collectionItem.classList.remove('is-dragover');

          var collectionId = collectionItem.dataset.collection;
          var mediaId = dragState.mediaId;

          // API call to add media to collection
          var collectionName = collectionItem.querySelector('.dam-collections__name').textContent;
          fetch('/nodehive/admin/dam/collection/add', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ media_ids: [mediaId], collection_id: collectionId })
          })
            .then(function (r) { return r.json(); })
            .then(function (result) {
              if (result.success) {
                // Visual feedback
                collectionItem.classList.add('is-drop-success');
                setTimeout(function () { collectionItem.classList.remove('is-drop-success'); }, 500);

                // Show toast notification
                Drupal.behaviors.nodehiveDam.showToast('Added to "' + collectionName + '"');
              }
            })
            .catch(function (err) { console.error('Add to collection failed:', err); });
        });
      }
    },

    initBulkSelection: function (context) {
      // Only initialize once on document level.
      if (context !== document) {
        return;
      }

      var bulkBar = document.getElementById('dam-bulk-bar');
      var bulkCount = document.getElementById('dam-bulk-count');
      var bulkMoveBtn = document.getElementById('dam-bulk-move');
      var bulkCollectionBtn = document.getElementById('dam-bulk-collection');
      var bulkRemoveCollectionBtn = document.getElementById('dam-bulk-remove-collection');
      var bulkDownloadBtn = document.getElementById('dam-bulk-download');
      var bulkClearBtn = document.getElementById('dam-bulk-clear');
      var collectionInput = document.getElementById('dam-collection-input');

      var moveModal = document.getElementById('dam-bulk-move-modal');
      var moveModalBackdrop = moveModal ? moveModal.querySelector('.dam-bulk-modal__backdrop') : null;
      var moveModalClose = moveModal ? moveModal.querySelector('.dam-bulk-modal__close') : null;
      var moveModalCancel = moveModal ? moveModal.querySelector('.dam-bulk-modal__cancel') : null;
      var moveModalConfirm = document.getElementById('dam-bulk-move-confirm');
      var moveModalCount = document.getElementById('dam-bulk-move-count');
      var moveModalFolder = document.getElementById('dam-bulk-move-folder');

      var collectionModal = document.getElementById('dam-bulk-collection-modal');
      var collectionModalBackdrop = collectionModal ? collectionModal.querySelector('.dam-bulk-modal__backdrop') : null;
      var collectionModalClose = collectionModal ? collectionModal.querySelector('.dam-bulk-modal__close') : null;
      var collectionModalCancel = collectionModal ? collectionModal.querySelector('.dam-bulk-modal__cancel') : null;
      var collectionModalConfirm = document.getElementById('dam-bulk-collection-confirm');
      var collectionModalCount = document.getElementById('dam-bulk-collection-count');
      var collectionModalSelect = document.getElementById('dam-bulk-collection-select');

      if (!bulkBar || bulkBar.dataset.bulkInitialized) {
        return;
      }
      bulkBar.dataset.bulkInitialized = 'true';

      // Track selected items.
      var selectedIds = new Set();

      // Show/hide remove from collection button based on current filter.
      function updateRemoveCollectionButton() {
        if (bulkRemoveCollectionBtn && collectionInput) {
          if (collectionInput.value && collectionInput.value !== '') {
            bulkRemoveCollectionBtn.style.display = '';
          } else {
            bulkRemoveCollectionBtn.style.display = 'none';
          }
        }
      }

      function updateBulkBar() {
        var count = selectedIds.size;
        bulkCount.textContent = count;
        updateRemoveCollectionButton();
        if (count > 0) {
          bulkBar.classList.add('is-visible');
        } else {
          bulkBar.classList.remove('is-visible');
        }
      }

      function clearSelection() {
        selectedIds.clear();
        document.querySelectorAll('.dam-item.is-selected').forEach(function (item) {
          item.classList.remove('is-selected');
          var checkbox = item.querySelector('.dam-item__select');
          if (checkbox) {
            checkbox.checked = false;
          }
        });
        updateBulkBar();
      }

      // Handle checkbox changes via event delegation.
      document.addEventListener('change', function (e) {
        var checkbox = e.target.closest('.dam-item__select');
        if (!checkbox) {
          return;
        }

        var item = checkbox.closest('.dam-item');
        var mediaId = checkbox.dataset.mediaId;

        if (checkbox.checked) {
          selectedIds.add(mediaId);
          item.classList.add('is-selected');
        } else {
          selectedIds.delete(mediaId);
          item.classList.remove('is-selected');
        }

        updateBulkBar();
      });

      // Prevent checkbox click from opening preview.
      document.addEventListener('click', function (e) {
        if (e.target.closest('.dam-item__checkbox')) {
          e.stopPropagation();
        }
      }, true);

      // Clear selection button.
      bulkClearBtn.addEventListener('click', clearSelection);

      // Move button - open modal.
      bulkMoveBtn.addEventListener('click', function () {
        moveModalCount.textContent = selectedIds.size;
        moveModal.classList.add('is-open');
      });

      // Move modal close handlers.
      function closeMoveModal() {
        moveModal.classList.remove('is-open');
      }

      moveModalBackdrop.addEventListener('click', closeMoveModal);
      moveModalClose.addEventListener('click', closeMoveModal);
      moveModalCancel.addEventListener('click', closeMoveModal);

      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && moveModal.classList.contains('is-open')) {
          closeMoveModal();
        }
      });

      // Move confirm.
      moveModalConfirm.addEventListener('click', function () {
        var folderId = moveModalFolder.value;
        var mediaIds = Array.from(selectedIds);

        moveModalConfirm.disabled = true;
        moveModalConfirm.textContent = 'Moving...';

        fetch('/nodehive/admin/dam/folder/move', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            media_ids: mediaIds,
            folder_id: folderId
          })
        })
          .then(function (response) {
            return response.json();
          })
          .then(function (result) {
            moveModalConfirm.disabled = false;
            moveModalConfirm.textContent = 'Move';

            if (result.success) {
              closeMoveModal();
              clearSelection();
              // Refresh the grid.
              var searchInput = document.querySelector('.dam-filters__input[name="search"]');
              if (searchInput) {
                htmx.trigger(searchInput, 'search');
              }
            }
          })
          .catch(function () {
            moveModalConfirm.disabled = false;
            moveModalConfirm.textContent = 'Move';
          });
      });

      // Download button - download as ZIP.
      bulkDownloadBtn.addEventListener('click', function () {
        var mediaIds = Array.from(selectedIds);
        if (mediaIds.length === 0) {
          return;
        }

        // Get current folder ID for filename.
        var folderInput = document.getElementById('dam-folder-input');
        var folderId = folderInput ? folderInput.value : '';

        bulkDownloadBtn.disabled = true;
        var originalText = bulkDownloadBtn.innerHTML;
        bulkDownloadBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg> Downloading...';

        fetch('/nodehive/admin/dam/download', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            media_ids: mediaIds,
            folder_id: folderId
          })
        })
          .then(function (response) {
            if (!response.ok) {
              throw new Error('Download failed');
            }
            // Extract filename from Content-Disposition header.
            var contentDisposition = response.headers.get('Content-Disposition');
            var filename = 'media-download.zip';
            if (contentDisposition) {
              var match = contentDisposition.match(/filename="(.+)"/);
              if (match && match[1]) {
                filename = match[1];
              }
            }
            return response.blob().then(function (blob) {
              return { blob: blob, filename: filename };
            });
          })
          .then(function (data) {
            // Create download link.
            var url = window.URL.createObjectURL(data.blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = data.filename;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            a.remove();

            bulkDownloadBtn.disabled = false;
            bulkDownloadBtn.innerHTML = originalText;
          })
          .catch(function (error) {
            console.error('Download failed:', error);
            bulkDownloadBtn.disabled = false;
            bulkDownloadBtn.innerHTML = originalText;
          });
      });

      // Collection button - open modal.
      if (bulkCollectionBtn && collectionModal) {
        var selectWrapper = document.getElementById('dam-bulk-collection-select-wrapper');
        var newCollectionWrapper = document.getElementById('dam-bulk-new-collection');
        var newCollectionInput = document.getElementById('dam-bulk-new-collection-name');
        var backToListBtn = document.getElementById('dam-bulk-collection-back');

        function showSelectMode() {
          selectWrapper.style.display = '';
          newCollectionWrapper.style.display = 'none';
          collectionModalConfirm.textContent = 'Add';
        }

        function showCreateMode() {
          selectWrapper.style.display = 'none';
          newCollectionWrapper.style.display = '';
          newCollectionInput.value = '';
          newCollectionInput.focus();
          collectionModalConfirm.textContent = 'Create & Add';
        }

        bulkCollectionBtn.addEventListener('click', function () {
          collectionModalCount.textContent = selectedIds.size;
          collectionModalSelect.value = '';
          showSelectMode();
          collectionModal.classList.add('is-open');
        });

        // Handle select change for "Create new" option.
        collectionModalSelect.addEventListener('change', function () {
          if (collectionModalSelect.value === '_new') {
            showCreateMode();
          }
        });

        // Back button to return to select.
        backToListBtn.addEventListener('click', function () {
          collectionModalSelect.value = '';
          showSelectMode();
        });

        // Collection modal close handlers.
        function closeCollectionModal() {
          collectionModal.classList.remove('is-open');
          showSelectMode();
        }

        collectionModalBackdrop.addEventListener('click', closeCollectionModal);
        collectionModalClose.addEventListener('click', closeCollectionModal);
        collectionModalCancel.addEventListener('click', closeCollectionModal);

        document.addEventListener('keydown', function (e) {
          if (e.key === 'Escape' && collectionModal.classList.contains('is-open')) {
            closeCollectionModal();
          }
        });

        // Handle enter key in new collection input.
        newCollectionInput.addEventListener('keydown', function (e) {
          if (e.key === 'Enter') {
            e.preventDefault();
            collectionModalConfirm.click();
          }
        });

        // Collection confirm.
        collectionModalConfirm.addEventListener('click', function () {
          var mediaIds = Array.from(selectedIds);
          var isCreateMode = newCollectionWrapper.style.display !== 'none';

          if (isCreateMode) {
            // Create new collection first, then add media.
            var newName = newCollectionInput.value.trim();
            if (!newName) {
              newCollectionInput.focus();
              return;
            }

            collectionModalConfirm.disabled = true;
            collectionModalConfirm.textContent = 'Creating...';

            fetch('/nodehive/admin/dam/collection/create', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ name: newName })
            })
              .then(function (response) {
                return response.json();
              })
              .then(function (result) {
                if (result.success && result.collection) {
                  // Now add media to the new collection.
                  collectionModalConfirm.textContent = 'Adding...';
                  return fetch('/nodehive/admin/dam/collection/add', {
                    method: 'POST',
                    headers: {
                      'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                      media_ids: mediaIds,
                      collection_id: result.collection.id
                    })
                  }).then(function (response) {
                    return response.json();
                  });
                } else {
                  throw new Error('Failed to create collection');
                }
              })
              .then(function (result) {
                collectionModalConfirm.disabled = false;
                collectionModalConfirm.textContent = 'Create & Add';

                if (result.success) {
                  closeCollectionModal();
                  clearSelection();
                  // Reload page to show new collection in sidebar.
                  window.location.reload();
                }
              })
              .catch(function () {
                collectionModalConfirm.disabled = false;
                collectionModalConfirm.textContent = 'Create & Add';
              });
          } else {
            // Existing collection selected.
            var collectionId = collectionModalSelect.value;
            if (!collectionId || collectionId === '_new') {
              collectionModalSelect.focus();
              return;
            }

            collectionModalConfirm.disabled = true;
            collectionModalConfirm.textContent = 'Adding...';

            fetch('/nodehive/admin/dam/collection/add', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                media_ids: mediaIds,
                collection_id: collectionId
              })
            })
              .then(function (response) {
                return response.json();
              })
              .then(function (result) {
                collectionModalConfirm.disabled = false;
                collectionModalConfirm.textContent = 'Add';

                if (result.success) {
                  closeCollectionModal();
                  clearSelection();
                  // Refresh the grid.
                  var searchInput = document.querySelector('.dam-filters__input[name="search"]');
                  if (searchInput) {
                    htmx.trigger(searchInput, 'search');
                  }
                }
              })
              .catch(function () {
                collectionModalConfirm.disabled = false;
                collectionModalConfirm.textContent = 'Add';
              });
          }
        });
      }

      // Remove from collection button - remove selected items from current collection.
      if (bulkRemoveCollectionBtn) {
        bulkRemoveCollectionBtn.addEventListener('click', function () {
          var currentCollectionId = collectionInput ? collectionInput.value : '';
          if (!currentCollectionId) {
            return;
          }

          var mediaIds = Array.from(selectedIds);
          var count = mediaIds.length;

          if (!confirm('Remove ' + count + ' item' + (count !== 1 ? 's' : '') + ' from this collection?')) {
            return;
          }

          bulkRemoveCollectionBtn.disabled = true;
          var originalText = bulkRemoveCollectionBtn.innerHTML;
          bulkRemoveCollectionBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg> Removing...';

          fetch('/nodehive/admin/dam/collection/remove', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              media_ids: mediaIds,
              collection_id: currentCollectionId
            })
          })
            .then(function (response) {
              return response.json();
            })
            .then(function (result) {
              bulkRemoveCollectionBtn.disabled = false;
              bulkRemoveCollectionBtn.innerHTML = originalText;

              if (result.success) {
                clearSelection();
                // Refresh the grid.
                var searchInput = document.querySelector('.dam-filters__input[name="search"]');
                if (searchInput) {
                  htmx.trigger(searchInput, 'search');
                }
              }
            })
            .catch(function () {
              bulkRemoveCollectionBtn.disabled = false;
              bulkRemoveCollectionBtn.innerHTML = originalText;
            });
        });
      }
    },

    initUrlHash: function (context) {
      // Only run once on document level.
      if (context !== document) {
        return;
      }

      // Only run once globally.
      if (initialGridLoadDone) {
        return;
      }
      initialGridLoadDone = true;

      var foldersList = document.getElementById('dam-folders');
      var collectionsList = document.getElementById('dam-collections');

      var hashData = this.parseUrlHash();

      // Update sidebar active states based on hash (inputs are already set by inline script).
      if (hashData && hashData.type === 'folder' && foldersList) {
        var folderItem = foldersList.querySelector('.dam-folders__item[data-folder="' + hashData.id + '"]');
        if (folderItem) {
          foldersList.querySelectorAll('.dam-folders__item').forEach(function (i) {
            i.classList.remove('dam-folders__item--active');
          });
          folderItem.classList.add('dam-folders__item--active');
        }
      } else if (hashData && hashData.type === 'collection' && collectionsList) {
        var collectionItem = collectionsList.querySelector('.dam-collections__item[data-collection="' + hashData.id + '"]');
        if (collectionItem) {
          collectionsList.querySelectorAll('.dam-collections__item').forEach(function (i) {
            i.classList.remove('dam-collections__item--active');
          });
          collectionItem.classList.add('dam-collections__item--active');

          // Clear folder selection in sidebar.
          if (foldersList) {
            foldersList.querySelectorAll('.dam-folders__item').forEach(function (i) {
              i.classList.remove('dam-folders__item--active');
            });
            var allMediaItem = foldersList.querySelector('.dam-folders__item[data-folder=""]');
            if (allMediaItem) {
              allMediaItem.classList.add('dam-folders__item--active');
            }
          }
        }
      }

      // Listen for hash changes (browser back/forward) - only add once.
      if (!window.damHashChangeListenerAdded) {
        window.damHashChangeListenerAdded = true;
        window.addEventListener('hashchange', function () {
          window.location.reload();
        });
      }
    }
  };

})(Drupal);
