class DemandLevelSelector {

    constructor(options = {}) {
        this.options = {
            containerId: options.containerId || null,
            required: options.required !== undefined ? options.required : true,
            onChange: options.onChange || (() => {}),
            onValidate: options.onValidate || null
        };

        this.selectedLevel = null;
        this.container = null;
        this.rowElements = [];
        this.validationErrors = {};

        this.demandLevels = [
            {
                level: 'Sedentary',
                value: 'sedentary',
                occasional: '10 lbs',
                frequent: 'Negligible',
                constant: 'Negligible',
                mets: '1.5-2.1',
                color: 'sedentary'
            },
            {
                level: 'Light',
                value: 'light',
                occasional: '20 lbs',
                frequent: '10 lbs and/or walk/stand',
                constant: 'Negligible and/or operate controls',
                mets: '2.2-3.5',
                color: 'light'
            },
            {
                level: 'Medium',
                value: 'medium',
                occasional: '20-50 lbs',
                frequent: '10-25 lbs',
                constant: '10 lbs',
                mets: '3.6-6.3',
                color: 'medium'
            },
            {
                level: 'Heavy',
                value: 'heavy',
                occasional: '50-100 lbs',
                frequent: '25-50 lbs',
                constant: '10-20 lbs',
                mets: '6.4-7.5',
                color: 'heavy'
            },
            {
                level: 'Very Heavy',
                value: 'very_heavy',
                occasional: '> 100 lbs',
                frequent: '> 50 lbs',
                constant: '> 20 lbs',
                mets: '> 7.5',
                color: 'very-heavy'
            }
        ];

        this.init();
    }

    init() {
        if (!this.options.containerId) {
            console.error('DemandLevelSelector requires a containerId');
            return;
        }

        this.container = document.getElementById(this.options.containerId);
        if (!this.container) {
            console.error(`Container with ID "${this.options.containerId}" not found`);
            return;
        }

        this.render();
    }

    render() {

        this.container.innerHTML = '';

        const wrapper = document.createElement('div');
        wrapper.className = 'demand-level-selector-wrapper';

        wrapper.appendChild(this.createTitle());
        wrapper.appendChild(this.createDescription());

        const table = this.createTable();
        wrapper.appendChild(table);

        this.container.appendChild(wrapper);
    }

    createTitle() {
        const title = document.createElement('div');
        title.className = 'demand-level-title';
        title.textContent = '37.02 U.S. Department of Labor Physical Demand Characteristics of Work';
        return title;
    }

    createDescription() {
        const description = document.createElement('div');
        description.className = 'demand-level-description';
        description.innerHTML = `
            <p>Select the physical demand level that best describes this job.
            Use the weight and frequency information to guide your selection.</p>
        `;
        return description;
    }

    createTable() {
        const table = document.createElement('div');
        table.className = 'demand-level-table';

        table.appendChild(this.createHeaderRow());

        this.rowElements = [];
        this.demandLevels.forEach((level, index) => {
            table.appendChild(this.createDataRow(level, index));
        });

        return table;
    }

    createHeaderRow() {
        const headerRow = document.createElement('div');
        headerRow.className = 'demand-level-header-row';
        headerRow.innerHTML = `
            <div class="demand-level-header-cell demand-level-header-level">Level</div>
            <div class="demand-level-header-cell">Occasional (0-33%)</div>
            <div class="demand-level-header-cell">Frequent (34-66%)</div>
            <div class="demand-level-header-cell">Constant (67-100%)</div>
            <div class="demand-level-header-cell">Energy Required (METS)</div>
        `;
        return headerRow;
    }

    createDataRow(level, index) {
        const row = document.createElement('div');
        row.className = `demand-level-row demand-level-${level.color}`;
        row.setAttribute('data-level-value', level.value);
        row.setAttribute('data-level-index', index);
        row.setAttribute('tabindex', '0');
        row.setAttribute('role', 'button');
        row.setAttribute('aria-pressed', 'false');

        row.innerHTML = `
            <div class="demand-level-cell demand-level-level-name">${level.level}</div>
            <div class="demand-level-cell">${level.occasional}</div>
            <div class="demand-level-cell">${level.frequent}</div>
            <div class="demand-level-cell">${level.constant}</div>
            <div class="demand-level-cell">${level.mets}</div>
        `;

        row.addEventListener('click', () => this.selectLevel(index));
        row.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                this.selectLevel(index);
            }
        });

        this.rowElements.push(row);
        return row;
    }

    selectLevel(index) {

        this.rowElements.forEach(row => {
            row.classList.remove('demand-level-selected');
            row.setAttribute('aria-pressed', 'false');
        });

        this.rowElements[index].classList.add('demand-level-selected');
        this.rowElements[index].setAttribute('aria-pressed', 'true');

        this.selectedLevel = this.demandLevels[index].value;

        this.validationErrors = {};
        this.clearValidationError();

        this.options.onChange(this.selectedLevel);
    }

    getSelectedLevel() {
        return this.selectedLevel;
    }

    setSelectedLevel(levelValue) {
        const levelIndex = this.demandLevels.findIndex(l => l.value === levelValue);
        if (levelIndex >= 0) {
            this.selectLevel(levelIndex);
        }
    }

    validate() {
        this.validationErrors = {};

        if (this.options.required && !this.selectedLevel) {
            this.validationErrors['demand-level'] = 'Please select a demand level.';
            this.showValidationError();
            return false;
        }

        this.clearValidationError();
        return true;
    }

    showValidationError() {
        const table = this.container.querySelector('.demand-level-table');
        if (table) {
            table.classList.add('demand-level-error');
        }
    }

    clearValidationError() {
        const table = this.container.querySelector('.demand-level-table');
        if (table) {
            table.classList.remove('demand-level-error');
        }
    }

    getValidationErrors() {
        return JSON.parse(JSON.stringify(this.validationErrors));
    }

    clear() {
        this.rowElements.forEach(row => {
            row.classList.remove('demand-level-selected');
            row.setAttribute('aria-pressed', 'false');
        });
        this.selectedLevel = null;
        this.validationErrors = {};
        this.clearValidationError();
    }

    destroy() {
        if (this.container) {
            this.container.innerHTML = '';
        }
        this.rowElements = [];
    }
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = DemandLevelSelector;
}