// @vitest-environment happy-dom
import { afterEach, describe, expect, it } from 'vitest'

import { setDocumentFavicon, BRAND_UPDATED_EVENT } from '../../lib/favicon.js'

afterEach(() => {
  document.head.querySelectorAll('link[rel="icon"]').forEach((l) => l.remove())
})

describe('setDocumentFavicon', () => {
  it('creates a link[rel=icon] when the document has none', () => {
    const { created, previousHref, link } = setDocumentFavicon(
      'https://cdn.example.com/fav.png',
      'image/png',
    )
    expect(created).toBe(true)
    expect(previousHref).toBeNull()
    expect(link.rel).toBe('icon')
    const found = document.querySelector<HTMLLinkElement>('link[rel="icon"]')
    expect(found).not.toBeNull()
    expect(found!.href).toContain('fav.png')
    expect(found!.type).toBe('image/png')
  })

  it('updates the existing link in place and reports the previous href', () => {
    const existing = document.createElement('link')
    existing.rel = 'icon'
    existing.href = 'https://cdn.example.com/old.png'
    document.head.appendChild(existing)

    const { created, previousHref, link } = setDocumentFavicon(
      'https://cdn.example.com/new.svg',
      'image/svg+xml',
    )
    expect(created).toBe(false)
    expect(previousHref).toContain('old.png')
    expect(link).toBe(existing)
    expect(existing.href).toContain('new.svg')
    expect(existing.type).toBe('image/svg+xml')
    // Never duplicates the icon link.
    expect(document.querySelectorAll('link[rel="icon"]').length).toBe(1)
  })

  it('preserves the existing type when no new type is provided', () => {
    setDocumentFavicon('https://cdn.example.com/a.png', 'image/png')
    setDocumentFavicon('https://cdn.example.com/b.png')
    const link = document.querySelector<HTMLLinkElement>('link[rel="icon"]')
    expect(link!.href).toContain('b.png')
    expect(link!.type).toBe('image/png')
  })

  it('exposes a stable brand-updated event name', () => {
    expect(BRAND_UPDATED_EVENT).toBe('actuate:brand-updated')
  })
})
