// @vitest-environment happy-dom
import { renderHook, waitFor } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'

import type { AppearanceSnapshot } from '../../components/ThemeProvider.js'

const applyAppearance = vi.fn<(snapshot: AppearanceSnapshot) => void>()
vi.mock('../../components/ThemeProvider.js', () => ({
  useTheme: () => ({ applyAppearance }),
}))

const cmsApi = vi.fn()
vi.mock('../../lib/api.js', () => ({ cmsApi }))

const { useAppearanceBootstrap } = await import('../../hooks/useAppearanceBootstrap.js')

describe('useAppearanceBootstrap', () => {
  it('fetches /appearance and applies the snapshot when a session is present', async () => {
    applyAppearance.mockClear()
    cmsApi.mockResolvedValueOnce({
      data: {
        appearance: {
          adminColorModeDefault: 'light',
          adminAccentColor: 'purple',
          sidebarDensity: 'default',
          contentFont: 'DM Sans',
          reduceMotion: false,
        },
        brand: {
          mode: 'customAdminBrand',
          adminPrimaryLogoAssetId: 'logo-1',
        },
        resolved: { admin: { initials: 'UP' } },
        assets: [
          {
            id: 'logo-1',
            publicUrl: 'https://cdn.example.com/logo.svg',
            mimeType: 'image/svg+xml',
          },
        ],
        siteTitle: 'UpChat',
      },
    })

    renderHook(() => useAppearanceBootstrap({ userId: 'user-1' }))

    await waitFor(() => expect(cmsApi).toHaveBeenCalledWith('/appearance'))
    await waitFor(() =>
      expect(applyAppearance).toHaveBeenCalledWith(
        expect.objectContaining({
          adminBrand: expect.objectContaining({
            primaryUrl: 'https://cdn.example.com/logo.svg',
          }),
        }),
      ),
    )
  })

  it('does not fetch when there is no session', async () => {
    applyAppearance.mockClear()
    cmsApi.mockClear()

    renderHook(() => useAppearanceBootstrap(null))

    await waitFor(() => {
      expect(cmsApi).not.toHaveBeenCalled()
    })
  })
})
