import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import BuilderClientPage from '@/components/BuilderClientPage'

vi.mock('next-intl', () => {
  return {
    useTranslations: () => (key: string) => key,
  }
})

const buildZipSpy = vi.fn(async (_arg: {
  html: string
  css: string
  js: string
  assets: Record<string, Uint8Array>
  extras?: Record<string, Uint8Array>
}) => new Uint8Array([80, 75]))

vi.mock('@/lib/exporter/zip', () => {
  return {
    buildZip: (arg: {
      html: string
      css: string
      js: string
      assets: Record<string, Uint8Array>
      extras?: Record<string, Uint8Array>
    }) => buildZipSpy(arg),
  }
})

describe('Export Options UI → manifest fields', () => {
  it('passes short_name/start_url/display/theme_color to extras manifest JSON', async () => {
    render(<BuilderClientPage />)

    const shortName = 'MyApp'
    const startUrl = '/home'
    const display = 'minimal-ui'
    const themeColor = '#112233'

    const snInput = await screen.findByLabelText('Manifest Short Name')
    fireEvent.change(snInput, { target: { value: shortName } })

    const startInput = await screen.findByLabelText('Manifest Start URL')
    fireEvent.change(startInput, { target: { value: startUrl } })

    const displayInput = await screen.findByLabelText('Manifest Display')
    fireEvent.change(displayInput, { target: { value: display } })

    const colorInput = await screen.findByLabelText('Manifest Theme Color')
    fireEvent.change(colorInput, { target: { value: themeColor } })

    const exportBtn = await screen.findByRole('button', { name: 'builder.action.export' })
    fireEvent.click(exportBtn)

    expect(buildZipSpy).toHaveBeenCalled()
    const first = buildZipSpy.mock.calls[0]
    const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
    const td = new TextDecoder()
    const manifestRaw = td.decode(extras['site.webmanifest'])
    const manifest = JSON.parse(manifestRaw)

    expect(manifest.short_name).toBe(shortName)
    expect(manifest.start_url).toBe(startUrl)
    expect(manifest.display).toBe(display)
    expect(manifest.theme_color).toBe(themeColor)
  })
})
