import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { mount } from '@vue/test-utils'
import { nextTick } from 'vue'
import HelpButton from '../HelpButton.vue'
import {
  activeStep,
  dismissActive,
  sessionSkipped,
  setHelpButtonHidden,
  tutorialEnabled,
  tutorialProgress,
} from '../controller'

vi.mock('vue-router', () => ({
  useRoute: vi.fn(() => ({ name: 'ChoreView' })),
}))

describe('HelpButton', () => {
  beforeEach(() => {
    tutorialEnabled.value = true
    tutorialProgress.value = {}
    sessionSkipped.value = false
    activeStep.value = null
    setHelpButtonHidden(false)
    document.body.innerHTML = ''
  })

  afterEach(() => {
    setHelpButtonHidden(false)
    activeStep.value = null
    document.body.innerHTML = ''
  })

  it('renders when tutorial is enabled and a step is mapped', () => {
    const wrapper = mount(HelpButton)
    expect(wrapper.find('.help-fab').exists()).toBe(true)
  })

  it('renders even when tutorial tips are disabled, so the help system stays reachable', () => {
    tutorialEnabled.value = false
    const wrapper = mount(HelpButton)
    expect(wrapper.find('.help-fab').exists()).toBe(true)
  })

  it('hides while helpButtonHidden is true', async () => {
    const wrapper = mount(HelpButton)
    expect(wrapper.find('.help-fab').exists()).toBe(true)

    setHelpButtonHidden(true)
    await nextTick()

    expect(wrapper.find('.help-fab').exists()).toBe(false)

    setHelpButtonHidden(false)
    await nextTick()

    expect(wrapper.find('.help-fab').exists()).toBe(true)
  })

  function setAnchorHtml() {
    document.body.innerHTML = `
      <div class="fab"></div>
      <div class="list-item"></div>
      <div class="delete-btn"></div>
    `
  }

  it('clicking the ? FAB when tips are disabled starts the help chain', async () => {
    tutorialEnabled.value = false
    setAnchorHtml()

    const wrapper = mount(HelpButton)
    await wrapper.find('.help-fab').trigger('click')
    await nextTick()

    expect(activeStep.value?.def.id).toBe('list-chore-help')
  })

  it('continues through the help chain while tips are disabled', async () => {
    tutorialEnabled.value = false
    setAnchorHtml()

    const wrapper = mount(HelpButton)
    await wrapper.find('.help-fab').trigger('click')
    await nextTick()
    expect(activeStep.value?.def.id).toBe('list-chore-help')

    dismissActive(true)
    await nextTick()
    expect(activeStep.value?.def.id).toBe('list-edit-hint')

    dismissActive(true)
    await nextTick()
    expect(activeStep.value?.def.id).toBe('list-delete-hint')
  })

  it('works even if the user previously skipped the session', async () => {
    sessionSkipped.value = true
    tutorialEnabled.value = false
    setAnchorHtml()

    const wrapper = mount(HelpButton)
    await wrapper.find('.help-fab').trigger('click')
    await nextTick()

    expect(sessionSkipped.value).toBe(false)
    expect(activeStep.value?.def.id).toBe('list-chore-help')
  })
})
