/* ==========================================================================
   Niwa Chatbot -- Scroll Behavior
   ---------------------------------------------------------------------------
   Auto-scrolls message area to bottom using requestAnimationFrame.

   NAMESPACE: window.Niwa.ScrollBehavior
   ========================================================================== */

window.Niwa = window.Niwa || {};

window.Niwa.ScrollBehavior = (function () {
  'use strict';

  var lifecycleBound = false;

  function scrollToBottom(el) {
    if (!el) return;
    requestAnimationFrame(function () {
      el.scrollTop = el.scrollHeight;
    });
  }

  function init(bodyEl) {
    if (!bodyEl) {
      bodyEl = document.querySelector('.niwa-morph__body')
        || document.querySelector('.niwa-center__body');
    }
    if (!bodyEl) return;

    // Auto-scroll to bottom after messages load
    setTimeout(function () {
      scrollToBottom(bodyEl);
    }, 100);

    if (!lifecycleBound) {
      lifecycleBound = true;
      window.addEventListener('niwa:morph:open', function () {
        scrollToBottom(bodyEl);
        setTimeout(function () { scrollToBottom(bodyEl); }, 650);
      });
    }
  }

  return {
    init: init,
    scrollToBottom: scrollToBottom
  };
})();
