const test = require('node:test')
const assert = require('node:assert')
const { findSsrHydrationRisks } = require('../src/lib/ssr-hydration-patterns')

function lines(issues) {
  return issues.map((i) => i.line)
}

test('findSsrHydrationRisks flags typeof window and typeof document in render', () => {
  const src = `export default function A() {
  if (typeof window !== "undefined") return null
  return <div />
}`
  const { issues } = findSsrHydrationRisks(src, 'x.jsx')
  assert.ok(issues.some((i) => i.code.includes('typeof')))
})

test('findSsrHydrationRisks skips typeof window inside useEffect callback', () => {
  const src = `import { useEffect } from "react"
export default function A() {
  useEffect(() => { if (typeof window !== "undefined") {} }, [])
  return <div />
}`
  const { issues } = findSsrHydrationRisks(src, 'x.jsx')
  assert.strictEqual(issues.filter((i) => i.code.includes('typeof')).length, 0)
})

test('findSsrHydrationRisks flags Math.random and Date.now in render', () => {
  const src = `export default function A() {
  const x = Math.random()
  const y = Date.now()
  return <div>{x}{y}</div>
}`
  const { issues } = findSsrHydrationRisks(src, 'x.jsx')
  assert.ok(issues.some((i) => i.code === 'Math.random()'))
  assert.ok(issues.some((i) => i.code === 'Date.now()'))
})

test('findSsrHydrationRisks flags useMemo factory (runs on server)', () => {
  const src = `import { useMemo } from "react"
export default function A() {
  const w = useMemo(() => window.innerWidth, [])
  return <div>{w}</div>
}`
  const { issues } = findSsrHydrationRisks(src, 'x.jsx')
  assert.ok(issues.some((i) => i.code.includes('window')))
})

test('findSsrHydrationRisks skips window in onClick handler', () => {
  const src = `export default function A() {
  return <button type="button" onClick={() => window.alert("x")} />
}`
  const { issues } = findSsrHydrationRisks(src, 'x.jsx')
  assert.strictEqual(issues.length, 0)
})

test('findSsrHydrationRisks reports line numbers in order', () => {
  const src = `export default function A() {
  const a = Date.now()
  const b = Math.random()
  return <div />
}`
  const { issues } = findSsrHydrationRisks(src, 'x.jsx')
  const ls = lines(issues)
  assert.deepStrictEqual(ls, [2, 3])
})
