import { describe, it, expect, beforeEach } from 'vitest'
import { sanitizeHtml, ETicketEditor, registerEditor } from '../../assets/modules/editor.js'

describe('sanitizeHtml', () => {
    it('keeps allowed tags', () => {
        const html = '<p>Hello <b>world</b></p>'
        expect(sanitizeHtml(html)).toBe('<p>Hello <b>world</b></p>')
    })

    it('strips disallowed tags but keeps content', () => {
        const html = '<div><span>Hello</span></div>'
        expect(sanitizeHtml(html)).toBe('Hello')
    })

    it('strips links but keeps text', () => {
        const html = '<a href="https://example.com">Link</a>'
        expect(sanitizeHtml(html)).toBe('Link')
    })

    it('keeps list elements', () => {
        const html = '<ul><li>Item 1</li><li>Item 2</li></ul>'
        expect(sanitizeHtml(html)).toBe('<ul><li>Item 1</li><li>Item 2</li></ul>')
    })

    it('strips blockquote but keeps content', () => {
        const html = '<blockquote>Citation</blockquote>'
        expect(sanitizeHtml(html)).toBe('Citation')
    })

    it('returns empty string for empty input', () => {
        expect(sanitizeHtml('')).toBe('')
    })

    it('strips headings but keeps content', () => {
        const html = '<h2>Title</h2><h3>Subtitle</h3>'
        expect(sanitizeHtml(html)).toBe('TitleSubtitle')
    })

    it('strips style attributes from allowed tags', () => {
        const html = '<p style="color:red">Text</p>'
        expect(sanitizeHtml(html)).toBe('<p>Text</p>')
    })

    it('strips onclick from allowed tags', () => {
        const html = '<b onclick="alert(1)">Bold</b>'
        expect(sanitizeHtml(html)).toBe('<b>Bold</b>')
    })

    it('strips onerror from allowed tags', () => {
        const html = '<p onerror="alert(1)">Text</p>'
        expect(sanitizeHtml(html)).toBe('<p>Text</p>')
    })

    it('strips class and id from allowed tags', () => {
        const html = '<p class="evil" id="inject">Text</p>'
        expect(sanitizeHtml(html)).toBe('<p>Text</p>')
    })

    it('strips data attributes from allowed tags', () => {
        const html = '<ul data-x="1"><li data-y="2">Item</li></ul>'
        expect(sanitizeHtml(html)).toBe('<ul><li>Item</li></ul>')
    })

    it('strips script tags entirely', () => {
        const html = '<p>Safe</p><script>alert(1)</script>'
        expect(sanitizeHtml(html)).toBe('<p>Safe</p>')
    })

    it('strips img onerror XSS', () => {
        const html = '<img src=x onerror="alert(1)">'
        expect(sanitizeHtml(html)).toBe('')
    })

    it('strips nested disallowed tags with attributes', () => {
        const html = '<div style="background:url(evil)"><p onclick="steal()">OK</p></div>'
        expect(sanitizeHtml(html)).toBe('<p>OK</p>')
    })

    it('ignores comment nodes', () => {
        const html = '<p>Before</p><!-- comment --><p>After</p>'
        expect(sanitizeHtml(html)).toBe('<p>Before</p><p>After</p>')
    })

    it('strips href from anchor but keeps text', () => {
        const html = '<a href="javascript:alert(1)">Click</a>'
        expect(sanitizeHtml(html)).toBe('Click')
    })
})

function createEditor(innerHtml = '<textarea></textarea>') {
    registerEditor()
    document.body.innerHTML = ''
    const el = document.createElement('e-ticket-editor')
    el.innerHTML = innerHtml
    document.body.appendChild(el)
    el.connectedCallback()

    return el
}

