import fs from 'node:fs'
import path from 'node:path'
import { beforeEach, describe, expect, it } from 'vitest'
import {
  AUTH_SHELL_BACKDROP_ID,
  ensureAuthShellBackdrop,
  isAuthShellRoute,
  syncAuthShellBackdrop,
} from '../auth/auth-shell-backdrop'

function readAuthShellCssRule() {
  const stylesPath = path.resolve(process.cwd(), 'src/styles/global.css')
  const styles = fs.readFileSync(stylesPath, 'utf8')
  return styles.match(/\.auth-shell\s*\{(?<rule>[^}]*)\}/m)?.groups?.rule || ''
}

describe('auth-shell-backdrop', () => {
  beforeEach(() => {
    document.body.innerHTML = '<div id="root"></div>'
  })

  it('recognizes login, register, and auth callback routes', () => {
    expect(isAuthShellRoute('/login')).toBe(true)
    expect(isAuthShellRoute('/login/reset')).toBe(true)
    expect(isAuthShellRoute('/register')).toBe(true)
    expect(isAuthShellRoute('/register/invite')).toBe(true)
    expect(isAuthShellRoute('/auth/callback')).toBe(true)
    expect(isAuthShellRoute('/app')).toBe(false)
    expect(isAuthShellRoute('/pricing')).toBe(false)
  })

  it('creates the auth backdrop with the expected styling', () => {
    const backdrop = ensureAuthShellBackdrop()

    expect(backdrop.id).toBe(AUTH_SHELL_BACKDROP_ID)
    expect(backdrop.getAttribute('data-testid')).toBe('supertokens-auth-backdrop')
    expect(backdrop.style.position).toBe('fixed')
    expect(backdrop.style.pointerEvents).toBe('none')
    expect(backdrop.style.zIndex).toBe('0')
  })

  it('keeps auth route content above the decorative backdrop layer', () => {
    const authShellRule = readAuthShellCssRule()

    expect(authShellRule).toContain('position: relative')
    expect(authShellRule).toContain('z-index: 1')
    expect(authShellRule).toContain('isolation: isolate')
  })

  it('removes the auth backdrop when navigation leaves auth routes', () => {
    syncAuthShellBackdrop('/login')
    expect(document.getElementById(AUTH_SHELL_BACKDROP_ID)).not.toBeNull()

    syncAuthShellBackdrop('/pricing')
    expect(document.getElementById(AUTH_SHELL_BACKDROP_ID)).toBeNull()
  })

  it('does not duplicate the backdrop across repeated auth-route syncs', () => {
    syncAuthShellBackdrop('/login')
    syncAuthShellBackdrop('/register')
    syncAuthShellBackdrop('/auth/callback')

    expect(document.querySelectorAll(`#${AUTH_SHELL_BACKDROP_ID}`)).toHaveLength(1)
  })
})
