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 polish', () => {
  it('uses a dropdown for Manifest Display and passes selected value', async () => {
    render(<BuilderClientPage />)

    // choose display = minimal-ui
    const displaySelect = await screen.findByLabelText('Manifest Display')
    fireEvent.change(displaySelect, { target: { value: 'minimal-ui' } })

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

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

  it('ignores invalid theme_color override and keeps default theme when not a hex', async () => {
    render(<BuilderClientPage />)

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

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

    const first = buildZipSpy.mock.calls[0]
    const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
    const td = new TextDecoder()
    const manifest = JSON.parse(td.decode(extras['site.webmanifest']))
    expect(manifest.theme_color).toBe('#0ea5e9') // default from page.theme.primaryColor
  })
})
