import { fixture, assert, html } from '@open-wc/testing'
import CircularProgress from '../../../src/md/progress/internals/CircularProgress.js'
import '../../../src/md/progress/ui-circular-progress.js'

describe('UiCircularProgress', () => {
  async function basicFixture(): Promise<CircularProgress> {
    return fixture(html`<ui-circular-progress></ui-circular-progress>`)
  }

  async function determinateFixture(): Promise<CircularProgress> {
    return fixture(html`<ui-circular-progress value="50" max="100"></ui-circular-progress>`)
  }

  async function indeterminateFixture(): Promise<CircularProgress> {
    return fixture(html`<ui-circular-progress indeterminate></ui-circular-progress>`)
  }

  async function fourColorFixture(): Promise<CircularProgress> {
    return fixture(html`<ui-circular-progress indeterminate fourcolor></ui-circular-progress>`)
  }

  async function disabledFixture(): Promise<CircularProgress> {
    return fixture(html`<ui-circular-progress disabled value="30"></ui-circular-progress>`)
  }

  async function customRangeFixture(): Promise<CircularProgress> {
    return fixture(html`<ui-circular-progress min="10" max="200" value="100"></ui-circular-progress>`)
  }

  // Accessibility-compliant fixtures for accessibility testing
  async function accessibleBasicFixture(): Promise<CircularProgress> {
    return fixture(html`<ui-circular-progress aria-label="Loading progress"></ui-circular-progress>`)
  }

  async function accessibleDeterminateFixture(): Promise<CircularProgress> {
    return fixture(
      html`<ui-circular-progress value="50" max="100" aria-label="Upload progress"></ui-circular-progress>`
    )
  }

  async function accessibleIndeterminateFixture(): Promise<CircularProgress> {
    return fixture(html`<ui-circular-progress indeterminate aria-label="Processing"></ui-circular-progress>`)
  }

  async function accessibleFourColorFixture(): Promise<CircularProgress> {
    return fixture(
      html`<ui-circular-progress indeterminate fourcolor aria-label="Loading with colors"></ui-circular-progress>`
    )
  }

  async function accessibleDisabledFixture(): Promise<CircularProgress> {
    return fixture(html`<ui-circular-progress disabled value="30" aria-label="Completed task"></ui-circular-progress>`)
  }

  describe('Basic Properties', () => {
    let progress: CircularProgress

    beforeEach(async () => {
      progress = await basicFixture()
    })

    it('sets default values', () => {
      assert.equal(progress.min, 0, 'default min should be 0')
      assert.equal(progress.max, 100, 'default max should be 100')
      assert.equal(progress.value, 0, 'default value should be 0')
      assert.equal(progress.fourColor, false, 'default fourColor should be false')
      assert.equal(progress.disabled, false, 'default disabled should be false')
      assert.isUndefined(progress.indeterminate, 'default indeterminate should be undefined')
    })

    it('sets and gets value property', async () => {
      progress.value = 50
      await progress.updateComplete
      assert.equal(progress.value, 50, 'value should be set to 50')
    })

    it('sets and gets max property', async () => {
      progress.max = 200
      await progress.updateComplete
      assert.equal(progress.max, 200, 'max should be set to 200')
    })

    it('sets and gets min property', async () => {
      progress.min = 10
      await progress.updateComplete
      assert.equal(progress.min, 10, 'min should be set to 10')
    })

    it('sets and gets fourColor property', async () => {
      progress.fourColor = true
      await progress.updateComplete
      assert.equal(progress.fourColor, true, 'fourColor should be set to true')
    })

    it('sets and gets disabled property', async () => {
      progress.disabled = true
      await progress.updateComplete
      assert.equal(progress.disabled, true, 'disabled should be set to true')
    })

    it('sets and gets indeterminate property', async () => {
      progress.indeterminate = true
      await progress.updateComplete
      assert.equal(progress.indeterminate, true, 'indeterminate should be set to true')
    })
  })

  describe('Value Validation and Clamping', () => {
    let progress: CircularProgress

    beforeEach(async () => {
      progress = await customRangeFixture()
    })

    it('clamps value to max', async () => {
      progress.value = 250
      await progress.updateComplete
      assert.equal(progress.value, progress.max, 'value should be clamped to max')
    })

    it('clamps value to min', async () => {
      progress.value = 5
      await progress.updateComplete
      assert.equal(progress.value, progress.min, 'value should be clamped to min')
    })

    it('handles step values correctly', async () => {
      progress.step = 10
      progress.value = 25
      await progress.updateComplete
      assert.equal(progress.value, 30, 'value should be stepped to nearest step value')
    })

    it('calculates ratio correctly', async () => {
      progress.min = 0
      progress.max = 100
      progress.value = 25
      await progress.updateComplete
      assert.equal(progress.ratio, 25, 'ratio should be 25% for value 25/100')
    })

    it('handles zero denominator in ratio calculation', async () => {
      progress.min = 50
      progress.max = 50
      progress.value = 50
      await progress.updateComplete
      assert.equal(progress.ratio, 0, 'ratio should be 0 when min equals max')
    })
  })

  describe('Rendering States', () => {
    describe('Determinate State', () => {
      let progress: CircularProgress

      beforeEach(async () => {
        progress = await determinateFixture()
      })

      it('renders SVG container for determinate progress', async () => {
        const svg = progress.shadowRoot?.querySelector('svg')
        assert.exists(svg, 'should render SVG element')
        assert.equal(svg?.getAttribute('viewBox'), '0 0 4800 4800', 'should have correct viewBox')
      })

      it('renders track and active track circles', async () => {
        const track = progress.shadowRoot?.querySelector('.track')
        const activeTrack = progress.shadowRoot?.querySelector('.active-track')

        assert.exists(track, 'should render track circle')
        assert.exists(activeTrack, 'should render active track circle')
        assert.equal(track?.getAttribute('pathLength'), '100', 'track should have pathLength 100')
        assert.equal(activeTrack?.getAttribute('pathLength'), '100', 'active track should have pathLength 100')
      })

      it('calculates correct stroke-dashoffset for progress value', async () => {
        const activeTrack = progress.shadowRoot?.querySelector('.active-track')
        const expectedOffset = (1 - progress.value / progress.max) * 100
        assert.equal(
          activeTrack?.getAttribute('stroke-dashoffset'),
          String(expectedOffset),
          'should calculate correct dashoffset'
        )
      })

      it('updates stroke-dashoffset when value changes', async () => {
        progress.value = 75
        await progress.updateComplete

        const activeTrack = progress.shadowRoot?.querySelector('.active-track')
        const expectedOffset = (1 - 75 / 100) * 100
        assert.equal(
          activeTrack?.getAttribute('stroke-dashoffset'),
          String(expectedOffset),
          'should update dashoffset when value changes'
        )
      })
    })

    describe('Indeterminate State', () => {
      let progress: CircularProgress

      beforeEach(async () => {
        progress = await indeterminateFixture()
      })

      it('renders spinner container for indeterminate progress', async () => {
        const spinner = progress.shadowRoot?.querySelector('.spinner')
        assert.exists(spinner, 'should render spinner element')
      })

      it('renders left and right containers', async () => {
        const left = progress.shadowRoot?.querySelector('.left')
        const right = progress.shadowRoot?.querySelector('.right')

        assert.exists(left, 'should render left container')
        assert.exists(right, 'should render right container')
      })

      it('renders circle elements for animation', async () => {
        const circles = progress.shadowRoot?.querySelectorAll('.circle')
        assert.equal(circles?.length, 2, 'should render 2 circle elements')
      })

      it('does not render SVG elements in indeterminate mode', async () => {
        const svg = progress.shadowRoot?.querySelector('svg')
        assert.isNull(svg, 'should not render SVG in indeterminate mode')
      })
    })

    describe('Four Color Animation', () => {
      let progress: CircularProgress

      beforeEach(async () => {
        progress = await fourColorFixture()
      })

      it('applies fourcolor attribute when fourColor is true', async () => {
        assert.isTrue(progress.hasAttribute('fourcolor'), 'should have fourcolor attribute')
      })

      it('removes fourcolor attribute when fourColor is false', async () => {
        progress.fourColor = false
        await progress.updateComplete
        assert.isFalse(progress.hasAttribute('fourcolor'), 'should not have fourcolor attribute')
      })
    })
  })

  describe('Accessibility', () => {
    describe('ARIA Attributes', () => {
      let progress: CircularProgress

      beforeEach(async () => {
        progress = await basicFixture()
      })

      it('has correct role attribute', () => {
        assert.equal(progress.getAttribute('role'), 'progressbar', 'should have progressbar role')
      })

      it('sets aria-valuemin attribute', async () => {
        progress.min = 10
        await progress.updateComplete
        assert.equal(progress.getAttribute('aria-valuemin'), '10', 'should set aria-valuemin')
      })

      it('sets aria-valuemax attribute', async () => {
        progress.max = 200
        await progress.updateComplete
        assert.equal(progress.getAttribute('aria-valuemax'), '200', 'should set aria-valuemax')
      })

      it('sets aria-valuenow for determinate progress', async () => {
        progress.value = 50
        await progress.updateComplete
        assert.equal(progress.getAttribute('aria-valuenow'), '50', 'should set aria-valuenow for determinate')
      })

      it('removes aria-valuenow for indeterminate progress', async () => {
        progress.indeterminate = true
        await progress.updateComplete
        assert.isNull(progress.getAttribute('aria-valuenow'), 'should remove aria-valuenow for indeterminate')
      })

      it('updates aria attributes when switching between states', async () => {
        // Start determinate
        progress.value = 30
        await progress.updateComplete
        assert.equal(progress.getAttribute('aria-valuenow'), '30', 'should have aria-valuenow initially')

        // Switch to indeterminate
        progress.indeterminate = true
        await progress.updateComplete
        assert.isNull(progress.getAttribute('aria-valuenow'), 'should remove aria-valuenow when indeterminate')

        // Switch back to determinate
        progress.indeterminate = false
        await progress.updateComplete
        assert.equal(progress.getAttribute('aria-valuenow'), '30', 'should restore aria-valuenow when determinate')
      })
    })

    describe('Accessibility Testing', () => {
      it('should be accessible in basic state', async () => {
        const progress = await accessibleBasicFixture()
        await assert.isAccessible(progress)
      })

      it('should be accessible in determinate state', async () => {
        const progress = await accessibleDeterminateFixture()
        await assert.isAccessible(progress)
      })

      it('should be accessible in indeterminate state', async () => {
        const progress = await accessibleIndeterminateFixture()
        await assert.isAccessible(progress)
      })

      it('should be accessible with four colors', async () => {
        const progress = await accessibleFourColorFixture()
        await assert.isAccessible(progress)
      })

      it('should be accessible when disabled', async () => {
        const progress = await accessibleDisabledFixture()
        await assert.isAccessible(progress)
      })
    })
  })

  describe('Events', () => {
    let progress: CircularProgress

    beforeEach(async () => {
      progress = await basicFixture()
    })

    it('dispatches ratiochange event when value changes', async () => {
      let eventFired = false
      progress.addEventListener('ratiochange', () => {
        eventFired = true
      })

      progress.value = 50
      await progress.updateComplete

      assert.isTrue(eventFired, 'should dispatch ratiochange event')
    })

    it('dispatches ratiochange event when max changes', async () => {
      let eventFired = false
      progress.value = 50 // Set initial value
      await progress.updateComplete

      progress.addEventListener('ratiochange', () => {
        eventFired = true
      })

      progress.max = 200
      await progress.updateComplete

      assert.isTrue(eventFired, 'should dispatch ratiochange event when max changes')
    })

    it('dispatches ratiochange event when min changes', async () => {
      let eventFired = false
      progress.value = 50 // Set initial value
      await progress.updateComplete

      progress.addEventListener('ratiochange', () => {
        eventFired = true
      })

      progress.min = 10
      await progress.updateComplete

      assert.isTrue(eventFired, 'should dispatch ratiochange event when min changes')
    })
  })

  describe('CSS Custom Properties Support', () => {
    let progress: CircularProgress

    beforeEach(async () => {
      progress = await basicFixture()
    })

    it('allows size customization via CSS custom property', async () => {
      progress.style.setProperty('--ui-circular-progress-size', '64px')
      await progress.updateComplete

      const computedStyle = getComputedStyle(progress)
      assert.include(computedStyle.getPropertyValue('--_size'), '64px', 'should use custom size')
    })

    it('supports color customization', async () => {
      progress.style.setProperty('--ui-circular-progress-active-indicator-color', 'red')
      await progress.updateComplete

      const computedStyle = getComputedStyle(progress)
      assert.include(computedStyle.getPropertyValue('--_active-indicator-color'), 'red', 'should use custom color')
    })
  })

  describe('Edge Cases', () => {
    let progress: CircularProgress

    beforeEach(async () => {
      progress = await basicFixture()
    })

    it('handles NaN values gracefully', async () => {
      progress.value = NaN
      await progress.updateComplete
      assert.equal(progress.value, 0, 'should handle NaN value gracefully')
    })

    it('handles negative step values', async () => {
      progress.step = -5
      progress.value = 10
      await progress.updateComplete
      assert.equal(progress.value, 10, 'should handle negative step values')
    })

    it('handles very small step values', async () => {
      progress.step = 0.1
      progress.value = 0.15
      await progress.updateComplete
      assert.equal(progress.value, 0.1, 'should handle small step values correctly')
    })

    it('maintains correct ratio when min is not zero', async () => {
      progress.min = 20
      progress.max = 80
      progress.value = 50
      await progress.updateComplete

      const expectedRatio = ((50 - 20) / (80 - 20)) * 100
      assert.equal(progress.ratio, expectedRatio, 'should calculate ratio correctly with non-zero min')
    })
  })

  describe('Disabled State', () => {
    let progress: CircularProgress

    beforeEach(async () => {
      progress = await disabledFixture()
    })

    it('reflects disabled attribute', () => {
      assert.isTrue(progress.hasAttribute('disabled'), 'should have disabled attribute')
      assert.isTrue(progress.disabled, 'disabled property should be true')
    })

    it('can be enabled programmatically', async () => {
      progress.disabled = false
      await progress.updateComplete

      assert.isFalse(progress.hasAttribute('disabled'), 'should not have disabled attribute')
      assert.isFalse(progress.disabled, 'disabled property should be false')
    })
  })

  describe('Performance Considerations', () => {
    let progress: CircularProgress

    beforeEach(async () => {
      progress = await basicFixture()
    })

    it('uses contain: strict for performance', () => {
      const computedStyle = getComputedStyle(progress)
      assert.equal(computedStyle.contain, 'strict', 'should use contain: strict')
    })

    it('uses content-visibility: auto', () => {
      const computedStyle = getComputedStyle(progress)
      assert.equal(computedStyle.contentVisibility, 'auto', 'should use content-visibility: auto')
    })
  })
})
