/**
 * UI Module - updateToggleCycle Tests
 * @countermeasure/web-components
 *
 * Tests for the updateToggleCycle function that configures
 * the theme toggle cycle order.
 */

import { describe, it, expect, beforeEach, afterEach } from 'vitest'

import { updateToggleCycle, configureTheme, toggleTheme, applyTheme, getNextTheme } from './index'
import type { ResolvedTheme } from './index'

describe('updateToggleCycle', () => {
  beforeEach(() => {
    localStorage.clear()
    document.documentElement.removeAttribute('data-theme')
    document.documentElement.classList.remove('light', 'dark', 'monokai', 'glass')
    // Reset theme config to defaults
    configureTheme({
      storageKey: 'theme',
      defaultTheme: 'system',
      themes: ['light', 'dark', 'monokai', 'glass', 'system'],
      attribute: 'data-theme',
    })
  })

  afterEach(() => {
    localStorage.clear()
    document.documentElement.removeAttribute('data-theme')
    document.documentElement.classList.remove('light', 'dark', 'monokai', 'glass')
  })

  it('changes the cycle order for toggleTheme', () => {
    // Set up initial state: current theme is 'light'
    localStorage.setItem('theme', 'light')
    applyTheme('light')

    // Default cycle is light -> dark -> monokai -> glass
    // Verify the default next theme from 'light' is 'dark'
    expect(getNextTheme('light')).toBe('dark')

    // Now change the cycle to only include dark and monokai
    const newCycle: ResolvedTheme[] = ['dark', 'monokai']
    updateToggleCycle(newCycle)

    // After updating the cycle, the next theme from 'dark' should be 'monokai'
    expect(getNextTheme('dark')).toBe('monokai')
    // And from 'monokai' should wrap back to 'dark'
    expect(getNextTheme('monokai')).toBe('dark')
  })

  it('accepts a single-theme cycle', () => {
    const newCycle: ResolvedTheme[] = ['dark']
    updateToggleCycle(newCycle)

    // With only one theme in the cycle, toggling should stay on dark
    expect(getNextTheme('dark')).toBe('dark')
  })

  it('accepts all four themes in a custom order', () => {
    const newCycle: ResolvedTheme[] = ['glass', 'monokai', 'light', 'dark']
    updateToggleCycle(newCycle)

    expect(getNextTheme('glass')).toBe('monokai')
    expect(getNextTheme('monokai')).toBe('light')
    expect(getNextTheme('light')).toBe('dark')
    expect(getNextTheme('dark')).toBe('glass')
  })

  it('integrates with toggleTheme to cycle through updated themes', () => {
    const newCycle: ResolvedTheme[] = ['light', 'glass']
    updateToggleCycle(newCycle)

    // Start with light
    localStorage.setItem('theme', 'light')
    applyTheme('light')

    // Toggle should go to glass
    const next = toggleTheme()
    expect(next).toBe('glass')
  })
})
