/**
 * @file
 * FlowDrop Dependency Navigator - Curved connector drawing
 *
 * @param {object} Drupal The Drupal API namespace.
 * @param {Function} once The "once" deduplication library.
 */

((Drupal, once) => {
  /**
   * 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.
   * @return {SVGPathElement} The path element.
   */
  function createCurvedPath(x1, y1, x2, y2) {
    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');

    // Calculate control points for a smooth S-curve
    const deltaX = x2 - x1;

    // 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;
  }

  /**
   * 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((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((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);
      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((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);
      path.classList.add('fd-dep-nav__connector-path');
      path.setAttribute('marker-end', 'url(#fd-arrow)');
      canvas.appendChild(path);
    });
  }

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

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

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

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