import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import StudioLayout from '../StudioLayout'

let pageMock = { url: '/studio', props: {} }
const originalLocation = window.location

vi.mock('@inertiajs/react', () => ({
  Link: ({ href, children, ...props }) => <a href={href} {...props}>{children}</a>,
  usePage: () => pageMock,
}))

vi.mock('../../utils/studioEvents', () => ({
  studioModule: () => 'overview',
  studioSurface: () => '/studio',
  trackStudioEvent: vi.fn(),
}))

describe('StudioLayout group context persistence', () => {
  beforeEach(() => {
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: {
        ...originalLocation,
        assign: vi.fn(),
      },
    })

    vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => null)
    vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {})
  })

  afterEach(() => {
    cleanup()
    vi.restoreAllMocks()
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: originalLocation,
    })
  })

  it('restores the last selected group context on supported personal studio routes', async () => {
    pageMock = {
      url: '/studio',
      props: {
        studio_groups: [
          {
            slug: 'warp-collective',
            name: 'Warp Collective',
            studio_url: '/studio/groups/warp-collective',
          },
        ],
        studioGroup: null,
      },
    }

    Storage.prototype.getItem.mockImplementation((key) => (key === 'sb.studio.last-context' ? 'warp-collective' : null))

    render(
      <StudioLayout title="Studio" subtitle="Overview">
        <div>Body</div>
      </StudioLayout>,
    )

    await waitFor(() => {
      expect(window.location.assign).toHaveBeenCalledWith('/studio/groups/warp-collective')
    })
  })

  it('stores the selected group slug and navigates into that group context', async () => {
    pageMock = {
      url: '/studio',
      props: {
        studio_groups: [
          {
            slug: 'warp-collective',
            name: 'Warp Collective',
            studio_url: '/studio/groups/warp-collective',
          },
        ],
        studioGroup: null,
      },
    }

    render(
      <StudioLayout title="Studio" subtitle="Overview">
        <div>Body</div>
      </StudioLayout>,
    )

    const [contextSwitcher] = screen.getAllByRole('combobox')
    await userEvent.selectOptions(contextSwitcher, 'warp-collective')

    expect(Storage.prototype.setItem).toHaveBeenCalledWith('sb.studio.last-context', 'warp-collective')
    await waitFor(() => {
      expect(window.location.assign).toHaveBeenCalledWith('/studio/groups/warp-collective')
    })
  })
})