/**
 * @file
 * Content X behaviors.
 */

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

  const STORAGE_KEY = 'contentXViewPreference';
  const LANG_STORAGE_KEY = 'contentXLangPreference';

  /**
   * Content X initialization.
   */
  Drupal.behaviors.contentX = {
    attach: function (context, settings) {
      // Initialize view switcher
      this.initViewSwitcher(context);

      // Initialize language switcher
      this.initLangSwitcher(context);

      // Initialize status switcher
      this.initStatusSwitcher(context);

      // Initialize author select
      this.initAuthorSelect(context);

      // Initialize space select
      this.initSpaceSelect(context);

      // Initialize limit select
      this.initLimitSelect(context);

      // Initialize filter links
      this.initFilterLinks(context);

      // Initialize htmx events
      this.initHtmxEvents(context);

      // Initialize quick add modal
      this.initQuickAddModal(context);
    },

    /**
     * Initialize view switcher functionality.
     */
    initViewSwitcher: function (context) {
      const viewButtons = once('view-switcher-init', '.content-x-view-btn', context);

      if (viewButtons.length === 0) return;

      // Restore saved view preference on page load
      const savedView = localStorage.getItem(STORAGE_KEY) || 'dense';
      this.setView(savedView);

      // Handle view button clicks
      viewButtons.forEach(function (button) {
        button.addEventListener('click', function (e) {
          e.preventDefault();
          const view = this.getAttribute('data-view');
          Drupal.behaviors.contentX.setView(view);
          localStorage.setItem(STORAGE_KEY, view);
        });
      });
    },

    /**
     * Set the active view (list, grid, or dense).
     */
    setView: function (view) {
      const listWrapper = document.getElementById('content-x-list-wrapper');
      const gridWrapper = document.getElementById('content-x-grid-wrapper');
      const denseWrapper = document.getElementById('content-x-dense-wrapper');
      const hiddenViewInput = document.getElementById('hidden-view');
      const viewButtons = document.querySelectorAll('.content-x-view-btn');

      // Hide all wrappers first
      if (listWrapper) listWrapper.classList.add('is-hidden');
      if (gridWrapper) gridWrapper.classList.add('is-hidden');
      if (denseWrapper) denseWrapper.classList.add('is-hidden');

      // Show the selected view
      if (view === 'grid' && gridWrapper) {
        gridWrapper.classList.remove('is-hidden');
      } else if (view === 'dense' && denseWrapper) {
        denseWrapper.classList.remove('is-hidden');
      } else if (listWrapper) {
        listWrapper.classList.remove('is-hidden');
      }

      // Update hidden input for htmx requests
      if (hiddenViewInput) {
        hiddenViewInput.value = view;
      }

      // Update button states
      viewButtons.forEach(function (btn) {
        if (btn.getAttribute('data-view') === view) {
          btn.classList.add('is-active');
        } else {
          btn.classList.remove('is-active');
        }
      });
    },

    /**
     * Initialize language switcher functionality.
     */
    initLangSwitcher: function (context) {
      const langButtons = once('lang-switcher-init', '.content-x-lang-btn', context);

      if (langButtons.length === 0) return;

      // Handle language button clicks
      langButtons.forEach(function (button) {
        button.addEventListener('click', function (e) {
          const lang = this.getAttribute('data-lang');
          Drupal.behaviors.contentX.setLang(lang);
          localStorage.setItem(LANG_STORAGE_KEY, lang);
        });
      });
    },

    /**
     * Set the active display language.
     */
    setLang: function (lang) {
      const hiddenLangInput = document.getElementById('hidden-display-lang');
      const langButtons = document.querySelectorAll('.content-x-lang-btn');

      // Update hidden input for htmx requests
      if (hiddenLangInput) {
        hiddenLangInput.value = lang;
      }

      // Update button states
      langButtons.forEach(function (btn) {
        if (btn.getAttribute('data-lang') === lang) {
          btn.classList.add('is-active');
        } else {
          btn.classList.remove('is-active');
        }
      });
    },

    /**
     * Initialize status switcher functionality.
     */
    initStatusSwitcher: function (context) {
      const statusButtons = once('status-switcher-init', '.content-x-status-btn', context);

      if (statusButtons.length === 0) return;

      // Handle status button clicks
      statusButtons.forEach(function (button) {
        button.addEventListener('click', function (e) {
          const status = this.getAttribute('data-status');
          Drupal.behaviors.contentX.setStatus(status);
        });
      });
    },

    /**
     * Set the active status filter.
     */
    setStatus: function (status) {
      const hiddenStatusInput = document.getElementById('hidden-status');
      const statusButtons = document.querySelectorAll('.content-x-status-btn');

      // Update hidden input for htmx requests
      if (hiddenStatusInput) {
        hiddenStatusInput.value = status;
      }

      // Update button states
      statusButtons.forEach(function (btn) {
        if (btn.getAttribute('data-status') === status) {
          btn.classList.add('is-active');
        } else {
          btn.classList.remove('is-active');
        }
      });
    },

    /**
     * Initialize author select functionality.
     */
    initAuthorSelect: function (context) {
      const authorSelect = once('author-select-init', '#filter-author', context);

      if (authorSelect.length === 0) return;

      authorSelect.forEach(function (select) {
        select.addEventListener('change', function () {
          const hiddenInput = document.getElementById('hidden-author');
          if (hiddenInput) {
            hiddenInput.value = this.value;
          }
        });
      });
    },

    /**
     * Initialize space select functionality.
     */
    initSpaceSelect: function (context) {
      const spaceSelect = once('space-select-init', '#filter-space', context);

      if (spaceSelect.length === 0) return;

      // Apply initial filter based on current space selection
      const currentSelect = document.getElementById('filter-space');
      if (currentSelect && currentSelect.value) {
        this.filterContentTypesBySpace(currentSelect.value);
      }

      spaceSelect.forEach(function (select) {
        select.addEventListener('change', function () {
          const hiddenInput = document.getElementById('hidden-space');
          if (hiddenInput) {
            hiddenInput.value = this.value;
          }
          document.cookie = 'nodehive_content_space=' + encodeURIComponent(this.value) + ';path=/;max-age=31536000;SameSite=Lax';
          // Filter content types based on selected space
          Drupal.behaviors.contentX.filterContentTypesBySpace(this.value);
        });
      });
    },

    /**
     * Initialize limit select functionality.
     */
    initLimitSelect: function (context) {
      const limitSelect = once('limit-select-init', '#filter-limit', context);

      if (limitSelect.length === 0) return;

      limitSelect.forEach(function (select) {
        select.addEventListener('change', function () {
          const hiddenInput = document.getElementById('hidden-limit');
          if (hiddenInput) {
            hiddenInput.value = this.value;
          }
        });
      });
    },

    /**
     * Get the space to content types mapping.
     */
    getSpaceContentTypesMapping: function () {
      const dataElement = document.getElementById('space-content-types-data');
      if (!dataElement) {
        return {};
      }
      try {
        return JSON.parse(dataElement.textContent);
      } catch (e) {
        console.error('Content X: Failed to parse space content types data', e);
        return {};
      }
    },

    /**
     * Filter content types in sidebar based on selected space.
     */
    filterContentTypesBySpace: function (spaceId) {
      const mapping = this.getSpaceContentTypesMapping();
      const filterList = document.querySelector('.content-x-filter-list');

      if (!filterList) return;

      const typeItems = filterList.querySelectorAll('.content-x-filter-list-item');
      const hiddenTypeInput = document.getElementById('hidden-type');
      let currentTypeHidden = false;

      // If no space selected or space not in mapping, show all types
      if (!spaceId || !mapping[spaceId]) {
        typeItems.forEach(function (item) {
          item.classList.remove('is-space-hidden');
        });
        return;
      }

      const allowedTypes = mapping[spaceId];

      // If allowedTypes is empty array, all types are allowed
      if (allowedTypes.length === 0) {
        typeItems.forEach(function (item) {
          item.classList.remove('is-space-hidden');
        });
        return;
      }

      // Filter content types based on allowed list
      typeItems.forEach(function (item) {
        const link = item.querySelector('.content-x-filter-link');
        if (!link) return;

        const typeId = link.getAttribute('data-type');

        // Always show the "All" option (empty type)
        if (typeId === '' || typeId === null) {
          item.classList.remove('is-space-hidden');
          return;
        }

        // Check if this type is in the allowed list
        if (allowedTypes.includes(typeId)) {
          item.classList.remove('is-space-hidden');
        } else {
          item.classList.add('is-space-hidden');
          // Check if current selection is being hidden
          if (item.classList.contains('is-active')) {
            currentTypeHidden = true;
          }
        }
      });

      // If the currently selected type is now hidden, reset to "All"
      if (currentTypeHidden) {
        // Find and click the "All" option to reset
        const allOption = filterList.querySelector('.content-x-filter-list-item .content-x-filter-link[data-type=""]');
        if (allOption && hiddenTypeInput) {
          hiddenTypeInput.value = '';
          // Update active states
          typeItems.forEach(function (item) {
            item.classList.remove('is-active');
          });
          const allItem = allOption.closest('.content-x-filter-list-item');
          if (allItem) {
            allItem.classList.add('is-active');
          }
        }
      }
    },

    /**
     * Initialize filter link functionality.
     */
    initFilterLinks: function (context) {
      const filterLinks = once('filter-link-init', '.content-x-filter-link', context);

      filterLinks.forEach(function (link) {
        link.addEventListener('click', function (e) {
          // Let htmx handle the request, but update active states
          const listItem = this.closest('.content-x-filter-list-item');
          const list = this.closest('.content-x-filter-list');

          if (list && listItem) {
            // Remove active from siblings
            list.querySelectorAll('.content-x-filter-list-item').forEach(function (item) {
              item.classList.remove('is-active');
            });
            // Add active to clicked item
            listItem.classList.add('is-active');
          }

          // Update hidden input if this is a type filter
          const typeValue = this.getAttribute('data-type');
          if (typeValue !== null) {
            const hiddenInput = document.getElementById('hidden-type');
            if (hiddenInput) {
              hiddenInput.value = typeValue;
            }
          }

          // Update hidden input if this is a status filter
          const statusValue = this.getAttribute('data-status');
          if (statusValue !== null) {
            const hiddenInput = document.getElementById('hidden-status');
            if (hiddenInput) {
              hiddenInput.value = statusValue;
            }
          }

          // Update hidden input if this is an author filter
          const authorValue = this.getAttribute('data-author');
          if (authorValue !== null) {
            const hiddenInput = document.getElementById('hidden-author');
            if (hiddenInput) {
              hiddenInput.value = authorValue;
            }
          }

          // Update hidden input if this is a space filter
          const spaceValue = this.getAttribute('data-space');
          if (spaceValue !== null) {
            const hiddenInput = document.getElementById('hidden-space');
            if (hiddenInput) {
              hiddenInput.value = spaceValue;
            }
          }
        });
      });
    },

    /**
     * Initialize htmx event handlers.
     */
    initHtmxEvents: function (context) {
      const initialized = once('htmx-events-init', 'body', context);

      if (initialized.length === 0) return;

      // Reset page to 0 when filters change (but not when pager is clicked)
      document.body.addEventListener('htmx:configRequest', function (event) {
        const trigger = event.detail.elt;
        // Check if this is a pager button
        if (trigger && trigger.closest('.content-x-pager')) {
          return; // Don't reset page for pager clicks
        }
        // Reset page to 0 for filter changes
        const hiddenPageInput = document.getElementById('hidden-page');
        if (hiddenPageInput) {
          hiddenPageInput.value = '0';
        }
      });

      // After htmx swaps content, restore view preference
      document.body.addEventListener('htmx:afterSwap', function (event) {
        if (event.detail && event.detail.target) {
          const targetId = event.detail.target.id;

          if (targetId === 'content-x-content-area') {
            // Restore view preference after content swap
            const savedView = localStorage.getItem(STORAGE_KEY) || 'dense';
            Drupal.behaviors.contentX.setView(savedView);
          }
        }
      });

      // Handle errors
      document.body.addEventListener('htmx:responseError', function (event) {
        console.error('Content X: htmx error', event.detail);
      });
    },

    /**
     * Initialize quick add modal functionality.
     */
    initQuickAddModal: function (context) {
      const trigger = once('quick-add-modal-init', '#content-x-quick-add-trigger', context);
      if (trigger.length === 0) return;

      const modal = document.getElementById('content-x-quick-add-modal');
      if (!modal) return;

      const backdrop = modal.querySelector('.content-x-modal__backdrop');
      const closeBtn = modal.querySelector('.content-x-modal__close');
      const cancelBtn = modal.querySelector('.content-x-modal__cancel');
      const saveBtn = document.getElementById('quick-add-save');
      const typeSelect = document.getElementById('quick-add-type');
      const titleInput = document.getElementById('quick-add-title');
      const spaceSelect = document.getElementById('quick-add-space');
      const authorSelect = document.getElementById('quick-add-author');

      // Filter quick-add content type options based on selected space.
      var updateQuickAddContentTypes = function (spaceId) {
        if (!typeSelect) return;

        var mapping = Drupal.behaviors.contentX.getSpaceContentTypesMapping();
        var options = typeSelect.querySelectorAll('option[data-type-id]');

        if (!spaceId) {
          // No space selected: disable type select, hide all type options.
          typeSelect.disabled = true;
          typeSelect.value = '';
          var placeholder = typeSelect.querySelector('option[value=""]');
          if (placeholder) placeholder.textContent = Drupal.t('- Select space first -');
          options.forEach(function (opt) { opt.hidden = true; });
          return;
        }

        var allowedTypes = mapping[spaceId] || [];

        options.forEach(function (opt) {
          // Empty allowedTypes means all types are allowed for this space.
          if (allowedTypes.length === 0 || allowedTypes.indexOf(opt.getAttribute('data-type-id')) !== -1) {
            opt.hidden = false;
          } else {
            opt.hidden = true;
          }
        });

        // Enable the select and update placeholder.
        typeSelect.disabled = false;
        var placeholder = typeSelect.querySelector('option[value=""]');
        if (placeholder) placeholder.textContent = Drupal.t('- Select -');

        // If current selection is now hidden, reset.
        if (typeSelect.value) {
          var selected = typeSelect.querySelector('option[value="' + typeSelect.value + '"]');
          if (selected && selected.hidden) {
            typeSelect.value = '';
          }
        }
      };

      // Listen for space changes in the modal.
      if (spaceSelect) {
        spaceSelect.addEventListener('change', function () {
          updateQuickAddContentTypes(this.value);
        });
      }

      const openModal = function () {
        modal.classList.add('is-open');

        // Get current filter values
        const hiddenSpace = document.getElementById('hidden-space');

        // Preset space from filter
        if (spaceSelect) {
          spaceSelect.value = (hiddenSpace && hiddenSpace.value) ? hiddenSpace.value : '';
        }

        // Update content types based on preselected space.
        var preselectedSpace = spaceSelect ? spaceSelect.value : '';
        updateQuickAddContentTypes(preselectedSpace);

        // Preset content type from filter if the space allows it.
        var hiddenType = document.getElementById('hidden-type');
        if (typeSelect && hiddenType && hiddenType.value && !typeSelect.disabled) {
          var opt = typeSelect.querySelector('option[value="' + hiddenType.value + '"]');
          if (opt && !opt.hidden) {
            typeSelect.value = hiddenType.value;
          }
        }

        // Reset other fields
        if (titleInput) {
          titleInput.value = '';
          setTimeout(function () { titleInput.focus(); }, 100);
        }
        if (authorSelect) authorSelect.value = '';
      };

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

      // Open modal
      trigger[0].addEventListener('click', openModal);

      // Close modal
      if (backdrop) backdrop.addEventListener('click', closeModal);
      if (closeBtn) closeBtn.addEventListener('click', closeModal);
      if (cancelBtn) cancelBtn.addEventListener('click', closeModal);

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

      // Save handler
      if (saveBtn) {
        saveBtn.addEventListener('click', function () {
          const type = typeSelect ? typeSelect.value : '';
          const title = titleInput ? titleInput.value.trim() : '';
          const space = spaceSelect ? spaceSelect.value : '';
          const author = authorSelect ? authorSelect.value : '';

          // Validate
          if (!title) {
            titleInput.focus();
            return;
          }
          if (spaceSelect && !space) {
            spaceSelect.focus();
            return;
          }
          if (!type) {
            typeSelect.focus();
            return;
          }

          // Disable button
          saveBtn.disabled = true;
          saveBtn.textContent = Drupal.t('Creating...');

          // Send request
          fetch('/nodehive/admin/content/quick-add', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              type: type,
              title: title,
              space: space,
              author: author
            })
          })
          .then(function (response) { return response.json(); })
          .then(function (data) {
            if (data.success) {
              // Redirect to content overview
              window.location.href = '/nodehive/admin/content';
            } else {
              alert(data.message || Drupal.t('Failed to create content.'));
              saveBtn.disabled = false;
              saveBtn.textContent = Drupal.t('Create');
            }
          })
          .catch(function (error) {
            console.error('Content X: Quick add error', error);
            alert(Drupal.t('An error occurred. Please try again.'));
            saveBtn.disabled = false;
            saveBtn.textContent = Drupal.t('Create');
          });
        });
      }
    }
  };

})(Drupal, once);
