const fs = require('fs');
const handlebars = require('handlebars');
const path = require('path');
const Ajv = require("ajv");
const ajv = new Ajv();
const componentsDir = path.join(__dirname, '..');
const filenames = fs.readdirSync(__dirname);
const buttons = fs.readdirSync(`${componentsDir}/eds-c-button`);
const schema = require('./data/eds-c-modal.schema.json');
const buttonSchema = require('../eds-c-button/data/eds-c-button.schema.json');
const exampleJson = require('./data/eds-c-modal.example.json');
const EdsCModal = require('./js/eds-c-modal.js');
const {findTemplates} = require('../../development/tests/templateLoader.js');
findTemplates(['eds-c-modal', 'eds-c-button']).load(handlebars);

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

describe('EDS modal component', () => {
    test('docs file exists', () => {
        const exists = fs.existsSync(path.resolve(__dirname, 'docs.md'));
        expect(exists).toBe(true);
    });
});

describe('Assert Modal Component', () => {

    beforeEach(() => {
        document.body.innerHTML = '<button data-modal-for="example-modal" class="eds-c-modal__trigger">Click this button to open the modal</button>' + renderedComponent;

    });
 
    const { configureAxe, toHaveNoViolations } = require('jest-axe');
    expect.extend(toHaveNoViolations);

    const axe = configureAxe({
        rules: {
            region: { enabled: false }
        }
    });

    test('Example data matches schema', () => {

        ajv.addSchema(buttonSchema, 'buttonSchema');

        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('Template can be compiled and rendered', () => {
        const container = document.querySelector('*');
        expect(container).toBeDefined();
    });

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

    test('Modal renders with correct title and description', () => {
        const triggerButton = document.querySelector('.eds-c-modal__trigger');
        triggerButton.click();

        const titleElement = document.querySelector('#eds-c-modal-title');
        expect(titleElement).toBeTruthy();

        const descriptionElement = document.querySelector('#eds-c-modal-description');
        expect(descriptionElement).toBeTruthy();
    });

    test('Modal renders with correct primary and secondary buttons', () => {
        const triggerButton = document.querySelector('.eds-c-modal__trigger');
        triggerButton.click();

        const primaryButton = document.querySelector('.eds-c-button--primary');
        expect(primaryButton).toBeTruthy();

        const secondaryButton = document.querySelector('.eds-c-button--secondary');
        expect(secondaryButton).toBeTruthy();
    });

    test('Modal renders the dismiss icon', () => {
        const triggerButton = document.querySelector('.eds-c-modal__trigger');
        triggerButton.click();

        const dismissIcon = document.querySelector('.eds-c-modal__dismiss');
        expect(dismissIcon).toBeTruthy();
    });

    test('Modal opens when trigger button is clicked', () => {
        const modalElement = document.querySelector('#example-modal');
        if (modalElement) {
             new EdsCModal.default(modalElement);
        }
        const triggerButton = document.querySelector('.eds-c-modal__trigger');
        triggerButton.click();
    
        expect(modalElement.classList.contains('eds-c-modal--open')).toBe(true);
    });

    test('Modal closes when dismiss button is clicked', () => {
        const triggerButton = document.querySelector('.eds-c-modal__trigger');
        triggerButton.click();

        const dismissButton = document.querySelector('.eds-c-modal__dismiss');
        dismissButton.click();

        const modal = document.querySelector('#example-modal');
        expect(modal.classList.contains('eds-c-modal--open')).toBe(false);
    });
});