import { ref, nextTick } from 'vue'

// (Almost) at the bottom edge? Threshold absorbs sub-pixels and small gaps.
export function istUnten(el, threshold = 60) {
  return el.scrollHeight - el.scrollTop - el.clientHeight < threshold
}

// Shared chat mechanics: send, cancel (run counter), scroll, focus.
// performRequest(messages) → Promise<{ reply, … }>; send() returns the response
// so the caller can evaluate extras (e.g. changes).
export function useChat(performRequest) {
  const messages = ref([])
  const input = ref('')
  const loading = ref(false)
  const messagesEl = ref(null) // template ref: messages container
  const inputEl = ref(null)    // template ref: textarea
  const stick = ref(true)      // "pinned" to the bottom — only then auto-scroll
  let run = 0 // identify the running request; cancel ignores its result

  // @scroll handler: pins only when the user is (almost) at the bottom.
  function onScroll() {
    if (messagesEl.value) stick.value = istUnten(messagesEl.value)
  }

  async function scrollToBottom() {
    await nextTick()
    if (messagesEl.value && stick.value) messagesEl.value.scrollTop = messagesEl.value.scrollHeight
  }

  function autoGrow(max = 140) {
    const el = inputEl.value
    if (!el) return
    el.style.height = 'auto'
    el.style.height = Math.min(el.scrollHeight, max) + 'px'
  }

  function cancel() {
    run++
    loading.value = false
    messages.value.push({ role: 'assistant', content: 'Cancelled.' })
  }

  function reset() {
    run++
    loading.value = false
    messages.value = []
    input.value = ''
  }

  async function send() {
    if (loading.value) { // second click = cancel
      cancel()
      return null
    }
    const text = input.value.trim()
    if (!text) return null
    stick.value = true // own send = jump to end; scrolling up while waiting resets it to false
    const current = ++run
    messages.value.push({ role: 'user', content: text })
    input.value = ''
    nextTick(() => autoGrow())
    loading.value = true
    scrollToBottom()
    try {
      const res = await performRequest(messages.value)
      if (current !== run) return null
      // Exam returns `question` (+ separate `feedback`); other chats `reply`.
      messages.value.push({
        role: 'assistant',
        content: res.question ?? res.reply ?? '…',
        feedback: res.feedback ?? null,
        rating: res.rating ?? null,
      })
      return res
    } catch {
      if (current !== run) return null
      messages.value.push({ role: 'assistant', content: 'Request failed.' })
      return null
    } finally {
      if (current === run) {
        loading.value = false
        scrollToBottom()
        nextTick(() => inputEl.value?.focus())
      }
    }
  }

  return { messages, input, loading, messagesEl, inputEl, stick, onScroll, send, cancel, reset, scrollToBottom, autoGrow }
}
