import { afterEach, describe, expect, it, vi } from 'vitest'
import { buildFrameUrl, FRAME_HEIGHT, getDefaultFramePath } from './WorkspaceFrame'


afterEach(() => {
  vi.unstubAllGlobals()
})

function stubBrowser({ cookie = '', origin = 'https://market.example' }: { cookie?: string; origin?: string } = {}) {
  const parsed = new URL(origin)
  vi.stubGlobal('window', {
    location: { origin, hostname: parsed.hostname, protocol: parsed.protocol, replace: vi.fn() },
  })
  vi.stubGlobal('document', { cookie })
}

describe('WorkspaceFrame helpers', () => {
  it('uses the dashboard sign-in path during server rendering', () => {
    vi.stubGlobal('window', undefined)

    expect(getDefaultFramePath('sign-in')).toBe('/dashboard/sign-in')
    expect(buildFrameUrl('https://dashboard.example/dashboard', '/dashboard/sign-in')).toBe('/dashboard/sign-in')
  })

  it('keeps users with an employee token on the embedded sign-in path until the dashboard confirms login', () => {
    stubBrowser({ cookie: 'other=1; employee_session=token_123' })

    expect(getDefaultFramePath('sign-in')).toBe('/dashboard/sign-in')
  })

  it('keeps unauthenticated visitors on the embedded sign-in path', () => {
    stubBrowser({ cookie: 'storefront-language=fr' })

    expect(getDefaultFramePath('sign-in')).toBe('/dashboard/sign-in')
  })

  it('rewrites a configured app base to the requested embedded path and query', () => {
    stubBrowser({ origin: 'https://market.example' })

    expect(buildFrameUrl('https://dashboard.example/dashboard', '/dashboard/reset-password?token=abc')).toBe(
      'https://market.example/dashboard/reset-password?token=abc',
    )
  })

  it('documents the iframe height contract used by embedded dashboard surfaces', () => {
    expect(FRAME_HEIGHT).toBe('calc(100vh - 56px)')
  })
})
