import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
  isParentAuthenticated,
  isUserLoggedIn,
  loginUser,
  initAuthSync,
  authenticateParent,
  logoutParent,
} from '../auth'
import { nextTick } from 'vue'

// Stub window.location to prevent jsdom "navigation to another Document" warnings
// triggered when the auth store sets window.location.href on logout.
const locationStub = { href: '', pathname: '/', assign: vi.fn(), replace: vi.fn(), reload: vi.fn() }
Object.defineProperty(window, 'location', { value: locationStub, writable: true })

// Helper to mock localStorage
global.localStorage = {
  store: {} as Record<string, string>,
  getItem(key: string) {
    return this.store[key] || null
  },
  setItem(key: string, value: string) {
    this.store[key] = value
  },
  removeItem(key: string) {
    delete this.store[key]
  },
  clear() {
    this.store = {}
  },
} as any

describe('auth store - child mode on login', () => {
  beforeEach(() => {
    // Use authenticateParent() to set up parent-mode state
    authenticateParent(false)
  })

  afterEach(() => {
    logoutParent()
  })

  it('should clear isParentAuthenticated and localStorage on loginUser()', async () => {
    expect(isParentAuthenticated.value).toBe(true)
    loginUser()
    await nextTick()
    expect(isParentAuthenticated.value).toBe(false)
  })

  it('logs out on cross-tab storage logout event', async () => {
    initAuthSync()
    isUserLoggedIn.value = true
    authenticateParent(false)
    expect(isParentAuthenticated.value).toBe(true)

    const logoutEvent = new StorageEvent('storage', {
      key: 'authSyncEvent',
      newValue: JSON.stringify({ type: 'logout', at: Date.now() }),
    })
    window.dispatchEvent(logoutEvent)

    await nextTick()
    expect(isUserLoggedIn.value).toBe(false)
    expect(isParentAuthenticated.value).toBe(false)
  })

  it('exits parent mode on cross-tab parent_logout storage event', async () => {
    initAuthSync()
    authenticateParent(false)
    expect(isParentAuthenticated.value).toBe(true)

    // Simulate being on a /parent route in this tab
    locationStub.pathname = '/parent'

    const parentLogoutEvent = new StorageEvent('storage', {
      key: 'authSyncEvent',
      newValue: JSON.stringify({ type: 'parent_logout', at: Date.now() }),
    })
    window.dispatchEvent(parentLogoutEvent)

    await nextTick()
    expect(isParentAuthenticated.value).toBe(false)
    expect(locationStub.href).toBe('/child')

    // Reset for other tests
    locationStub.pathname = '/'
  })
})
