import { describe, it, expect, vi } from 'vitest'
import { render } from '@testing-library/react'

import { YamlOverrideEditor } from '../yaml-override-editor'

describe('YamlOverrideEditor', () => {
  it('mounts and exposes the host slot', () => {
    const { container } = render(<YamlOverrideEditor value="foo: bar\n" onChange={() => {}} />)
    expect(container.querySelector('[data-slot="yaml-override-editor"]')).toBeTruthy()
    expect(container.querySelector('[data-slot="yaml-override-editor-host"]')).toBeTruthy()
  })

  it('omits the placeholder legend when no placeholders are provided', () => {
    const { container } = render(<YamlOverrideEditor value="key: val\n" onChange={() => {}} />)
    expect(container.querySelector('[data-slot="yaml-override-editor-legend"]')).toBeNull()
  })

  it('renders a placeholder legend chip per declared placeholder', () => {
    const { container } = render(
      <YamlOverrideEditor
        value="dataset: TODO\nversion: TODO\n"
        onChange={() => {}}
        placeholders={{
          __DATASET__: { label: 'Dataset id', description: 'Replace with the dataset id' },
          __VERSION__: { label: 'Version' },
        }}
      />
    )
    const legend = container.querySelector('[data-slot="yaml-override-editor-legend"]')
    expect(legend).toBeTruthy()
    const codes = legend?.querySelectorAll('code') ?? []
    const codeTexts = Array.from(codes).map(c => c.textContent)
    expect(codeTexts).toContain('__DATASET__')
    expect(codeTexts).toContain('__VERSION__')
    expect(legend?.textContent).toContain('Dataset id')
    expect(legend?.textContent).toContain('Version')
  })

  it('honors a numeric height by setting an explicit pixel style', () => {
    const { container } = render(<YamlOverrideEditor value="" onChange={() => {}} height={400} />)
    const host = container.querySelector(
      '[data-slot="yaml-override-editor-host"]'
    ) as HTMLElement | null
    expect(host?.style.height).toBe('400px')
  })

  it('honors a string height verbatim', () => {
    const { container } = render(<YamlOverrideEditor value="" onChange={() => {}} height="50vh" />)
    const host = container.querySelector(
      '[data-slot="yaml-override-editor-host"]'
    ) as HTMLElement | null
    expect(host?.style.height).toBe('50vh')
  })

  it('forwards className to the wrapper', () => {
    const { container } = render(
      <YamlOverrideEditor value="" onChange={() => {}} className="custom-yoe" />
    )
    const wrap = container.querySelector('[data-slot="yaml-override-editor"]')
    expect(wrap?.className).toContain('custom-yoe')
  })

  it('mounts in readOnly mode without throwing', () => {
    const onChange = vi.fn()
    expect(() =>
      render(<YamlOverrideEditor value="x: 1\n" onChange={onChange} readOnly />)
    ).not.toThrow()
  })
})
