import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render } from '@testing-library/react'

import { ThemeStudio } from './theme-studio'
import { _resetCache, getTheme, teardownTheme } from '../services/theme-engine/engine'

function resetDom(): void {
  document.head.innerHTML = ''
  document.body.innerHTML = ''
  document.documentElement.removeAttribute('data-theme')
  document.documentElement.removeAttribute('data-accent')
  document.documentElement.removeAttribute('data-density')
  document.documentElement.removeAttribute('data-icon-set')
  document.documentElement.removeAttribute('style')
}

describe('React ThemeStudio', () => {
  beforeEach(() => {
    localStorage.clear()
    teardownTheme()
    _resetCache()
    resetDom()
  })

  it('renders the vanilla theme studio into a React container and seeds an initial theme once', () => {
    const onThemeChange = vi.fn()

    const { container, rerender } = render(
      <ThemeStudio
        initialTheme={{ mode: 'glass', accent: 'violet' }}
        onThemeChange={onThemeChange}
        showTabs={false}
        showHeader={false}
        showBrandSection={false}
        className="custom-studio"
      />
    )

    expect(container.querySelector('[data-slot="theme-studio"]')).toBeTruthy()
    expect(container.querySelector('.custom-studio')).toBeTruthy()
    expect(container.textContent).toContain('Start from a preset')
    expect(container.querySelector('.theme-studio-brand-note')).toBeNull()
    expect(container.textContent).not.toContain('Appearance')
    expect(getTheme().mode).toBe('glass')
    expect(getTheme().accent).toBe('violet')
    expect(onThemeChange).toHaveBeenCalled()

    rerender(
      <ThemeStudio initialTheme={{ mode: 'light', accent: 'rose' }} onThemeChange={onThemeChange} />
    )

    expect(getTheme().mode).toBe('glass')
    expect(getTheme().accent).toBe('violet')
  })

  it('respects seedStrategy="never" and leaves a persisted theme alone', () => {
    localStorage.setItem(
      'cm-theme-v1',
      JSON.stringify({
        ...getTheme(),
        mode: 'dark',
        accent: 'cyan',
      })
    )
    teardownTheme()
    _resetCache()

    render(<ThemeStudio initialTheme={{ mode: 'light', accent: 'rose' }} seedStrategy="never" />)

    expect(getTheme().mode).toBe('dark')
    expect(getTheme().accent).toBe('cyan')
  })
})