describe('ETicketEditor', () => {
    beforeEach(() => {
        registerEditor()
        if (!document.execCommand) {
            document.execCommand = () => true
        }
    })

    it('registers the custom element', () => {
        expect(globalThis.customElements.get('e-ticket-editor')).toBe(ETicketEditor)
    })

    it('hides the textarea and creates toolbar + content area', () => {
        const editor = createEditor('<textarea placeholder="Ecrivez ici...">Hello</textarea>')
        const textarea = editor.querySelector('textarea')
        const toolbar = editor.querySelector('.ete-toolbar')
        const content = editor.querySelector('.ete-content')

        expect(textarea.style.display).toBe('none')
        expect(toolbar).not.toBeNull()
        expect(content).not.toBeNull()
        expect(content.getAttribute('contenteditable')).toBe('true')
        expect(content.innerHTML).toBe('Hello')
        expect(content.dataset.placeholder).toBe('Ecrivez ici...')
    })

    it('does nothing without a textarea', () => {
        const editor = createEditor('')
        expect(editor.querySelector('.ete-toolbar')).toBeNull()
        expect(editor.querySelector('.ete-content')).toBeNull()
    })

    it('toolbar has buttons', () => {
        const editor = createEditor()
        const buttons = editor.querySelectorAll('.ete-btn')
        expect(buttons.length).toBeGreaterThan(0)
    })

    it('toolbar buttons have aria-label', () => {
        const editor = createEditor()
        const buttons = editor.querySelectorAll('.ete-btn')
        buttons.forEach(btn => {
            expect(btn.getAttribute('aria-label')).toBeTruthy()
        })
    })

    it('toolbar buttons have tabindex=0', () => {
        const editor = createEditor()
        const buttons = editor.querySelectorAll('.ete-btn')
        buttons.forEach(btn => {
            expect(btn.tabIndex).toBe(0)
        })
    })

    it('toolbar has separators', () => {
        const editor = createEditor()
        const separators = editor.querySelectorAll('.ete-separator')
        expect(separators.length).toBeGreaterThan(0)
    })

    it('getHtml returns textarea value', () => {
        const editor = createEditor('<textarea>Content</textarea>')
        expect(editor.getHtml()).toBe('Content')
    })

    it('prevents tab key default in content area', () => {
        const editor = createEditor()
        const content = editor.querySelector('.ete-content')
        const event = new KeyboardEvent('keydown', { key: 'Tab', cancelable: true })
        content.dispatchEvent(event)
        expect(event.defaultPrevented).toBe(true)
    })

    it('sanitizeNode handles text nodes and element nodes', () => {
        const html = 'Hello <b>world</b> plain'
        const result = sanitizeHtml(html)
        expect(result).toContain('Hello')
        expect(result).toContain('<b>world</b>')
        expect(result).toContain('plain')
    })

    it('allows non-tab keys', () => {
        const editor = createEditor()
        const content = editor.querySelector('.ete-content')
        const event = new KeyboardEvent('keydown', { key: 'Enter', cancelable: true })
        content.dispatchEvent(event)
        expect(event.defaultPrevented).toBe(false)
    })

    it('toolbar button mousedown calls exec and prevents default', () => {
        const editor = createEditor()
        const btn = editor.querySelector('.ete-btn')
        const event = new MouseEvent('mousedown', { cancelable: true, bubbles: true })
        btn.dispatchEvent(event)
        expect(event.defaultPrevented).toBe(true)
    })

    it('syncs content to textarea via _sync', () => {
        const editor = createEditor()
        const textarea = editor.querySelector('textarea')

        editor._content.innerHTML = '<p>Updated</p>'
        editor._sync()

        expect(textarea.value).toBe('<p>Updated</p>')
    })

    it('syncs sanitized content to textarea via _sync', () => {
        const editor = createEditor()
        const textarea = editor.querySelector('textarea')

        editor._content.innerHTML = '<div>Stripped</div><p>Safe</p>'
        editor._sync()

        expect(textarea.value).toBe('Stripped<p>Safe</p>')
    })

    it('exec with value calls execCommand with value', () => {
        const editor = createEditor()
        const btn = editor.querySelectorAll('.ete-btn')
        const pBtn = Array.from(btn).find(b => b.title === 'Paragraphe')
        if (pBtn) {
            const event = new MouseEvent('mousedown', { cancelable: true, bubbles: true })
            pBtn.dispatchEvent(event)
            expect(event.defaultPrevented).toBe(true)
        }
    })

    it('exec without value calls execCommand without value', () => {
        const editor = createEditor()
        const btn = editor.querySelectorAll('.ete-btn')
        const boldBtn = Array.from(btn).find(b => b.title === 'Gras')
        if (boldBtn) {
            const event = new MouseEvent('mousedown', { cancelable: true, bubbles: true })
            boldBtn.dispatchEvent(event)
            expect(event.defaultPrevented).toBe(true)
        }
    })
})
