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 → extras overrides', () => {
  it('passes manifest.name and robots Disallow to buildExtrasForPage via buildZip extras', async () => {
    render(<BuilderClientPage />)

    const manifestName = 'My App Custom'
    const robotsDisallow = '/private\n/tmp'

    const nameInput = await screen.findByLabelText('Manifest Name')
    fireEvent.change(nameInput, { target: { value: manifestName } })

    const robotsInput = await screen.findByLabelText('Robots Disallow')
    fireEvent.change(robotsInput, { target: { value: robotsDisallow } })

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

    expect(buildZipSpy).toHaveBeenCalled()
    const first = buildZipSpy.mock.calls[0]
    expect(first && first[0]).toBeTruthy()
    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 robotsRaw = td.decode(extras['robots.txt'])
    const manifest = JSON.parse(manifestRaw)

    expect(manifest.name).toBe(manifestName)
    expect(robotsRaw).toMatch(/Disallow: \/private/)
    expect(robotsRaw).toMatch(/Disallow: \/tmp/)
    // integrity index should be included
    expect(Object.prototype.hasOwnProperty.call(extras, 'assets.integrity.index.json')).toBe(true)
  })
})
