class DemandsAnalysisGenerator {

    constructor() {
        this.formData = {};

        this.varsConfig = {};

        this.secureStorage = new SecureStorage();
        this.storageUIManager = null;
        this.storageDataManager = null;
        this.tabsManager = null;

        this.init();
    }

    async init() {

        await this.loadVarsConfig();

        this.initializeTabsManager();

        this.setupEventListeners();

        this.initializeStorageManagers();
    }

    async loadVarsConfig() {
        try {
            const response = await fetch('src/fields/vars.json');
            this.varsConfig = await response.json();
        } catch (error) {
            console.warn('Could not load src/fields/vars.json, using default configuration');
            this.varsConfig = this.getDefaultVarsConfig();
        }
    }

    getDefaultVarsConfig() {
        return {
            "documentTitle": "{documentTitle}",
            "authorName": "{authorName}",
            "documentDate": "{documentDate}",
            "documentContent": "{documentContent}"
        };
    }

    initializeTabsManager() {
        if (typeof TabsManager !== 'undefined') {
            this.tabsManager = new TabsManager();
            this.tabsManager.init();
        } else {

            setTimeout(() => this.initializeTabsManager(), 100);
        }
    }

    setupEventListeners() {

        const setupGenerateButton = () => {

            if (this.tabsManager && this.tabsManager.summaryTab) {

                this.tabsManager.summaryTab.setGenerateButtonHandler(() => {
                    this.generateDocument();
                });
            } else {

                const generateBtn = document.getElementById('generateBtn');
                if (generateBtn) {
                    generateBtn.addEventListener('click', () => {
                        this.generateDocument();
                    });
                } else {

                    setTimeout(setupGenerateButton, 100);
                }
            }
        };

        setupGenerateButton();
    }

    initializeStorageManagers() {

        if (typeof StorageDataManager !== 'undefined') {
            this.storageDataManager = new StorageDataManager(this);
        }

        if (typeof StorageUIManager !== 'undefined') {
            this.storageUIManager = new StorageUIManager(this);
            this.storageUIManager.initialize();
        }

        if (!this.storageDataManager || !this.storageUIManager) {
            setTimeout(() => this.initializeStorageManagers(), 100);
        }
    }

    refreshStorageUI() {
        if (this.storageUIManager) {
            this.storageUIManager.refreshStorageUI();
        }
    }

    collectFormData() {
        if (!this.tabsManager) {
            console.error('Tabs manager not initialized');
            return {};
        }

        const allTabData = this.tabsManager.getAllData();

        this.formData = {
            ...allTabData.intro,
            ...allTabData.demographics,
            ...allTabData.summary,

            jobsData: allTabData.jobs,

            physicalDemands: allTabData.jobs?.physicalDemands || {},
            mobilityDemands: allTabData.jobs?.mobilityDemands || {},
            cognitiveSensoryDemands: allTabData.jobs?.cognitiveSensoryDemands || {},
            environmentalDemands: allTabData.jobs?.environmentalDemands || {},
            liftingPushingPulling: allTabData.jobs?.liftingPushingPulling || {},
            classificationOfWork: allTabData.jobs?.classificationOfWork || {}
        };
        return this.formData;
    }

    validateForm() {
        if (!this.tabsManager) {
            return false;
        }

        const validation = this.tabsManager.validateAll();
        return validation.isValid;
    }

    temporarilyDisableButton() {
        const button = this.getGenerateButton();
        if (!button) return;

        button.setDisabled(true);

        setTimeout(() => {
            button.setDisabled(false);
        }, 3000);
    }

    getGenerateButton() {

        if (this.tabsManager?.summaryTab?.generateButton) {
            return this.tabsManager.summaryTab.generateButton;
        }

        const domButton = document.getElementById('generateBtn');
        if (domButton) {
            return {
                setDisabled: (disabled) => { domButton.disabled = disabled; },
                setLoading: (loading) => {
                    domButton.disabled = loading;
                    domButton.textContent = loading ? 'Generating...' : 'Generate Document';
                },
                setText: (text) => { domButton.textContent = text; }
            };
        }

        return null;
    }

    async generateDocument() {
        if (!this.validateForm()) {

            const firstErrorTab = this.tabsManager?.getFirstTabWithErrors();

            if (firstErrorTab) {

                showError('Please complete all required fields');

                this.tabsManager.switchToTab(firstErrorTab);

                if (firstErrorTab === 'jobs' && this.tabsManager?.jobsTab?.subNav) {
                    const firstErrorSection = this.tabsManager.jobsTab.getFirstSubnavSectionWithErrors();
                    if (firstErrorSection) {
                        this.tabsManager.jobsTab.subNav.setActiveSection(firstErrorSection);
                    }
                }
            } else {

                showError('Please fill in all required fields');
            }

            this.temporarilyDisableButton();
            return;
        }

        const button = this.getGenerateButton();

        if (button) {
            button.setLoading(true);
            button.setText('Generating...');
        }

        this.collectFormData();

        try {

            const generatedPDF = await this.generatePDFWithTemplate();

            this.createDownloadLinkForPDF(generatedPDF);

            showSuccess('PDF generated and download started successfully!');

        } catch (error) {
            console.error('Document generation failed:', error);
            showError(`Failed to generate document: ${error.message}`);
            this.temporarilyDisableButton();
        } finally {

            if (button) {
                button.setLoading(false);
                button.setText('Generate Document');
            }
        }
    }

    async generatePDFWithTemplate() {

        const selectedTemplate = this.formData.selectedTemplate || this.formData.template;
        if (!selectedTemplate) {
            throw new Error('No template selected');
        }

        const templateClasses = this.tabsManager.introTab?.getSelectedTemplateClasses();
        if (!templateClasses || !templateClasses.generator) {
            throw new Error('Generator class not found for selected template');
        }

        const GeneratorClass = window[templateClasses.generator];
        if (!GeneratorClass) {
            throw new Error(`Generator class ${templateClasses.generator} not found`);
        }

        const generator = new GeneratorClass();

        const doc = generator.generate(this.formData);

        return doc.output('blob');
    }

    createDownloadLinkForPDF(pdfBlob) {

        const blobUrl = URL.createObjectURL(pdfBlob);

        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = `${this.formData.jobTitle || 'JDA Report'} - Job Demands Analysis - ${new Date().toLocaleDateString()}.pdf`;

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        URL.revokeObjectURL(blobUrl);
    }

    async handleSaveData(isUpdate = false) {
        if (this.storageDataManager) {
            return await this.storageDataManager.handleSaveData(isUpdate);
        } else {
            showError('Storage system not initialized. Please try again.');
            return false;
        }
    }

    async handleLoadData() {
        if (this.storageDataManager) {
            return await this.storageDataManager.handleLoadData();
        } else {
            showError('Storage system not initialized. Please try again.');
            return false;
        }
    }

    async handleClearData() {
        if (this.storageDataManager) {
            return await this.storageDataManager.handleClearData();
        } else {
            showError('Storage system not initialized. Please try again.');
            return false;
        }
    }

}

document.addEventListener('DOMContentLoaded', () => {
    window.demandsAnalysisGenerator = new DemandsAnalysisGenerator();
});