const test = require('node:test')
const assert = require('node:assert')
const fs = require('fs')
const os = require('os')
const path = require('path')

const { runCodemod } = require('../src/lib/codemod')

/**
 * RichText must not rewire inline typography onto the field object — keep the template
 * markup so CSS cascade and inline styles still apply in the live editor. Typographic
 * literals are copied into the RichText default for CMS overrides only.
 */
test('from-jsx keeps inline typography on element; RichText default mirrors literals', () => {
  const src = `export default function F() {
  return (
    <p style={{ color: '#abc', fontWeight: '700', marginTop: 12 }}>Hello</p>
  )
}
`
  const d = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-richtext-style-'))
  const f = path.join(d, 'C.jsx')
  fs.writeFileSync(f, src)
  const { output } = runCodemod({
    source: src,
    filePath: f,
    cssMode: 'hybrid',
    namingStrategy: 'camelComponent',
    depsFilePath: null,
    fieldMapPath: path.join(d, '.bild', 'c.field-map.json'),
    groupingStyle: 'lineComments',
  })

  assert.match(
    output,
    /\{\s*color:\s*['"]#abc['"],\s*fontWeight:\s*['"]700['"],\s*marginTop:\s*12/,
    'inline style object literals stay — color is not hoisted into a CMS Color binding',
  )
  assert.ok(!/\bcolor\b.*\$\(.*:Color=/s.test(output), 'foreground color stays inline, not lifted to Color template var')
  assert.match(output, /\{helloText\.text\}/)
  assert.match(
    output,
    /RichText=\{\s*text:\s*["']Hello["'],\s*color:\s*["']#abc["'],\s*fontWeight:\s*["']700["']\s*\}/,
  )
})

test('from-jsx: fontStyle and textDecoration alone still populate RichText default', () => {
  const src = `export default function F() {
  return (
    <span style={{ fontStyle: 'italic', textDecoration: 'underline' }}>Hi</span>
  )
}
`
  const d = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-richtext-style2-'))
  const f = path.join(d, 'C.jsx')
  fs.writeFileSync(f, src)
  const { output } = runCodemod({
    source: src,
    filePath: f,
    cssMode: 'hybrid',
    namingStrategy: 'camelComponent',
    depsFilePath: null,
    fieldMapPath: path.join(d, '.bild', 'c.field-map.json'),
    groupingStyle: 'lineComments',
  })

  assert.match(output, /\{\s*fontStyle:\s*['"]italic['"],\s*textDecoration:\s*['"]underline['"]/)
  assert.match(
    output,
    /RichText=\{\s*text:\s*["']Hi["'],\s*fontStyle:\s*["']italic["'],\s*textDecoration:\s*["']underline["']\s*\}/,
  )
})
