import Handsontable from 'handsontable'
import { makeNumberFormatRenderer } from './renderers.utils'

describe('makeNumberFormatRenderer', () => {
  it('renders a numeric cell as EUR currency without changing the value', () => {
    const container = document.createElement('div')
    document.body.appendChild(container)

    const hot = new Handsontable(container, {
      data: [{ amt: 1025 }],
      columns: [
        {
          data: 'amt',
          type: 'numeric',
          renderer: makeNumberFormatRenderer(
            '{"style":"currency","currency":"EUR"}'
          )
        }
      ],
      licenseKey: 'non-commercial-and-evaluation'
    })
    hot.render()

    const td = hot.getCell(0, 0)
    // Display is formatted as currency...
    expect(td?.textContent).toContain('€')
    expect(td?.textContent).toContain('1,025')
    // ...but the stored value is untouched
    expect(hot.getDataAtCell(0, 0)).toEqual(1025)

    hot.destroy()
    container.remove()
  })

  it('is overridden by numbro numericFormat (why DcValidator clears it for NUMBER_FORMAT cols)', () => {
    // Regression note: on a `type: 'numeric'` column, a `numericFormat` makes
    // HOT re-render via numbro and drop our currency symbol. DcValidator clears
    // numericFormat on NUMBER_FORMAT columns so the Intl renderer wins.
    const container = document.createElement('div')
    document.body.appendChild(container)

    const hot = new Handsontable(container, {
      data: [{ amt: 1025 }],
      columns: [
        {
          data: 'amt',
          type: 'numeric',
          numericFormat: { pattern: '0,0', culture: 'en-US' },
          renderer: makeNumberFormatRenderer(
            '{"style":"currency","currency":"EUR"}'
          )
        }
      ],
      licenseKey: 'non-commercial-and-evaluation'
    })
    hot.render()

    const td = hot.getCell(0, 0)
    expect(td?.textContent).not.toContain('€')

    hot.destroy()
    container.remove()
  })

  it('falls back to a plain number when options JSON is invalid', () => {
    const container = document.createElement('div')
    document.body.appendChild(container)

    const hot = new Handsontable(container, {
      data: [{ amt: 1025 }],
      columns: [
        {
          data: 'amt',
          type: 'numeric',
          renderer: makeNumberFormatRenderer('not json')
        }
      ],
      licenseKey: 'non-commercial-and-evaluation'
    })
    hot.render()

    const td = hot.getCell(0, 0)
    expect(td?.textContent).not.toContain('€')

    hot.destroy()
    container.remove()
  })
})
