class IntroTab {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        if (!this.container) {
            console.error(`Intro tab container with ID "${containerId}" not found`);
            return;
        }
        this.templateCards = null;
        this.selectedTemplate = null;
        this.titleInput = null;
        this.companyNameInput = null;
        this.companyAddress = null;
        this.authorInput = null;
        this.emailInput = null;
        this.dateInput = null;
        this.brandColorPicker = null;
        this.secondaryColorPicker = null;
        this.logoUpload = null;
        this.render();
        this.init();
    }

    render() {
        this.container.innerHTML = `
            <div class="intro-content">
                <h2>Pick a Template *</h2>

                <div class="form-group">
                    <label for="template-selection"></label>
                    <div id="template-selection-container"></div>
                    <!-- Hidden input for storage system compatibility -->
                    <input type="hidden" id="selectedTemplate" name="selectedTemplate" value="">
                </div>

                <p>This section will collect information for the document cover page.</p>

                <!-- Two-column layout for form fields -->
                <div class="intro-form-columns">
                    <div class="intro-column-left">
                        <div id="title-input-container"></div>
                        <div id="company-name-input-container"></div>
                        <div id="company-address-container"></div>
                    </div>
                    <div class="intro-column-right">
                        <div id="author-input-container"></div>
                        <div id="email-input-container"></div>
                        <div id="date-input-container"></div>
                        <div class="intro-color-pickers">
                            <div id="brand-color-picker-container"></div>
                            <div id="secondary-color-picker-container"></div>
                        </div>
                    </div>
                </div>

                <!-- Logo upload - full width below columns -->
                <div id="logo-upload-container"></div>

                <!-- Next button container -->
                <div class="form-actions-right">
                    <div id="intro-next-button-container"></div>
                </div>
            </div>
        `;
    }

    init() {
        this.initializeTextInputs();
        this.initializeAddressComponent();
        this.initializeColorPickers();
        this.initializeTemplateSelection();
        this.initializeLogoUpload();
    }

    initializeTextInputs() {

        if (typeof TextInput === 'undefined') {
            setTimeout(() => this.initializeTextInputs(), 100);
            return;
        }

        this.titleInput = new TextInput({
            containerId: 'title-input-container',
            id: 'intro-title',
            name: 'title',
            label: 'Document Title',
            placeholder: 'Enter document title',
            defaultValue: 'Job Demands Analysis',
            required: true
        });

        this.companyNameInput = new TextInput({
            containerId: 'company-name-input-container',
            id: 'intro-company-name',
            name: 'companyName',
            label: 'Company Name',
            placeholder: 'Enter company name',
            required: true
        });

        this.authorInput = new TextInput({
            containerId: 'author-input-container',
            id: 'intro-author',
            name: 'author',
            label: 'Your Name (Author)',
            placeholder: 'First Last',
            required: true
        });

        this.emailInput = new TextInput({
            containerId: 'email-input-container',
            id: 'intro-email',
            name: 'email',
            label: 'Your Email Address',
            placeholder: 'example@example.com',
            type: 'email',
            required: true
        });

        this.dateInput = new TextInput({
            containerId: 'date-input-container',
            id: 'intro-date',
            name: 'date',
            label: 'Today\'s Date',
            type: 'date',
            defaultValue: new Date().toISOString().split('T')[0],
            required: true
        });
    }

    initializeAddressComponent() {

        if (typeof Address === 'undefined') {
            setTimeout(() => this.initializeAddressComponent(), 100);
            return;
        }

        this.companyAddress = new Address({
            containerId: 'company-address-container',
            compact: false,
            required: true,
            showLabel: false
        });
    }

    initializeColorPickers() {

        if (typeof ColorPicker === 'undefined') {
            setTimeout(() => this.initializeColorPickers(), 100);
            return;
        }

        this.brandColorPicker = new ColorPicker({
            containerId: 'brand-color-picker-container',
            id: 'intro-brand-color',
            name: 'brandColor',
            label: 'Primary Brand Color',
            defaultValue: '#003366',
            required: false,
            helpText: 'Select your primary brand color',
            style: 'margin-top: calc(var(--spacing-md) * -1);'
        });

        this.secondaryColorPicker = new ColorPicker({
            containerId: 'secondary-color-picker-container',
            id: 'intro-secondary-color',
            name: 'secondaryBrandColor',
            label: 'Secondary Brand Color',
            defaultValue: '#001e96',
            required: false,
            helpText: 'Select your secondary brand color',
            style: 'margin-top: calc(var(--spacing-md) * -1);'
        });
    }

    initializeLogoUpload() {

        if (typeof ImageUpload === 'undefined') {
            setTimeout(() => this.initializeLogoUpload(), 100);
            return;
        }

        this.logoUpload = new ImageUpload({
            containerId: 'logo-upload-container',
            id: 'intro-company-logo',
            name: 'companyLogo',
            label: 'Company Logo',
            required: false,
            maxFiles: 1,
            maxFileSize: 5 * 1024 * 1024,
            acceptedFormats: ['image/jpeg', 'image/png', 'jpg']
        });
    }

    initializeTemplateSelection() {

        if (typeof Cards === 'undefined') {
            setTimeout(() => this.initializeTemplateSelection(), 100);
            return;
        }

        const templateCards = [
            {
                title: 'Classic Template',
                content: 'Traditional professional document layout',
                image: 'src/templates/images/template_1.png',
                pdf: 'src/templates/pdf/template_1.pdf',
                value: 'template_1',
                generator: 'Template1Generator',
                preview: 'Template1Preview'

            }
        ];

        this.templateCards = new Cards({
            containerId: 'template-selection-container',
            cards: templateCards,
            multiSelect: false,
            required: true,
            gridLayout: '3x2',
            onChange: (selection) => {
                if (selection.length > 0) {
                    this.selectedTemplate = selection[0].value;

                    const hiddenInput = document.getElementById('selectedTemplate');
                    if (hiddenInput) {
                        hiddenInput.value = this.selectedTemplate;
                    }
                } else {
                    this.selectedTemplate = null;

                    const hiddenInput = document.getElementById('selectedTemplate');
                    if (hiddenInput) {
                        hiddenInput.value = '';
                    }
                }
            }
        });
    }

    getSelectedTemplateClasses() {
        if (!this.selectedTemplate || !this.templateCards) {
            return { generator: null, preview: null };
        }

        const selectedCard = this.templateCards.cards.find(card => card.value === this.selectedTemplate);

        if (selectedCard) {
            return {
                generator: selectedCard.generator,
                preview: selectedCard.preview
            };
        }

        return { generator: null, preview: null };
    }

    getData() {
        const data = {
            template: this.selectedTemplate || '',
            selectedTemplate: this.selectedTemplate || ''
        };

        if (this.titleInput) Object.assign(data, this.titleInput.getData());
        if (this.companyNameInput) Object.assign(data, this.companyNameInput.getData());
        if (this.authorInput) Object.assign(data, this.authorInput.getData());
        if (this.emailInput) Object.assign(data, this.emailInput.getData());
        if (this.dateInput) Object.assign(data, this.dateInput.getData());

        if (this.companyAddress) {
            const addressData = this.companyAddress.getData();

            data.companyStreet = addressData.street;
            data.companyCity = addressData.city;
            data.companyState = addressData.state;
            data.companyZip = addressData.zip;
        }

        if (this.brandColorPicker) Object.assign(data, this.brandColorPicker.getData());
        if (this.secondaryColorPicker) Object.assign(data, this.secondaryColorPicker.getData());

        if (this.logoUpload) Object.assign(data, this.logoUpload.getData());

        return data;
    }

    setData(data) {

        if (this.titleInput) this.titleInput.setData(data);
        if (this.companyNameInput) this.companyNameInput.setData(data);
        if (this.authorInput) this.authorInput.setData(data);
        if (this.emailInput) this.emailInput.setData(data);
        if (this.dateInput) this.dateInput.setData(data);

        if (this.companyAddress) {
            const addressData = {
                street: data.companyStreet || '',
                city: data.companyCity || '',
                state: data.companyState || '',
                zip: data.companyZip || ''
            };
            this.companyAddress.setData(addressData);
        }

        if (this.brandColorPicker) this.brandColorPicker.setData(data);
        if (this.secondaryColorPicker) this.secondaryColorPicker.setData(data);

        const templateValue = data.template || data.selectedTemplate;
        if (templateValue && this.templateCards) {
            this.templateCards.setSelection([templateValue]);
            this.selectedTemplate = templateValue;

            const hiddenInput = document.getElementById('selectedTemplate');
            if (hiddenInput) {
                hiddenInput.value = templateValue;
            }
        }

        if (this.logoUpload) this.logoUpload.setData(data);
    }

    validate() {
        let isValid = true;

        if (this.titleInput && !this.titleInput.validate()) isValid = false;
        if (this.companyNameInput && !this.companyNameInput.validate()) isValid = false;
        if (this.authorInput && !this.authorInput.validate()) isValid = false;
        if (this.emailInput && !this.emailInput.validate()) isValid = false;
        if (this.dateInput && !this.dateInput.validate()) isValid = false;

        if (this.companyAddress && !this.companyAddress.validate()) isValid = false;

        const hasTemplate = this.selectedTemplate !== null && this.selectedTemplate !== '';
        if (!hasTemplate && this.templateCards) {
            this.templateCards.showValidationError('Please select a template to continue');
            isValid = false;
        }

        return isValid;
    }
}

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