class StorageDataManager {

    constructor(documentGenerator) {
        this.documentGenerator = documentGenerator;
        this.secureStorage = documentGenerator.secureStorage;
        this.sessionPassphrase = null;
    }

    async handleSaveData(isUpdate = false) {

        this.documentGenerator.collectFormData();

        if (Object.keys(this.documentGenerator.formData).length === 0) {
            showError('Please fill in some information before saving');
            return false;
        }

        let userPhrase;

        if (isUpdate && this.sessionPassphrase) {

            userPhrase = this.sessionPassphrase;
        } else {

            userPhrase = await this.promptForPhrase('save');
            if (!userPhrase) return false;

            this.sessionPassphrase = userPhrase;
        }

        try {
            const success = await this.secureStorage.saveFormData(this.documentGenerator.formData, userPhrase);
            if (success) {
                const expirationDays = this.secureStorage.getExpirationDays();
                const message = isUpdate
                    ? `Data updated successfully! Your changes have been saved. Saved data will expire in ${expirationDays} days.`
                    : `Information saved securely! Use the same phrase to load it later. Saved data will expire in ${expirationDays} days.`;

                showSuccess(message, { duration: 8 });

                showWarning('Note: Uploaded images are not stored for later. You will need to re-upload them when you load your saved data.', { duration: 7 });

                if (this.documentGenerator.storageUIManager) {
                    if (isUpdate) {

                        this.documentGenerator.storageUIManager.handleStorageOperation('update', true);
                    } else {

                        this.documentGenerator.storageUIManager.handleStorageOperation('save_and_unlock', true);
                    }
                }
                return true;
            } else {
                showError('Failed to save information. Please try again.');
                return false;
            }
        } catch (error) {
            console.error('Save error:', error);
            showError('Failed to save information. Please try again.');
            return false;
        }
    }

    async handleLoadData() {
        const userPhrase = await this.promptForPhrase('load');
        if (!userPhrase) return false;

        try {
            const formData = await this.secureStorage.loadFormData(userPhrase);

            if (formData) {
                this.populateForm(formData);
                showSuccess('Information loaded successfully!');

                this.sessionPassphrase = userPhrase;

                if (this.documentGenerator.storageUIManager) {
                    this.documentGenerator.storageUIManager.handleStorageOperation('load', true);
                }
                return true;
            } else {
                console.warn('loadFormData returned null - either no cookie or decryption failed');
                showWarning('No saved information found or incorrect passphrase.');
                return false;
            }
        } catch (error) {
            console.error('Load error (exception thrown):', error);
            console.error('Error message:', error.message);
            console.error('Error stack:', error.stack);
            showError('Failed to load information. Please check your phrase and try again.');
            return false;
        }
    }

    async handleClearData() {
        const confirmed = confirm('Are you sure you want to clear all saved information? This cannot be undone.');
        if (confirmed) {
            this.secureStorage.clearStoredData();

            this.sessionPassphrase = null;

            if (this.documentGenerator.storageUIManager) {
                this.documentGenerator.storageUIManager.handleStorageOperation('clear', true);
            }

            showSuccess('Saved information cleared successfully.');
            return true;
        }
        return false;
    }

    async promptForPhrase(action) {

        if (window.phraseModal) {
            return await window.phraseModal.show(action);
        } else {

            const expirationDays = this.secureStorage.getExpirationDays();
            const expirationText = action === 'save' ? ` Saved data will expire in ${expirationDays} days.` : '';
            const phrase = prompt(
                `Enter a phrase to ${action} your information securely:\n\n` +
                `This phrase will be used to encrypt your data. ` +
                `${action === 'save' ? 'Remember this phrase - you\'ll need it to load your information later!' : 'Use the same phrase you used when saving.'}${expirationText}\n\n` +
                `Tip: Use a memorable phrase that's at least 4 characters long.`
            );

            if (!phrase) {
                return null;
            }

            if (phrase.length < 4) {
                showError('Please use a phrase that\'s at least 4 characters long for better security.');
                return null;
            }

            return phrase;
        }
    }

    populateForm(formData) {

        if (this.documentGenerator.tabsManager) {

            const tabData = {
                intro: {},
                demographics: {},
                jobs: {},
                summary: {}
            };

            if (formData.jobsData && typeof formData.jobsData === 'object') {

                tabData.jobs = formData.jobsData;
            } else if (formData.jobs && typeof formData.jobs === 'object') {

                tabData.jobs = formData.jobs;
            } else {

                tabData.jobs = {
                    physicalDemands: formData.physicalDemands || {},
                    mobilityDemands: formData.mobilityDemands || {},
                    cognitiveSensoryDemands: formData.cognitiveSensoryDemands || {},
                    environmentalDemands: formData.environmentalDemands || {},
                    liftingPushingPulling: formData.liftingPushingPulling || {},
                    classificationOfWork: formData.classificationOfWork || {}
                };
            }

            const varsConfig = this.documentGenerator.varsConfig;
            Object.keys(varsConfig).forEach(fieldName => {
                if (formData.hasOwnProperty(fieldName)) {

                    if (['title', 'companyName', 'companyStreet', 'companyCity', 'companyState', 'companyZip', 'companyLogo', 'brandColor', 'secondaryBrandColor', 'author', 'email', 'date', 'selectedTemplate', 'template'].includes(fieldName)) {
                        tabData.intro[fieldName] = formData[fieldName];
                    } else if (['jobTitle', 'jobPurpose', 'essentialFunctions', 'marginalFunctions', 'workSchedule', 'breaks', 'otherShiftInfo'].includes(fieldName)) {
                        tabData.demographics[fieldName] = formData[fieldName];
                    } else if (['documentContent', 'summaryText'].includes(fieldName)) {
                        tabData.summary[fieldName] = formData[fieldName];
                    }

                }
            });

            this.documentGenerator.tabsManager.setAllData(tabData);
        } else {

            const varsConfig = this.documentGenerator.varsConfig;

            Object.keys(varsConfig).forEach(fieldName => {

                if (formData.hasOwnProperty(fieldName)) {
                    const element = document.getElementById(fieldName);
                    if (element) {
                        element.value = formData[fieldName];
                    } else {
                        console.warn(`Field "${fieldName}" defined in src/fields/vars.json but not found in form`);
                    }
                }
            });
        }

        this.documentGenerator.validateForm();
    }

    hasStoredData() {
        return this.secureStorage.hasStoredData();
    }

    getRemainingDays() {
        return this.secureStorage.getRemainingDays();
    }

    getExpirationDays() {
        return this.secureStorage.getExpirationDays();
    }
}