/**
 * @file
 * DAM Media Widget JavaScript.
 */

(function (Drupal, drupalSettings) {
  'use strict';

  // Store widget state.
  var widgetState = {
    activeField: null,
    selectedIds: [],
    cardinality: -1,
    allowedBundles: [],
    modal: null
  };

  Drupal.behaviors.damWidget = {
    attach: function (context) {
      this.initWidgets(context);
      this.initModal(context);
    },

    /**
     * Initialize all DAM widgets on the page.
     */
    initWidgets: function (context) {
      var self = this;
      var widgets = context.querySelectorAll ? context.querySelectorAll('.dam-widget') : [];

      widgets.forEach(function (widget) {
        if (widget.dataset.widgetInitialized) return;
        widget.dataset.widgetInitialized = 'true';

        var fieldName = widget.dataset.fieldName;
        var browseBtn = widget.querySelector('.dam-widget__browse');
        var clearBtn = widget.querySelector('.dam-widget__clear');
        var input = widget.querySelector('.dam-widget__input');

        // Browse button opens the modal.
        if (browseBtn) {
          browseBtn.addEventListener('click', function (e) {
            e.preventDefault();
            self.openModal(fieldName, widget);
          });
        }

        // Clear button removes all selections.
        if (clearBtn) {
          clearBtn.addEventListener('click', function (e) {
            e.preventDefault();
            self.clearSelection(widget);
          });
        }

        // Remove individual items.
        widget.addEventListener('click', function (e) {
          var removeBtn = e.target.closest('.dam-widget__remove');
          if (removeBtn) {
            e.preventDefault();
            var item = removeBtn.closest('.dam-widget__item');
            if (item) {
              self.removeItem(widget, item.dataset.mediaId);
            }
          }
        });
      });
    },

    /**
     * Initialize the modal (only once).
     */
    initModal: function (context) {
      if (context !== document) return;
      if (widgetState.modal) return;

      // Create modal container if not exists.
      var modal = document.getElementById('dam-widget-modal');
      if (!modal) {
        // Fetch modal HTML from server.
        this.loadModalHtml();
        return;
      }

      this.setupModal(modal);
    },

    /**
     * Load modal HTML from server.
     */
    loadModalHtml: function () {
      var self = this;
      fetch(Drupal.url('admin/dam/widget/modal'))
        .then(function (r) { return r.text(); })
        .then(function (html) {
          var container = document.createElement('div');
          container.innerHTML = html;
          document.body.appendChild(container.firstElementChild);
          self.setupModal(document.getElementById('dam-widget-modal'));
        })
        .catch(function (err) {
          console.error('Failed to load DAM widget modal:', err);
        });
    },

    /**
     * Set up modal event handlers.
     */
    setupModal: function (modal) {
      var self = this;
      widgetState.modal = modal;

      var backdrop = modal.querySelector('.dam-widget-modal__backdrop');
      var closeBtn = modal.querySelector('.dam-widget-modal__close');
      var cancelBtn = modal.querySelector('.dam-widget-modal__cancel');
      var confirmBtn = modal.querySelector('.dam-widget-modal__confirm');
      var searchInput = modal.querySelector('#dam-widget-search');
      var typeFilter = modal.querySelector('#dam-widget-type-filter');
      var foldersContainer = modal.querySelector('#dam-widget-folders');
      var collectionsContainer = modal.querySelector('#dam-widget-collections');
      var grid = modal.querySelector('#dam-widget-grid');

      // Close handlers.
      backdrop.addEventListener('click', function () { self.closeModal(); });
      closeBtn.addEventListener('click', function () { self.closeModal(); });
      cancelBtn.addEventListener('click', function () { self.closeModal(); });

      // Confirm selection.
      confirmBtn.addEventListener('click', function () { self.confirmSelection(); });

      // Search with debounce.
      var searchTimeout;
      searchInput.addEventListener('input', function () {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function () {
          self.loadGrid();
        }, 300);
      });

      // Type filter.
      typeFilter.addEventListener('change', function () {
        self.loadGrid();
      });

      // Folder selection.
      foldersContainer.addEventListener('click', function (e) {
        var folderBtn = e.target.closest('button');
        if (!folderBtn) return;
        var folderItem = folderBtn.closest('.dam-widget-modal__folder');
        if (!folderItem) return;

        // Clear other selections.
        foldersContainer.querySelectorAll('.dam-widget-modal__folder').forEach(function (f) {
          f.classList.remove('dam-widget-modal__folder--active');
        });
        collectionsContainer.querySelectorAll('.dam-widget-modal__collection').forEach(function (c) {
          c.classList.remove('dam-widget-modal__collection--active');
        });

        folderItem.classList.add('dam-widget-modal__folder--active');
        self.loadGrid();
      });

      // Collection selection.
      collectionsContainer.addEventListener('click', function (e) {
        var collectionBtn = e.target.closest('button');
        if (!collectionBtn) return;
        var collectionItem = collectionBtn.closest('.dam-widget-modal__collection');
        if (!collectionItem) return;

        // Clear other selections.
        foldersContainer.querySelectorAll('.dam-widget-modal__folder').forEach(function (f) {
          f.classList.remove('dam-widget-modal__folder--active');
        });
        collectionsContainer.querySelectorAll('.dam-widget-modal__collection').forEach(function (c) {
          c.classList.remove('dam-widget-modal__collection--active');
        });

        collectionItem.classList.add('dam-widget-modal__collection--active');
        self.loadGrid();
      });

      // Grid item selection.
      grid.addEventListener('click', function (e) {
        var item = e.target.closest('.dam-widget-modal__item');
        if (!item) return;

        var mediaId = item.dataset.mediaId;
        self.toggleItemSelection(item, mediaId);
      });

      // Keyboard handling.
      modal.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
          self.closeModal();
        }
      });

      // Upload handling.
      var uploadInput = modal.querySelector('#dam-widget-upload-input');
      if (uploadInput) {
        uploadInput.addEventListener('change', function (e) {
          if (e.target.files && e.target.files.length > 0) {
            self.uploadFiles(e.target.files);
            e.target.value = '';
          }
        });
      }

      // Drag and drop upload on the grid area.
      var mainArea = modal.querySelector('.dam-widget-modal__main');
      mainArea.addEventListener('dragover', function (e) {
        e.preventDefault();
        e.stopPropagation();
        mainArea.classList.add('is-dragover');
      });

      mainArea.addEventListener('dragleave', function (e) {
        e.preventDefault();
        e.stopPropagation();
        mainArea.classList.remove('is-dragover');
      });

      mainArea.addEventListener('drop', function (e) {
        e.preventDefault();
        e.stopPropagation();
        mainArea.classList.remove('is-dragover');
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
          self.uploadFiles(e.dataTransfer.files);
        }
      });
    },

    /**
     * Upload files to the DAM.
     */
    uploadFiles: function (files) {
      var self = this;
      var modal = widgetState.modal;
      var grid = modal.querySelector('#dam-widget-grid');
      var uploadQueue = Array.from(files);
      var uploadedCount = 0;
      var totalCount = uploadQueue.length;

      // Show upload progress.
      var progressHtml = '<div class="dam-widget-modal__upload-progress">';
      progressHtml += '<div class="dam-widget-modal__spinner"></div>';
      progressHtml += '<p>Uploading <span id="dam-widget-upload-count">0</span> of ' + totalCount + ' files...</p>';
      progressHtml += '</div>';

      // Prepend progress indicator.
      var existingContent = grid.innerHTML;
      grid.innerHTML = progressHtml + existingContent;

      // Upload files sequentially.
      function uploadNext() {
        if (uploadQueue.length === 0) {
          // All done, reload grid.
          self.loadGrid();
          return;
        }

        var file = uploadQueue.shift();
        var formData = new FormData();
        formData.append('file', file);

        // Get active folder if any.
        var activeFolder = modal.querySelector('.dam-widget-modal__folder--active');
        if (activeFolder && activeFolder.dataset.folder && activeFolder.dataset.folder !== '_none') {
          formData.append('folder', activeFolder.dataset.folder);
        }

        fetch(Drupal.url('nodehive/admin/dam/upload'), {
          method: 'POST',
          body: formData
        })
          .then(function (response) {
            if (!response.ok) {
              throw new Error('Upload failed');
            }
            return response.text();
          })
          .then(function () {
            uploadedCount++;
            var countEl = document.getElementById('dam-widget-upload-count');
            if (countEl) {
              countEl.textContent = uploadedCount;
            }
            uploadNext();
          })
          .catch(function (err) {
            console.error('Failed to upload file:', file.name, err);
            uploadedCount++;
            uploadNext();
          });
      }

      uploadNext();
    },

    /**
     * Open the modal for a specific field.
     */
    openModal: function (fieldName, widget) {
      var self = this;
      var settings = drupalSettings.damWidget && drupalSettings.damWidget[fieldName];
      if (!settings) {
        console.error('No settings found for field:', fieldName);
        return;
      }

      widgetState.activeField = fieldName;
      widgetState.cardinality = settings.cardinality;
      widgetState.allowedBundles = settings.allowedBundles || [];
      widgetState.widget = widget;

      // Get current selections from the widget.
      var input = widget.querySelector('.dam-widget__input');
      var currentIds = input.value ? input.value.split(',').filter(Boolean) : [];
      widgetState.selectedIds = currentIds.map(function (id) { return parseInt(id, 10); });

      // Update modal title based on cardinality.
      var modal = widgetState.modal;
      if (!modal) {
        // Wait for modal to load.
        setTimeout(function () { self.openModal(fieldName, widget); }, 100);
        return;
      }

      var title = modal.querySelector('.dam-widget-modal__title');
      if (widgetState.cardinality === 1) {
        title.textContent = 'Select Media';
      } else {
        title.textContent = 'Select Media';
      }

      // Load folders and collections, then load grid.
      this.loadFilters().then(function () {
        self.loadGrid();
      });

      modal.classList.add('is-open');
      modal.querySelector('#dam-widget-search').focus();

      this.updateSelectionCount();
    },

    /**
     * Close the modal.
     */
    closeModal: function () {
      if (widgetState.modal) {
        widgetState.modal.classList.remove('is-open');
      }
      widgetState.activeField = null;
      widgetState.selectedIds = [];
    },

    /**
     * Load folders and collections for filters.
     */
    loadFilters: function () {
      var self = this;
      var params = new URLSearchParams();
      if (widgetState.allowedBundles.length > 0) {
        params.append('bundles', widgetState.allowedBundles.join(','));
      }
      return fetch(Drupal.url('admin/dam/widget/filters') + '?' + params.toString())
        .then(function (r) { return r.json(); })
        .then(function (data) {
          self.renderFilters(data);
        })
        .catch(function (err) {
          console.error('Failed to load filters:', err);
        });
    },

    /**
     * Render folders and collections in the sidebar.
     */
    renderFilters: function (data) {
      var modal = widgetState.modal;
      var foldersContainer = modal.querySelector('#dam-widget-folders');
      var collectionsContainer = modal.querySelector('#dam-widget-collections');
      var typeFilter = modal.querySelector('#dam-widget-type-filter');

      // Render folders.
      var foldersHtml = '<li class="dam-widget-modal__folder dam-widget-modal__folder--active" data-folder=""><button type="button">All Media</button></li>';
      foldersHtml += '<li class="dam-widget-modal__folder" data-folder="_none"><button type="button">Unfiled</button></li>';
      if (data.folders) {
        data.folders.forEach(function (folder) {
          var indent = '—'.repeat(folder.depth);
          foldersHtml += '<li class="dam-widget-modal__folder" data-folder="' + folder.id + '"><button type="button">' + indent + (folder.depth > 0 ? ' ' : '') + self.escapeHtml(folder.name) + '</button></li>';
        });
      }
      foldersContainer.innerHTML = foldersHtml;

      // Render collections.
      var collectionsHtml = '';
      if (data.collections && data.collections.length > 0) {
        data.collections.forEach(function (collection) {
          collectionsHtml += '<li class="dam-widget-modal__collection" data-collection="' + collection.id + '"><button type="button">' + self.escapeHtml(collection.name) + '</button></li>';
        });
      } else {
        collectionsHtml = '<li class="dam-widget-modal__empty">No collections</li>';
      }
      collectionsContainer.innerHTML = collectionsHtml;

      // Render media types.
      var typesHtml = '<option value="">All types</option>';
      if (data.media_types) {
        Object.keys(data.media_types).forEach(function (id) {
          typesHtml += '<option value="' + id + '">' + self.escapeHtml(data.media_types[id]) + '</option>';
        });
      }
      typeFilter.innerHTML = typesHtml;
    },

    /**
     * Load media grid.
     */
    loadGrid: function () {
      var self = this;
      var modal = widgetState.modal;
      var grid = modal.querySelector('#dam-widget-grid');
      var search = modal.querySelector('#dam-widget-search').value;
      var type = modal.querySelector('#dam-widget-type-filter').value;

      // Get active folder/collection.
      var folder = '';
      var collection = '';
      var activeFolder = modal.querySelector('.dam-widget-modal__folder--active');
      var activeCollection = modal.querySelector('.dam-widget-modal__collection--active');

      if (activeFolder) {
        folder = activeFolder.dataset.folder;
      }
      if (activeCollection) {
        collection = activeCollection.dataset.collection;
      }

      // Build query string.
      var params = new URLSearchParams();
      if (search) params.append('search', search);
      if (type) params.append('type', type);
      if (folder) params.append('folder', folder);
      if (collection) params.append('collection', collection);
      if (widgetState.allowedBundles.length > 0) {
        params.append('bundles', widgetState.allowedBundles.join(','));
      }
      params.append('widget', '1');

      grid.innerHTML = '<div class="dam-widget-modal__loading"><div class="dam-widget-modal__spinner"></div><p>Loading media...</p></div>';

      fetch(Drupal.url('admin/dam/widget/grid') + '?' + params.toString())
        .then(function (r) { return r.json(); })
        .then(function (data) {
          self.renderGrid(data);
        })
        .catch(function (err) {
          console.error('Failed to load grid:', err);
          grid.innerHTML = '<p class="dam-widget-modal__error">Failed to load media</p>';
        });
    },

    /**
     * Render media grid.
     */
    renderGrid: function (data) {
      var self = this;
      var modal = widgetState.modal;
      var grid = modal.querySelector('#dam-widget-grid');

      if (!data.items || data.items.length === 0) {
        grid.innerHTML = '<p class="dam-widget-modal__empty">No media found</p>';
        return;
      }

      var html = '<div class="dam-widget-modal__items">';
      data.items.forEach(function (item) {
        var isSelected = widgetState.selectedIds.indexOf(item.id) !== -1;
        var selectedClass = isSelected ? ' is-selected' : '';

        html += '<div class="dam-widget-modal__item' + selectedClass + '" data-media-id="' + item.id + '">';
        if (item.thumbnail) {
          html += '<img src="' + item.thumbnail + '" alt="" class="dam-widget-modal__thumb">';
        } else {
          html += '<span class="dam-widget-modal__icon">' + self.getMediaIcon(item.bundle) + '</span>';
        }
        html += '<span class="dam-widget-modal__name">' + self.escapeHtml(item.name) + '</span>';
        html += '<span class="dam-widget-modal__check"></span>';
        html += '</div>';
      });
      html += '</div>';

      grid.innerHTML = html;
    },

    /**
     * Toggle item selection.
     */
    toggleItemSelection: function (item, mediaId) {
      mediaId = parseInt(mediaId, 10);
      var index = widgetState.selectedIds.indexOf(mediaId);

      if (index !== -1) {
        // Deselect.
        widgetState.selectedIds.splice(index, 1);
        item.classList.remove('is-selected');
      } else {
        // Check cardinality.
        if (widgetState.cardinality === 1) {
          // Single selection - clear others.
          widgetState.selectedIds = [mediaId];
          widgetState.modal.querySelectorAll('.dam-widget-modal__item.is-selected').forEach(function (el) {
            el.classList.remove('is-selected');
          });
        } else if (widgetState.cardinality > 0 && widgetState.selectedIds.length >= widgetState.cardinality) {
          // Max selections reached.
          Drupal.behaviors.nodehiveDam.showToast('Maximum ' + widgetState.cardinality + ' items allowed');
          return;
        } else {
          widgetState.selectedIds.push(mediaId);
        }
        item.classList.add('is-selected');
      }

      this.updateSelectionCount();
    },

    /**
     * Update selection count display.
     */
    updateSelectionCount: function () {
      var modal = widgetState.modal;
      var countEl = modal.querySelector('#dam-widget-selection-count');
      var confirmBtn = modal.querySelector('.dam-widget-modal__confirm');

      countEl.textContent = widgetState.selectedIds.length;
      confirmBtn.disabled = widgetState.selectedIds.length === 0;
    },

    /**
     * Confirm selection and update widget.
     */
    confirmSelection: function () {
      var self = this;
      var widget = widgetState.widget;
      if (!widget) return;

      var input = widget.querySelector('.dam-widget__input');
      var selectedContainer = widget.querySelector('.dam-widget__selected');

      // Update hidden input.
      input.value = widgetState.selectedIds.join(',');

      // Fetch media details and update preview.
      if (widgetState.selectedIds.length > 0) {
        fetch(Drupal.url('admin/dam/widget/preview') + '?ids=' + widgetState.selectedIds.join(','))
          .then(function (r) { return r.json(); })
          .then(function (data) {
            self.renderWidgetPreviews(widget, data.items);
            self.closeModal();
          })
          .catch(function (err) {
            console.error('Failed to load previews:', err);
            self.closeModal();
          });
      } else {
        selectedContainer.innerHTML = '';
        self.closeModal();
      }

      // Show/hide clear button.
      var clearBtn = widget.querySelector('.dam-widget__clear');
      if (clearBtn) {
        clearBtn.style.display = widgetState.selectedIds.length > 0 ? '' : 'none';
      }
    },

    /**
     * Render widget previews (grid-style like DAM).
     */
    renderWidgetPreviews: function (widget, items) {
      var self = this;
      var selectedContainer = widget.querySelector('.dam-widget__selected');
      var html = '';

      items.forEach(function (item) {
        html += '<div class="dam-widget__item" data-media-id="' + item.id + '">';
        html += '<div class="dam-widget__thumb-wrapper">';
        if (item.thumbnail) {
          html += '<img src="' + item.thumbnail + '" alt="" class="dam-widget__thumbnail">';
        } else {
          html += '<span class="dam-widget__icon">' + self.getMediaIcon(item.bundle) + '</span>';
        }
        html += '</div>';
        html += '<button type="button" class="dam-widget__remove" aria-label="Remove">×</button>';
        html += '<div class="dam-widget__info">';
        html += '<span class="dam-widget__name" title="' + self.escapeHtml(item.name) + '">' + self.escapeHtml(item.name) + '</span>';
        html += '<span class="dam-widget__meta">' + self.escapeHtml(item.bundle_label || item.bundle) + '</span>';
        html += '</div>';
        html += '</div>';
      });

      selectedContainer.innerHTML = html;
    },

    /**
     * Clear all selections from widget.
     */
    clearSelection: function (widget) {
      var input = widget.querySelector('.dam-widget__input');
      var selectedContainer = widget.querySelector('.dam-widget__selected');
      var clearBtn = widget.querySelector('.dam-widget__clear');

      input.value = '';
      selectedContainer.innerHTML = '';
      if (clearBtn) {
        clearBtn.style.display = 'none';
      }
    },

    /**
     * Remove a single item from widget.
     */
    removeItem: function (widget, mediaId) {
      var input = widget.querySelector('.dam-widget__input');
      var item = widget.querySelector('.dam-widget__item[data-media-id="' + mediaId + '"]');

      // Remove from input value.
      var ids = input.value ? input.value.split(',').filter(Boolean) : [];
      ids = ids.filter(function (id) { return id !== mediaId; });
      input.value = ids.join(',');

      // Remove from DOM.
      if (item) {
        item.remove();
      }

      // Hide clear button if no items left.
      if (ids.length === 0) {
        var clearBtn = widget.querySelector('.dam-widget__clear');
        if (clearBtn) {
          clearBtn.style.display = 'none';
        }
      }
    },

    /**
     * Get icon for media type.
     */
    getMediaIcon: function (bundle) {
      var icons = {
        'image': '🖼️',
        'video': '🎬',
        'audio': '🎵',
        'document': '📄',
        'file': '📎',
        'remote_video': '🎬'
      };
      return icons[bundle] || '📄';
    },

    /**
     * Escape HTML.
     */
    escapeHtml: function (str) {
      var div = document.createElement('div');
      div.textContent = str;
      return div.innerHTML;
    }
  };

  // Helper for escapeHtml in renderFilters context.
  var self = Drupal.behaviors.damWidget;

})(Drupal, drupalSettings);
