/**
 * 247ChatMate — Scroll Controller (LOCKED v1.2)
 * --------------------------------------------------
 * Sole owner of scroll behaviour inside widget
 *
 * • Listens for `matewa:scroll-request`
 * • Scrolls `.matewa-bubbles` only
 * • Resolves header + CTA exclusion
 * • Anchors to instruction bubble when present
 */

(function () {
  'use strict';

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  function init() {
    const widget = document.getElementById('matewa-widget');
    if (!widget) return;

    const scroller = widget.querySelector('.matewa-bubbles');
    if (!scroller) return;

    const header = widget.querySelector('.matewa-header');
    const cta = widget.querySelector('.matewa-cta');
    const branding = widget.querySelector('.matewa-branding');

    /**
     * Resolve scroll target inside widget
     */
    function resolveTarget(target) {
      switch (target) {
        case 'intent':
          return widget.querySelector('.matewa-task-intent');

        case 'notes':
          return widget.querySelector('.matewa-notes');

        case 'notes-input':
          return widget.querySelector('.matewa-notes-textarea');

        case 'phone':
          return widget.querySelector('.matewa-phone');

        case 'contact':
          return widget.querySelector('.matewa-contact');

        default:
          return null;
      }
    }

    /**
     * If a task contains an instruction bubble,
     * scroll to that bubble instead of the wrapper
     */
    function resolveAnchor(el) {
      if (!el) return null;
      const bubble = el.querySelector('.matewa-bubble');
      return bubble || el;
    }

    /**
     * Perform smooth, container-relative scroll
     * respecting header + CTA exclusion
     */
    function scrollToElement(el) {
      if (!el) return;

      const anchor = resolveAnchor(el);

      const scrollerRect = scroller.getBoundingClientRect();
      const anchorRect = anchor.getBoundingClientRect();

      const headerHeight = header ? header.offsetHeight : 0;
      const ctaHeight = cta ? cta.offsetHeight : 0;
      const brandingHeight = branding ? branding.offsetHeight : 0;

      const safePaddingTop = 16;     // matches .matewa-bubbles padding
      const safePaddingBottom = 12;  // breathing room above CTA

      // Desired top alignment (under header)
      let targetTop =
        anchorRect.top -
        scrollerRect.top +
        scroller.scrollTop -
        headerHeight -
        safePaddingTop;

      // Clamp so content never lands behind CTA / branding
      const maxScroll =
        scroller.scrollHeight -
        scroller.clientHeight +
        ctaHeight +
        brandingHeight +
        safePaddingBottom;

      if (targetTop > maxScroll) {
        targetTop = maxScroll;
      }

      if (targetTop < 0) {
        targetTop = 0;
      }

      scroller.scrollTo({
        top: targetTop,
        behavior: 'smooth'
      });
    }

    /**
     * Listen for scroll requests
     */
    widget.addEventListener('matewa:scroll-request', e => {
      const target = e.detail?.target;
      if (!target) return;

      const el = resolveTarget(target);
      if (!el) return;

      // Defer one frame to allow layout to settle
      requestAnimationFrame(() => {
        scrollToElement(el);
      });
    });
  }
})();
