export function useTravelReimbursementCreateViewScroll({
  COMPOSER_MAX_ROWS,
  COMPOSER_TEXTAREA_HEIGHT,
  composerTextareaRef,
  messageListRef,
  nextTick,
  reviewActionBusy,
  sessionSwitchBusy,
  submitComposer,
  submitting
}) {
  function scrollToBottom() {
    const scrollOnce = () => {
      const list = messageListRef.value?.$el || messageListRef.value
      if (!list) {
        return false
      }
      list.scrollTop = list.scrollHeight
      return true
    }

    nextTick(() => {
      if (scrollOnce()) {
        return
      }
      requestAnimationFrame(() => {
        scrollOnce()
        requestAnimationFrame(scrollOnce)
      })
    })
  }

  function handleAssistantModalAfterEnter() {
    scrollToBottom()
    requestAnimationFrame(() => {
      scrollToBottom()
    })
  }

  function adjustComposerTextareaHeight() {
    if (!composerTextareaRef.value) return

    const textarea = composerTextareaRef.value
    textarea.style.height = 'auto'
    const styles = window.getComputedStyle(textarea)
    const lineHeight = Number.parseFloat(styles.lineHeight) || 20
    const verticalPadding =
      Number.parseFloat(styles.paddingTop || '0') + Number.parseFloat(styles.paddingBottom || '0')
    const minHeight = COMPOSER_TEXTAREA_HEIGHT
    const maxHeight = lineHeight * COMPOSER_MAX_ROWS + verticalPadding
    const nextHeight = Math.max(minHeight, Math.min(textarea.scrollHeight, maxHeight))

    textarea.style.height = `${nextHeight}px`
    textarea.style.overflowY = textarea.scrollHeight > maxHeight ? 'auto' : 'hidden'
  }

  function handleComposerInput() {
    adjustComposerTextareaHeight()
  }

  function handleComposerEnter(event) {
    if (event?.isComposing || submitting.value || reviewActionBusy.value || sessionSwitchBusy.value) {
      return
    }
    submitComposer()
  }

  return {
    adjustComposerTextareaHeight,
    handleAssistantModalAfterEnter,
    handleComposerEnter,
    handleComposerInput,
    scrollToBottom
  }
}
