/**
 * (persist Accept-Language to localStorage by locale; edge: unknown/empty).
 */
import React from 'react'
import { render } from '@testing-library/react'
import LocaleWatcher from '../locale-provider'

const mockSetItem = jest.fn()
beforeAll(() => {
  Object.defineProperty(window, 'localStorage', {
    value: {
      getItem: jest.fn(),
      setItem: mockSetItem,
      removeItem: jest.fn(),
      clear: jest.fn(),
    },
    writable: true,
  })
})

describe('[providers/locale-provider] LocaleWatcher', () => {
  beforeEach(() => {
    mockSetItem.mockClear()
  })

  describe('render', () => {
    it('renders nothing (fragment)', () => {
      const { container } = render(<LocaleWatcher locale="vi" />)
      expect(container.firstChild).toBeNull()
    })
  })

  describe('Accept-Language persistence', () => {
    it('maps vi → vi_VN', () => {
      render(<LocaleWatcher locale="vi" />)
      expect(mockSetItem).toHaveBeenCalledWith(expect.any(String), 'vi_VN')
    })

    it('maps en → en_US', () => {
      render(<LocaleWatcher locale="en" />)
      expect(mockSetItem).toHaveBeenCalledWith(expect.any(String), 'en_US')
    })

    it('falls back to default accept-language for unknown locale', () => {
      render(<LocaleWatcher locale="xx" />)
      expect(mockSetItem).toHaveBeenCalledWith(expect.any(String), 'vi_VN')
    })

    it('does not write when locale is empty', () => {
      render(<LocaleWatcher locale={'' as any} />)
      expect(mockSetItem).not.toHaveBeenCalled()
    })
  })
})
