import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { NextIntlClientProvider } from 'next-intl'
import BuilderClientPage from '@/components/BuilderClientPage'

declare global {
  interface Window { __exportPreview?: () => { html: string } }
}

describe('BuilderClientPage 이미지 옵션 UI 연동', () => {
  beforeEach(() => {
    // JSDOM 환경 초기화용
    window.__exportPreview = undefined
  })

  it('기본값으로 img에 loading="lazy" decoding="async"가 포함된다', async () => {
    render(
      <NextIntlClientProvider locale="en" messages={{}}>
        <BuilderClientPage />
      </NextIntlClientProvider>
    )
    // Ensure a hero section with image is present
    const addHeroBtn = screen.getByTestId('btn-add-hero')
    addHeroBtn.click()
    expect(typeof window.__exportPreview).toBe('function')
    await waitFor(() => {
      const out = window.__exportPreview!()
      expect(out.html).toContain('loading="lazy"')
      expect(out.html).toContain('decoding="async"')
    })
  })

  it('UI에서 eager/sync로 변경 시 preview HTML에 반영된다', async () => {
    render(
      <NextIntlClientProvider locale="en" messages={{}}>
        <BuilderClientPage />
      </NextIntlClientProvider>
    )
    const addHeroBtn = screen.getByTestId('btn-add-hero')
    addHeroBtn.click()
    const loadingSelect = screen.getByLabelText('Image Loading') as HTMLSelectElement
    const decodingSelect = screen.getByLabelText('Image Decoding') as HTMLSelectElement

    fireEvent.change(loadingSelect, { target: { value: 'eager' } })
    fireEvent.change(decodingSelect, { target: { value: 'sync' } })

    await waitFor(() => {
      const out = window.__exportPreview!()
      expect(out.html).toContain('loading="eager"')
      expect(out.html).toContain('decoding="sync"')
    })
  })
})
