/**
 * @file
 * JavaScript for the NodeHive sitemap visualization.
 */

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

  /**
   * Sitemap visualization behavior.
   */
  Drupal.behaviors.nodehiveSitemap = {
    attach: function (context, settings) {
      once('nodehive-sitemap', '.nodehive-sitemap', context).forEach(function (element) {
        var $sitemap = $(element);

        // Add expand/collapse functionality
        initializeExpandCollapse($sitemap);

        // Add search functionality
        initializeSearch($sitemap);

        // Add orphaned content search functionality
        initializeOrphanedSearch($sitemap);

        // Add section toggle functionality
        initializeSectionToggle($sitemap);
      });
    }
  };

  /**
   * Initialize expand/collapse functionality for tree items.
   */
  function initializeExpandCollapse($sitemap) {
    // Add toggle buttons to items with children
    $sitemap.find('.sitemap-item').each(function () {
      var $item = $(this);
      var $children = $item.find('> .sitemap-children');

      if ($children.length > 0) {
        var $toggleBtn = $('<button class="sitemap-toggle" aria-expanded="true">')
          .html('<span class="toggle-icon">−</span>')
          .attr('title', Drupal.t('Collapse/Expand'));

        // Insert toggle button
        if ($item.find('.node-card').length > 0) {
          $item.find('.node-card-header').prepend($toggleBtn);
        } else if ($item.find('.menu-item').length > 0) {
          $item.find('.menu-item').prepend($toggleBtn);
        }

        // Toggle functionality
        $toggleBtn.on('click', function (e) {
          e.preventDefault();
          var $btn = $(this);
          var $children = $btn.closest('.sitemap-item').find('> .sitemap-children');
          var isExpanded = $btn.attr('aria-expanded') === 'true';

          if (isExpanded) {
            $children.slideUp(300);
            $btn.attr('aria-expanded', 'false')
               .find('.toggle-icon').text('+');
            $btn.closest('.sitemap-item').addClass('collapsed');
          } else {
            $children.slideDown(300);
            $btn.attr('aria-expanded', 'true')
               .find('.toggle-icon').text('−');
            $btn.closest('.sitemap-item').removeClass('collapsed');
          }
        });
      }
    });
  }

  /**
   * Initialize search functionality.
   */
  function initializeSearch($sitemap) {
    // Add search box
    var $searchContainer = $('<div class="sitemap-search-container">')
      .html('<input type="text" class="sitemap-search" placeholder="' +
            Drupal.t('Search nodes and menu items...') + '">');

    $sitemap.find('.sitemap-header').after($searchContainer);

    var $searchInput = $searchContainer.find('.sitemap-search');
    var searchTimeout;

    $searchInput.on('input', function () {
      clearTimeout(searchTimeout);
      var query = $(this).val().toLowerCase().trim();

      searchTimeout = setTimeout(function () {
        performSearch($sitemap, query);
      }, 300);
    });
  }

  /**
   * Perform search and highlight results.
   */
  function performSearch($sitemap, query) {
    var $items = $sitemap.find('.sitemap-item');

    if (query === '') {
      // Reset search - show all items
      $items.removeClass('search-hidden search-match');
      $sitemap.find('.sitemap-children').show();
      return;
    }

    $items.each(function () {
      var $item = $(this);
      var $title = $item.find('.node-title, .menu-item-title').first();
      var $contentType = $item.find('.content-type-badge');
      var $slug = $item.find('.slug');

      var titleText = $title.text().toLowerCase();
      var contentTypeText = $contentType.text().toLowerCase();
      var slugText = $slug.text().toLowerCase();

      var matches = titleText.includes(query) ||
                   contentTypeText.includes(query) ||
                   slugText.includes(query);

      if (matches) {
        $item.removeClass('search-hidden').addClass('search-match');
        // Show parent items
        $item.parents('.sitemap-children').show();
        $item.parents('.sitemap-item').removeClass('search-hidden');
      } else {
        $item.addClass('search-hidden').removeClass('search-match');
      }
    });

    // Hide empty sections
    $sitemap.find('.sitemap-section').each(function () {
      var $section = $(this);
      var hasVisibleItems = $section.find('.sitemap-item:not(.search-hidden)').length > 0;

      if (hasVisibleItems) {
        $section.show();
      } else {
        $section.hide();
      }
    });
  }

  /**
   * Initialize section toggle functionality.
   */
  function initializeSectionToggle($sitemap) {
    $sitemap.find('.section-header').each(function () {
      var $header = $(this);
      var $section = $header.closest('.sitemap-section');
      var $content = $section.find('.sitemap-tree, .empty-section');

      // Add toggle button to section header
      var $toggleBtn = $('<button class="section-toggle" aria-expanded="true">')
        .html('<span class="section-toggle-icon">−</span>')
        .attr('title', Drupal.t('Collapse/Expand section'));

      $header.find('.section-title').append($toggleBtn);

      $toggleBtn.on('click', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var isExpanded = $btn.attr('aria-expanded') === 'true';

        if (isExpanded) {
          $content.slideUp(400);
          $btn.attr('aria-expanded', 'false')
             .find('.section-toggle-icon').text('+');
          $section.addClass('section-collapsed');
        } else {
          $content.slideDown(400);
          $btn.attr('aria-expanded', 'true')
             .find('.section-toggle-icon').text('−');
          $section.removeClass('section-collapsed');
        }
      });
    });

    // Add "Expand All" / "Collapse All" buttons
    var $controlsContainer = $('<div class="sitemap-controls">')
      .html('<button class="sitemap-control-btn expand-all">' +
            Drupal.t('Expand All') + '</button>' +
            '<button class="sitemap-control-btn collapse-all">' +
            Drupal.t('Collapse All') + '</button>');

    $sitemap.find('.sitemap-search-container').after($controlsContainer);

    $controlsContainer.find('.expand-all').on('click', function () {
      expandAll($sitemap);
    });

    $controlsContainer.find('.collapse-all').on('click', function () {
      collapseAll($sitemap);
    });
  }

  /**
   * Expand all sections and items.
   */
  function expandAll($sitemap) {
    // Expand all sections
    $sitemap.find('.section-toggle[aria-expanded="false"]').trigger('click');

    // Expand all tree items
    $sitemap.find('.sitemap-toggle[aria-expanded="false"]').trigger('click');
  }

  /**
   * Collapse all sections and items.
   */
  function collapseAll($sitemap) {
    // Collapse all tree items first
    $sitemap.find('.sitemap-toggle[aria-expanded="true"]').trigger('click');

    // Then collapse sections
    setTimeout(function () {
      $sitemap.find('.section-toggle[aria-expanded="true"]').trigger('click');
    }, 100);
  }

  /**
   * Initialize orphaned content search functionality.
   */
  function initializeOrphanedSearch($sitemap) {
    var $orphanedSearch = $sitemap.find('#orphaned-search');
    var $resultsCount = $sitemap.find('#search-results-count');

    if ($orphanedSearch.length === 0) {
      return;
    }

    var searchTimeout;

    $orphanedSearch.on('input', function () {
      clearTimeout(searchTimeout);
      var query = $(this).val().toLowerCase().trim();

      searchTimeout = setTimeout(function () {
        performOrphanedSearch($sitemap, query, $resultsCount);
      }, 300);
    });
  }

  /**
   * Perform search on orphaned content table.
   */
  function performOrphanedSearch($sitemap, query, $resultsCount) {
    var $nodeCards = $sitemap.find('.orphaned-content-table .node-card--table');
    var totalCards = $nodeCards.length;
    var visibleCards = 0;

    if (query === '') {
      // Reset search - show all cards
      $nodeCards.removeClass('node-card--hidden node-card--search-match');
      $resultsCount.text('');
      return;
    }

    $nodeCards.each(function () {
      var $card = $(this);
      var $title = $card.find('.node-title');
      var $slug = $card.find('.slug');

      var titleText = $title.text().toLowerCase();
      var slugText = $slug.text().toLowerCase();

      var matches = titleText.includes(query) || slugText.includes(query);

      if (matches) {
        $card.removeClass('node-card--hidden').addClass('node-card--search-match');
        visibleCards++;

        // Highlight matching text
        highlightText($title, query);
        highlightText($slug, query);
      } else {
        $card.addClass('node-card--hidden').removeClass('node-card--search-match');

        // Remove highlights
        removeHighlights($title);
        removeHighlights($slug);
      }
    });

    // Update results count
    if (visibleCards === 0) {
      $resultsCount.text(Drupal.t('No results found'));
    } else if (visibleCards === totalCards) {
      $resultsCount.text('');
    } else {
      $resultsCount.text(Drupal.t('@visible of @total items', {
        '@visible': visibleCards,
        '@total': totalCards
      }));
    }
  }

  /**
   * Highlight matching text in an element.
   */
  function highlightText($element, query) {
    if (!$element.length || !query) return;

    var originalText = $element.data('original-text') || $element.text();
    $element.data('original-text', originalText);

    var regex = new RegExp('(' + escapeRegex(query) + ')', 'gi');
    var highlightedText = originalText.replace(regex, '<span class="search-highlight">$1</span>');

    $element.html(highlightedText);
  }

  /**
   * Remove highlights from an element.
   */
  function removeHighlights($element) {
    if (!$element.length) return;

    var originalText = $element.data('original-text');
    if (originalText) {
      $element.text(originalText);
    }
  }

  /**
   * Escape special regex characters.
   */
  function escapeRegex(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }

})(jQuery, Drupal, once);
