/**
 * @file
 * FlowDrop Dependency Navigator - Curved connector drawing
 */

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

  /**
   * Draw curved bezier connectors between job items.
   */
  Drupal.behaviors.flowdropDependencyNavigator = {
    attach: function (context) {
      once('flowdrop-dependency-navigator', '[data-flowdrop-dependency-navigator]', context).forEach(function (nav) {
        drawConnectors(nav);

        // Redraw on window resize with debounce
        var resizeTimeout;
        var resizeHandler = function () {
          clearTimeout(resizeTimeout);
          resizeTimeout = setTimeout(function () {
            drawConnectors(nav);
          }, 100);
        };
        window.addEventListener('resize', resizeHandler);
        // Store handler reference on element for cleanup
        nav._flowdropResizeHandler = resizeHandler;
      });
    },

    detach: function (context, settings, trigger) {
      if (trigger !== 'unload') {
        return;
      }

      var navs = context.querySelectorAll('[data-flowdrop-dependency-navigator]');
      navs.forEach(function (nav) {
        if (nav._flowdropResizeHandler) {
          window.removeEventListener('resize', nav._flowdropResizeHandler);
          nav._flowdropResizeHandler = null;
        }
      });
    }
  };

  /**
   * Draw all connectors for a dependency navigator.
   * 
   * @param {HTMLElement} nav - The navigator container element.
   */
  function drawConnectors(nav) {
    const canvas = nav.querySelector('.fd-dep-nav__canvas');
    if (!canvas) return;

    // Clear existing paths
    const existingPaths = canvas.querySelectorAll('.fd-dep-nav__connector-path');
    existingPaths.forEach(function (path) { path.remove(); });

    const navRect = nav.getBoundingClientRect();
    const currentItem = nav.querySelector('.fd-dep-nav__item--current');
    if (!currentItem) return;

    const currentRect = currentItem.getBoundingClientRect();
    const currentCenterY = currentRect.top + currentRect.height / 2 - navRect.top;
    const currentLeft = currentRect.left - navRect.left;
    const currentRight = currentRect.right - navRect.left;

    // Draw connectors from parent items to current (with arrows)
    const parentItems = nav.querySelectorAll('[data-column="parents"] [data-connector-source]');
    parentItems.forEach(function (item) {
      const itemRect = item.getBoundingClientRect();
      const startX = itemRect.right - navRect.left;
      const startY = itemRect.top + itemRect.height / 2 - navRect.top;
      const endX = currentLeft;
      const endY = currentCenterY;

      const path = createCurvedPath(startX, startY, endX, endY, 'right');
      path.classList.add('fd-dep-nav__connector-path');
      path.setAttribute('marker-end', 'url(#fd-arrow)');
      canvas.appendChild(path);
    });

    // Draw connectors from current to child items
    const childItems = nav.querySelectorAll('[data-column="children"] [data-connector-target="right"]');
    childItems.forEach(function (item) {
      const itemRect = item.getBoundingClientRect();
      const startX = currentRight;
      const startY = currentCenterY;
      const endX = itemRect.left - navRect.left;
      const endY = itemRect.top + itemRect.height / 2 - navRect.top;

      const path = createCurvedPath(startX, startY, endX, endY, 'right');
      path.classList.add('fd-dep-nav__connector-path');
      path.setAttribute('marker-end', 'url(#fd-arrow)');
      canvas.appendChild(path);
    });
  }

  /**
   * Create an SVG path element with a smooth cubic bezier curve.
   * 
   * @param {number} x1 - Start X coordinate.
   * @param {number} y1 - Start Y coordinate.
   * @param {number} x2 - End X coordinate.
   * @param {number} y2 - End Y coordinate.
   * @param {string} direction - 'right' for left-to-right flow.
   * @returns {SVGPathElement} The path element.
   */
  function createCurvedPath(x1, y1, x2, y2, direction) {
    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    
    // Calculate control points for a smooth S-curve
    const deltaX = x2 - x1;
    const deltaY = y2 - y1;
    
    // Control point offset (how far the curve bends)
    const curveStrength = Math.min(Math.abs(deltaX) * 0.5, 80);
    
    // For horizontal flow (left to right)
    const cx1 = x1 + curveStrength;
    const cy1 = y1;
    const cx2 = x2 - curveStrength;
    const cy2 = y2;
    
    // Create cubic bezier path
    const d = `M ${x1} ${y1} C ${cx1} ${cy1}, ${cx2} ${cy2}, ${x2} ${y2}`;
    path.setAttribute('d', d);
    
    return path;
  }

})(Drupal, once);
