const schema = require('./data/eds-c-error-message.schema.json');
const exampleJson = require('./data/eds-c-error-message.example.json');
const fs = require('node:fs');
const path = require('node:path');
const Ajv = require('ajv');
const ajv = new Ajv();
const handlebars = require('handlebars');

const {findTemplates} = require('../../development/tests/templateLoader.js');
findTemplates(['eds-c-error-message']).load(handlebars);

const componentTemplate = '{{> eds-c-error-message }}';
const componentHbs = handlebars.compile(componentTemplate);
const renderedComponent = componentHbs(exampleJson);

describe('Error Message Schema Validation and Accessibility Test', () => {
    const { configureAxe, toHaveNoViolations } = require('jest-axe');
    expect.extend(toHaveNoViolations);
    
    const axe = configureAxe({
        rules: {
            region: { enabled: false }
        }
    });
    
    test('Example data matches schema', () => {
        const validate = ajv.compile(schema);
        const valid = validate(exampleJson);
    
        if (!valid) {
            // Extract and format the Ajv validation errors
            const errors = validate.errors.map((error) => ajv.errorsText([error])).join('\n');
            throw new Error(errors);
        }
    
        expect(valid).toBeTruthy();
    });

    test('Id should be set correctly', () => {
        document.body.innerHTML = renderedComponent;
        const errorElement = document.querySelector('.eds-c-error-message');
        expect(errorElement.getAttribute('id')).toBe('error-my-id');
    });

    test('Icon element should be present', () => {
        document.body.innerHTML = renderedComponent;
        const icon = document.querySelector('.eds-c-error-message svg');
        const xlinkHref = icon.querySelector('use').getAttribute('xlink:href');
        expect(icon).not.toBeNull();
        expect(xlinkHref).toBe('#eds-i-error-filled-medium');
    });

    test('Text element should be present', () => {
        document.body.innerHTML = renderedComponent;
        const textElement = document.querySelector('.eds-c-error-message');
        expect(textElement.textContent.replace(/\s+/g, ' ').trim()).toBe('Error: Enter your name');
    });

    test('Prefix only visible to screen reader should be present', () => {
        document.body.innerHTML = renderedComponent;
        const errorElement = document.querySelector('.eds-c-error-message');
        expect(errorElement.outerHTML).toMatch('class="u-hide-sr-only"');
    });

    test('Template passes basic HTML accessibility', async () => {
        expect(await axe(renderedComponent)).toHaveNoViolations();
    });
});