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')

test('legacy from-jsx hoists $() fields to module scope for stable ids', () => {
  const src = `export function Home() {
  return (
    <div>
      <Sub />
    </div>
  );
}
function Sub() {
  return <p>Hello</p>;
}
export default Home;
`
  const d = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-nest-'))
  const f = path.join(d, 'nest.jsx')
  fs.writeFileSync(f, src)
  const { output } = runCodemod({
    source: src,
    filePath: f,
    cssMode: 'hybrid',
    namingStrategy: 'camelComponent',
    depsFilePath: null,
    fieldMapPath: path.join(d, '.bild', 'n.field-map.json'),
    groupingStyle: 'lineComments',
  })
  assert.ok(output.includes('const helloText = $(helloText:RichText={ text: "Hello" })'))
  assert.ok(output.includes('{helloText.text}'))
  const subIdx = output.indexOf('function Sub()')
  const constIdx = output.indexOf('const helloText = $(helloText:RichText={ text: "Hello" })')
  assert.ok(constIdx >= 0 && subIdx >= 0 && constIdx < subIdx, 'RichText $() should be at module scope')
})
