/**
 * @file
 * Content Finder functionality.
 */

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

  /**
   * Content Finder behavior.
   */
  // Store overlay state outside of attach function
  let $overlay = null;
  let currentIndex = -1;
  let searchResults = [];
  let lastNavigationTime = 0;

  Drupal.behaviors.contentFinder = {
    attach: function (context, settings) {
      const searchUrl = drupalSettings.contentFinder ? drupalSettings.contentFinder.searchUrl : '/nodehive/content-browser/search';
      const contentTypesUrl = drupalSettings.contentFinder ? drupalSettings.contentFinder.contentTypesUrl : '/nodehive/content-browser/content-types';
      let availableContentTypes = [];

      /**
       * Creates the overlay element.
       */
      function createOverlay() {
        const template = Drupal.theme('contentFinderOverlay');
        $overlay = $(template).appendTo('body');

        // Event handlers.
        $overlay.find('.content-finder-backdrop, .content-finder-close').on('click', closeOverlay);
        $overlay.find('.content-finder-search').on('input', Drupal.debounce(performSearch, 300));
        $overlay.find('.content-finder-list').on('click', '.content-finder-item', handleItemClick);

        // Keyboard navigation - remove any existing handlers first
        $(document).off('keydown.contentFinder').on('keydown.contentFinder', handleKeydown);
      }

      /**
       * Opens the overlay.
       */
      function openOverlay(e) {
        e.preventDefault();
        e.stopPropagation();

        if (!$overlay) {
          createOverlay();
        }

        $overlay.addClass('is-open');
        $('body').addClass('content-finder-open');

        // Use setTimeout to ensure the overlay is fully rendered before focusing
        setTimeout(function () {
          $overlay.find('.content-finder-search').val('').focus();
        }, 100);

        resetResults();
        loadContentTypes();
      }

      /**
       * Closes the overlay.
       */
      function closeOverlay() {
        if ($overlay) {
          $overlay.removeClass('is-open');
          $('body').removeClass('content-finder-open');
          currentIndex = -1;
          searchResults = [];

          // Clear search input
          $overlay.find('.content-finder-search').val('');
        }
      }

      /**
       * Performs the search.
       */
      function performSearch() {
        const query = $overlay.find('.content-finder-search').val().trim();

        if (!query) {
          resetResults();
          return;
        }

        showLoading();

        $.ajax({
          url: searchUrl,
          data: { q: query, limit: 20 },
          dataType: 'json',
          success: function (data) {
            displayResults(data);
          },
          error: function () {
            showError();
          }
        });
      }

      /**
       * Loads available content types.
       */
      function loadContentTypes() {
        $.ajax({
          url: contentTypesUrl,
          dataType: 'json',
          success: function (data) {
            availableContentTypes = data.content_types || [];
          }
        });
      }

      /**
       * Displays search results.
       */
      function displayResults(data) {
        const $list = $overlay.find('.content-finder-list').empty();
        searchResults = data.results || [];
        currentIndex = -1;

        $overlay.find('.content-finder-loading').hide();

        if (searchResults.length === 0) {
          $overlay.find('.content-finder-empty').hide();
          displayCreateOptions();
          return;
        }

        $overlay.find('.content-finder-empty').hide();
        $overlay.find('.content-finder-create-section').remove();

        searchResults.forEach(function (item, index) {
          const $item = $(Drupal.theme('contentFinderItem', item, index));
          $list.append($item);
        });
      }

      /**
       * Displays content creation options.
       */
      function displayCreateOptions() {
        const $results = $overlay.find('.content-finder-results');

        // Remove existing create section if any
        $results.find('.content-finder-create-section').remove();

        if (availableContentTypes.length === 0) {
          $overlay.find('.content-finder-empty').text(Drupal.t('No results found. You do not have permission to create content.')).show();
          return;
        }

        const $createSection = $('<div class="content-finder-create-section">');
        $createSection.append('<h3>' + Drupal.t('No results found. Create new content:') + '</h3>');

        const $typesList = $('<ul class="content-finder-create-list">');
        availableContentTypes.forEach(function (type) {
          const $typeItem = $(Drupal.theme('contentFinderCreateItem', type));
          $typesList.append($typeItem);
        });

        $createSection.append($typesList);
        $results.append($createSection);
      }

      /**
       * Resets the results display.
       */
      function resetResults() {
        $overlay.find('.content-finder-list').empty();
        $overlay.find('.content-finder-loading, .content-finder-empty').hide();
        $overlay.find('.content-finder-create-section').remove();
        currentIndex = -1;
        searchResults = [];
      }

      /**
       * Shows loading state.
       */
      function showLoading() {
        $overlay.find('.content-finder-list').empty();
        $overlay.find('.content-finder-empty').hide();
        $overlay.find('.content-finder-loading').show();
      }

      /**
       * Shows error state.
       */
      function showError() {
        $overlay.find('.content-finder-loading').hide();
        $overlay.find('.content-finder-empty').text(Drupal.t('An error occurred. Please try again.')).show();
      }

      /**
       * Handles keyboard navigation.
       */
      function handleKeydown(e) {
        if (!$overlay || !$overlay.hasClass('is-open')) {
          // Global shortcut to open - Command+Shift+F (Mac) or Ctrl+Shift+F (Windows/Linux)
          if ((e.metaKey || e.ctrlKey) && e.shiftKey && (e.key === 'f' || e.key === 'F')) {
            e.preventDefault();
            e.stopPropagation();
            const $toolbar = $('.toolbar-icon-content-finder');
            $toolbar.first().trigger('click');
          }
          return;
        }

        switch (e.key) {
          case 'Escape':
            e.preventDefault();
            closeOverlay();
            break;

          case 'ArrowDown':
            e.preventDefault();
            e.stopPropagation();
            // Don't navigate if this is a key repeat
            if (!e.repeat) {
              navigateResults(1);
            }
            break;

          case 'ArrowUp':
            e.preventDefault();
            e.stopPropagation();
            // Don't navigate if this is a key repeat
            if (!e.repeat) {
              navigateResults(-1);
            }
            break;

          case 'Enter':
            e.preventDefault();
            if (currentIndex >= 0 && searchResults[currentIndex]) {
              const url = e.ctrlKey || e.metaKey
                ? searchResults[currentIndex].edit_url
                : searchResults[currentIndex].view_url;
              window.location.href = url;
            }
            break;

        }
      }

      /**
       * Navigates through results.
       */
      function navigateResults(direction) {
        // Throttle navigation to prevent rapid movement
        const now = Date.now();
        if (now - lastNavigationTime < 100) {
          return;
        }
        lastNavigationTime = now;

        const $items = $overlay.find('.content-finder-item');
        const maxIndex = $items.length - 1;

        currentIndex += direction;
        if (currentIndex < 0) currentIndex = maxIndex;
        if (currentIndex > maxIndex) currentIndex = 0;

        $items.removeClass('is-selected').attr('aria-selected', 'false');
        $items.eq(currentIndex).addClass('is-selected').attr('aria-selected', 'true');

        // Ensure the selected item is visible
        const $selected = $items.eq(currentIndex);
        if ($selected.length) {
          const container = $overlay.find('.content-finder-results')[0];
          const item = $selected[0];
          const containerTop = container.scrollTop;
          const containerBottom = containerTop + container.offsetHeight;
          const itemTop = item.offsetTop;
          const itemBottom = itemTop + item.offsetHeight;

          if (itemTop < containerTop) {
            container.scrollTop = itemTop;
          } else if (itemBottom > containerBottom) {
            container.scrollTop = itemBottom - container.offsetHeight;
          }
        }
      }

      /**
       * Handles item click.
       */
      function handleItemClick(e) {
        e.preventDefault();
        const $target = $(e.currentTarget);
        const isEdit = $(e.target).hasClass('content-finder-edit');
        const url = isEdit ? $target.data('edit-url') : $target.data('view-url');
        window.location.href = url;
      }

      // Attach click handler to toolbar item.
      // Use Drupal 10's once API correctly
      const elements = once('content-finder-global', 'body', context);
      if (elements.length) {
        // Try multiple selectors to find the toolbar item
        $(document).on('click', '.toolbar-icon-content-finder, #toolbar-item-content-finder, a[data-dialog-type="content-finder"]', openOverlay);

        // Also attach keyboard handler globally - remove any existing handlers first
        $(document).off('keydown.contentFinderGlobal').on('keydown.contentFinderGlobal', handleKeydown);
      }
    }
  };

  /**
   * Theme function for overlay.
   */
  Drupal.theme.contentFinderOverlay = function () {
    return '<div class="content-finder-overlay">' +
      '<div class="content-finder-backdrop"></div>' +
      '<div class="content-finder-dialog">' +
        '<div class="content-finder-header">' +
          '<input type="text" class="content-finder-search" placeholder="' + Drupal.t('Search content by title...') + '" autocomplete="off" autofocus>' +
          '<button class="content-finder-close" aria-label="' + Drupal.t('Close') + '"><span aria-hidden="true">&times;</span></button>' +
        '</div>' +
        '<div class="content-finder-results">' +
          '<div class="content-finder-loading">' + Drupal.t('Searching...') + '</div>' +
          '<div class="content-finder-empty">' + Drupal.t('No results found') + '</div>' +
          '<ul class="content-finder-list" role="listbox"></ul>' +
        '</div>' +
        '<div class="content-finder-footer">' +
          '<span class="content-finder-hint">' +
            '<kbd>↑↓</kbd> ' + Drupal.t('to navigate') + ' ' +
            '<kbd>↵</kbd> ' + Drupal.t('to view') + ' ' +
            '<kbd>Ctrl+↵</kbd> ' + Drupal.t('to edit') + ' ' +
            '<kbd>Esc</kbd> ' + Drupal.t('to close') +
          '</span>' +
        '</div>' +
      '</div>' +
    '</div>';
  };

  /**
   * Theme function for result item.
   */
  Drupal.theme.contentFinderItem = function (item, index) {
    let spacesHtml = '';
    if (item.spaces && item.spaces.length > 0) {
      const spaceNames = item.spaces.map(function (space) { return space.title; }).join(', ');
      spacesHtml = '<span class="content-finder-item-spaces">' + Drupal.t('Space: @spaces', {'@spaces': spaceNames}) + '</span>';
    }

    const statusClass = item.status === 'published' ? 'is-published' : 'is-unpublished';
    const statusText = item.status === 'published' ? Drupal.t('Published') : Drupal.t('Unpublished');

    return '<li class="content-finder-item" role="option" data-index="' + index + '" ' +
      'data-view-url="' + item.view_url + '" data-edit-url="' + item.edit_url + '">' +
      '<div class="content-finder-item-content">' +
        '<div class="content-finder-item-header">' +
          '<span class="content-finder-item-type">[' + item.type_label + ']</span> ' +
          '<span class="content-finder-item-title">' + item.title + '</span>' +
          '<span class="content-finder-item-status ' + statusClass + '">' + statusText + '</span>' +
          spacesHtml +
        '</div>' +
        '<div class="content-finder-item-meta">' +
          Drupal.t('Last modified: @time', {'@time': item.changed}) +
        '</div>' +
      '</div>' +
      '<div class="content-finder-item-actions">' +
        '<a href="#" class="content-finder-edit" title="' + Drupal.t('Edit') + '">' +
          '<span class="visually-hidden">' + Drupal.t('Edit') + '</span>' +
          '<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">' +
            '<path d="M12.854 0.146a0.5 0.5 0 0 0-0.707 0L10.5 1.793 14.207 5.5l1.647-1.646a0.5 0.5 0 0 0 0-0.708l-3-3zM9.793 2.5L3.5 8.793V12.5h3.707l6.293-6.293L9.793 2.5z"/>' +
          '</svg>' +
        '</a>' +
      '</div>' +
    '</li>';
  };

  /**
   * Theme function for content type create item.
   */
  Drupal.theme.contentFinderCreateItem = function (type) {
    return '<li class="content-finder-create-item">' +
      '<a href="' + type.create_url + '" class="content-finder-create-link">' +
        '<span class="content-finder-create-icon">+</span>' +
        '<div class="content-finder-create-content">' +
          '<div class="content-finder-create-label">' + type.label + '</div>' +
          (type.description ? '<div class="content-finder-create-description">' + type.description + '</div>' : '') +
        '</div>' +
      '</a>' +
    '</li>';
  };

})(jQuery, Drupal, drupalSettings, once);