const test = require('node:test')
const assert = require('node:assert/strict')
const fs = require('fs')
const path = require('path')
const webTranspile = require('../src/lib/transpile')
const {
  guessWebCodeTypeFromSource,
  resolveWebCodeType,
} = webTranspile

test('guessWebCodeTypeFromSource detects as const and typed props', () => {
  const snippet =
    'const x = [] as const;\nexport function F({ a }: { a?: string }) {\n  return null;\n}'
  assert.equal(guessWebCodeTypeFromSource(snippet), 'tsx')
})

test('resolveWebCodeType upgrades jsx to tsx when source has TS syntax', () => {
  const code = 'const T = [] as const;\nexport function C() {}'
  assert.equal(resolveWebCodeType(code, 'jsx'), 'tsx')
  assert.equal(resolveWebCodeType(code, 'js'), 'tsx')
  assert.equal(resolveWebCodeType(code, 'ts'), 'tsx')
})

test('resolveWebCodeType preserves html', () => {
  assert.equal(resolveWebCodeType('<div/>', 'html'), 'html')
})

test('resolveWebCodeType leaves plain jsx alone', () => {
  const plain = 'export function C() { return <div /> }'
  assert.equal(resolveWebCodeType(plain, 'jsx'), 'jsx')
})

test('guessWebCodeTypeFromSource detects interface declarations', () => {
  const code = 'interface TimeLeft { days: number }\nexport default function C() { return null }'
  assert.equal(guessWebCodeTypeFromSource(code), 'tsx')
})

test('webTranspile accepts interface declarations when codeType is jsx', () => {
  const code = [
    'interface TimeLeft { days: number; hours: number }',
    'export default function C() {',
    '  const [t] = useState<TimeLeft>({ days: 0, hours: 0 })',
    '  return <div>{t.days}</div>',
    '}',
  ].join('\n')
  assert.doesNotThrow(() => webTranspile(code, 'jsx', 'countdown-banner'))
})

test('webTranspile accepts real template with interfaces (jsx codeType)', () => {
  const templatePath = path.join(
    __dirname,
    '..',
    'test-library',
    '2-Column-with-Content-Below.tsx',
  )
  if (!fs.existsSync(templatePath)) return
  const code = fs.readFileSync(templatePath, 'utf8')
  if (!/\binterface\s+/.test(code)) return
  assert.doesNotThrow(() => webTranspile(code, 'jsx', 'two-column'))
})
