
// Using a React-like functional component approach for structure, though not using React library.
// All elements are created directly using document.createElement.

interface FormDataValues {
    [key: string]: string | number | boolean | undefined;
}

const App = () => {
    const root = document.getElementById('root');
    if (!root) return;

    // Clear existing content
    root.innerHTML = '';

    // Create header
    const header = document.createElement('header');
    const h1 = document.createElement('h1');
    h1.textContent = 'Mapa de Crédito';
    const pHeader = document.createElement('p');
    pHeader.textContent = 'Preencha o formulário abaixo para entendermos suas necessidades.';
    header.appendChild(h1);
    header.appendChild(pHeader);
    root.appendChild(header);

    // Create form
    const form = document.createElement('form');
    form.id = 'creditMapForm';
    form.setAttribute('novalidate', 'true'); // Disable browser validation

    // Helper to create a required indicator
    const createRequiredIndicator = () => {
        const span = document.createElement('span');
        span.className = 'required-indicator';
        span.textContent = '*';
        span.setAttribute('aria-hidden', 'true');
        return span;
    };
    
    // Helper function to create form groups with various input types
    const createFormGroup = (
        id: string, 
        labelText: string, 
        type: string, 
        options: { value: string; text: string }[] = [], 
        required: boolean = false,
        attrs: { [key: string]: string } = {},
        helperText?: string
    ): HTMLElement => {
        const group = document.createElement('div');
        group.className = 'form-group';

        const label = document.createElement('label');
        label.setAttribute('for', id);
        label.textContent = labelText;
        if (required) {
            label.appendChild(createRequiredIndicator());
        }
        
        let inputElement: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;

        if (type === 'select') {
            inputElement = document.createElement('select');
            // Add a default, non-selectable, placeholder option
            const placeholderOption = document.createElement('option');
            placeholderOption.value = '';
            placeholderOption.textContent = `Selecione ${labelText.toLowerCase()}...`;
            placeholderOption.disabled = true;
            placeholderOption.selected = true;
            inputElement.appendChild(placeholderOption);

            options.forEach(opt => {
                const option = document.createElement('option');
                option.value = opt.value;
                option.textContent = opt.text;
                inputElement.appendChild(option);
            });
        } else if (type === 'textarea') {
            inputElement = document.createElement('textarea');
        } else {
            inputElement = document.createElement('input');
            inputElement.type = type;
        }

        inputElement.id = id;
        inputElement.name = id;
        if (required) {
            inputElement.setAttribute('aria-required', 'true');
            inputElement.required = true; // Also set native required for easier selection later
        }

        for (const key in attrs) {
            inputElement.setAttribute(key, attrs[key]);
        }
        
        group.appendChild(label);
        group.appendChild(inputElement);

        if (helperText) {
            const small = document.createElement('small');
            small.className = 'helper-text';
            small.textContent = helperText;
            group.appendChild(small);
        }
        
        const errorSpan = document.createElement('span');
        errorSpan.className = 'error-message';
        errorSpan.id = `${id}-error`;
        errorSpan.setAttribute('aria-live', 'polite');
        group.appendChild(errorSpan);

        return group;
    };

    // Helper function to create radio button groups
    const createRadioGroup = (
        name: string,
        labelText: string,
        options: { value: string; text: string; id: string }[],
        required: boolean = false,
        onChangeCallback?: (value: string) => void
    ): HTMLElement => {
        const fieldset = document.createElement('fieldset');
        fieldset.className = 'form-group radio-group-container'; 
        fieldset.setAttribute('role', 'radiogroup');


        const legend = document.createElement('legend');
        legend.className = 'radio-group-label';
        legend.textContent = labelText;
        if (required) {
            legend.appendChild(createRequiredIndicator());
        }
        fieldset.appendChild(legend);

        const radioWrapper = document.createElement('div');
        radioWrapper.className = 'radio-group';

        options.forEach((opt, index) => {
            const optionContainer = document.createElement('div');
            optionContainer.className = 'radio-option';

            const radioInput = document.createElement('input');
            radioInput.type = 'radio';
            radioInput.id = opt.id;
            radioInput.name = name;
            radioInput.value = opt.value;
            if (required) radioInput.setAttribute('aria-required', 'true');
            if (index === 0 && required) { // For validation logic
                 (radioInput as any)._isRadioGroupRequired = true;
            }
            
            radioInput.addEventListener('change', () => {
                if (onChangeCallback) {
                    onChangeCallback(radioInput.value);
                }
                const errorSpan = fieldset.querySelector('.error-message');
                if (errorSpan) errorSpan.textContent = '';
                fieldset.removeAttribute('aria-invalid');
            });
            
            const radioLabel = document.createElement('label');
            radioLabel.setAttribute('for', opt.id);
            radioLabel.textContent = opt.text;

            optionContainer.appendChild(radioInput);
            optionContainer.appendChild(radioLabel);
            radioWrapper.appendChild(optionContainer);
        });
        
        fieldset.appendChild(radioWrapper);
        const errorSpan = document.createElement('span');
        errorSpan.className = 'error-message';
        errorSpan.id = `${name}-error`;
        errorSpan.setAttribute('aria-live', 'polite');
        fieldset.appendChild(errorSpan);
        
        return fieldset;
    };


    // Function to create a form section
    const createSection = (title: string, fields: HTMLElement[]): HTMLElement => {
        const section = document.createElement('fieldset');
        section.className = 'form-section';
        const legend = document.createElement('legend');
        legend.textContent = title;
        section.appendChild(legend);
        fields.forEach(field => section.appendChild(field));
        return section;
    };

    // --- Define form structure ---

    // 1. Dados da Empresa
    const empresaFields = [
        createFormGroup('nomeEmpresa', 'Nome da Empresa', 'text', [], true),
        createFormGroup('cnpj', 'CNPJ', 'text', [], true, { placeholder: '00.000.000/0000-00', pattern: '^\\d{2}\\.\\d{3}\\.\\d{3}/\\d{4}-\\d{2}$' }, 'Formato: XX.XXX.XXX/XXXX-XX'),
        createFormGroup('dataFundacao', 'Data de Fundação', 'date', [], true),
        createFormGroup('setorAtuacao', 'Setor de Atuação', 'select', [
            { value: 'comercio', text: 'Comércio' },
            { value: 'servicos', text: 'Serviços' },
            { value: 'industria', text: 'Indústria' },
            { value: 'agronegocio', text: 'Agronegócio' },
            { value: 'outro', text: 'Outro' },
        ], true),
        createFormGroup('porteEmpresa', 'Porte da Empresa', 'select', [
            { value: 'mei', text: 'MEI - Microempreendedor Individual' },
            { value: 'me', text: 'ME - Microempresa' },
            { value: 'epp', text: 'EPP - Empresa de Pequeno Porte' },
            { value: 'medio', text: 'Média Empresa' },
            { value: 'grande', text: 'Grande Empresa' },
        ], true),
        createFormGroup('faturamentoAnual', 'Faturamento Anual (Estimado)', 'select', [
            { value: 'ate_81k', text: 'Até R$ 81 mil (MEI)' },
            { value: 'ate_360k', text: 'Até R$ 360 mil (ME)' },
            { value: 'ate_4_8m', text: 'Até R$ 4.8 milhões (EPP)' },
            { value: 'ate_300m', text: 'Até R$ 300 milhões (Média)' },
            { value: 'acima_300m', text: 'Acima de R$ 300 milhões (Grande)' },
        ]),
    ];
    form.appendChild(createSection('Dados da Empresa', empresaFields));

    // 2. Informações Financeiras
    const valorDividasBancariasGroup = createFormGroup('valorTotalDividasBancarias', 'Valor Total das Dívidas Bancárias (R$)', 'number', [], false, { placeholder: '0.00', step: '0.01', min: '0' });
    valorDividasBancariasGroup.style.display = 'none'; // Initially hidden

    const infoFinanceirasFields = [
        createFormGroup('regimeTributario', 'Regime Tributário', 'select', [
            { value: 'simples', text: 'Simples Nacional' },
            { value: 'presumido', text: 'Lucro Presumido' },
            { value: 'real', text: 'Lucro Real' },
            { value: 'mei', text: 'MEI (Simei)' },
        ], true),
        createRadioGroup('restricoesCnpj', 'Possui Restrições no CNPJ?', [
            { value: 'sim', text: 'Sim', id: 'restricoesCnpjSim' },
            { value: 'nao', text: 'Não', id: 'restricoesCnpjNao' },
        ], true),
        createRadioGroup('dividasBancarias', 'Possui Dívidas Bancárias?', [
            { value: 'sim', text: 'Sim', id: 'dividasBancariasSim' },
            { value: 'nao', text: 'Não', id: 'dividasBancariasNao' },
        ], true, (value) => {
            const label = valorDividasBancariasGroup.querySelector('label') as HTMLLabelElement;
            const input = valorDividasBancariasGroup.querySelector('input') as HTMLInputElement;
            if (value === 'sim') {
                valorDividasBancariasGroup.style.display = 'block';
                input.setAttribute('aria-required', 'true');
                input.required = true;
                if(label && !label.querySelector('.required-indicator')) {
                    label.appendChild(createRequiredIndicator());
                }
            } else {
                valorDividasBancariasGroup.style.display = 'none';
                input.removeAttribute('aria-required');
                input.required = false;
                input.value = ''; // Clear value
                const indicator = label.querySelector('.required-indicator');
                if (indicator) label.removeChild(indicator);
                const errorSpan = valorDividasBancariasGroup.querySelector('.error-message');
                if (errorSpan && errorSpan.textContent) errorSpan.textContent = ''; // Clear error
            }
        }),
        valorDividasBancariasGroup,
        createFormGroup('principaisBancos', 'Principais Bancos com Relacionamento', 'textarea', [], false, { rows: '3', placeholder: 'Ex: Banco do Brasil, Itaú, Bradesco...' }),
    ];
    form.appendChild(createSection('Informações Financeiras', infoFinanceirasFields));
    
    // 3. Necessidade de Crédito
    const necessidadeCreditoFields = [
        createFormGroup('valorCreditoDesejado', 'Valor do Crédito Desejado (R$)', 'number', [], true, { placeholder: '0.00', step: '0.01', min: '0.01' }),
        createFormGroup('finalidadeCredito', 'Finalidade do Crédito', 'select', [
            { value: 'capital_giro', text: 'Capital de Giro' },
            { value: 'investimento', text: 'Investimento (Máquinas, Equipamentos, Expansão)' },
            { value: 'refinanciamento', text: 'Refinanciamento de Dívidas' },
            { value: 'inovacao', text: 'Inovação e Tecnologia' },
            { value: 'outro', text: 'Outro' },
        ], true),
        createFormGroup('prazoPagamento', 'Prazo Desejado para Pagamento (em meses)', 'number', [], false, { placeholder: 'Ex: 12, 24, 36', min: '1' }),
        createFormGroup('garantiasOferecidas', 'Garantias Oferecidas', 'textarea', [], false, { rows: '3', placeholder: 'Ex: Imóvel, Veículo, Avalista...' }),
    ];
    form.appendChild(createSection('Necessidade de Crédito', necessidadeCreditoFields));

    // 4. Informações Adicionais
    const infoAdicionaisFields = [
        createFormGroup('descricaoNegocio', 'Breve Descrição do Negócio', 'textarea', [], false, { rows: '4', placeholder: 'Descreva sua empresa, principais produtos/serviços e mercado de atuação.' }),
        createFormGroup('comoConheceu', 'Como nos conheceu?', 'select', [
            { value: 'indicacao', text: 'Indicação' },
            { value: 'google', text: 'Google / Pesquisa Online' },
            { value: 'redes_sociais', text: 'Redes Sociais' },
            { value: 'evento', text: 'Evento / Feira' },
            { value: 'parceiro', text: 'Parceiro' },
            { value: 'outro', text: 'Outro' },
        ]),
    ];
    form.appendChild(createSection('Informações Adicionais', infoAdicionaisFields));
    
    // 5. Dados de Contato
    const dadosContatoFields = [
        createFormGroup('nomeContato', 'Nome Completo do Contato', 'text', [], true),
        createFormGroup('emailContato', 'Email', 'email', [], true, { placeholder: 'seuemail@dominio.com' }),
        createFormGroup('telefoneContato', 'Telefone/Celular', 'tel', [], true, { placeholder: '(XX) XXXXX-XXXX', pattern: '^\\(\\d{2}\\)\\s\\d{4,5}-\\d{4}$' }, 'Formato: (XX) XXXXX-XXXX'),
        createFormGroup('cargoContato', 'Cargo na Empresa', 'text', [], false),
    ];
    form.appendChild(createSection('Dados de Contato', dadosContatoFields));


    // Submit Button
    const submitButton = document.createElement('button');
    submitButton.type = 'submit';
    submitButton.className = 'submit-button';
    submitButton.textContent = 'Enviar Análise';
    form.appendChild(submitButton);

    // Validation and Submission Logic
    const validateField = (field: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement): boolean => {
        let isValid = true;
        const group = field.closest('.form-group') || field.closest('.form-group.radio-group-container');
        const errorSpan = group?.querySelector('.error-message') as HTMLElement | null;
        
        if (!errorSpan) return true; 

        errorSpan.textContent = ''; 
        field.removeAttribute('aria-invalid');
        if (group && group.classList.contains('radio-group-container')) {
             group.removeAttribute('aria-invalid');
        }

        if (field.required && !field.value.trim() && field.type !== 'radio') {
            isValid = false;
            errorSpan.textContent = 'Este campo é obrigatório.';
        }
        else if (field instanceof HTMLInputElement && field.type === 'email' && field.value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(field.value)) {
                isValid = false;
                errorSpan.textContent = 'Por favor, insira um email válido.';
            }
        } 
        else if (field instanceof HTMLInputElement && field.type === 'tel' && field.value && field.pattern) {
             const telRegex = new RegExp(field.pattern);
             if(!telRegex.test(field.value)) {
                isValid = false;
                errorSpan.textContent = 'Formato de telefone inválido. Use (XX) XXXXX-XXXX.';
             }
        }
        else if (field instanceof HTMLInputElement && field.id === 'cnpj' && field.value && field.pattern) {
             const cnpjRegex = new RegExp(field.pattern);
             if(!cnpjRegex.test(field.value)) {
                isValid = false;
                errorSpan.textContent = 'Formato de CNPJ inválido. Use XX.XXX.XXX/XXXX-XX.';
             }
        }
        else if (field instanceof HTMLInputElement && field.type === 'number' && field.hasAttribute('min') && field.value) {
             const minValue = parseFloat(field.getAttribute('min')!);
            if (parseFloat(field.value) < minValue) {
                isValid = false;
                errorSpan.textContent = `O valor deve ser no mínimo ${minValue.toLocaleString('pt-BR', {minimumFractionDigits: field.step === '0.01' ? 2 : 0})}.`;
            }
        }

        if (!isValid) {
            field.setAttribute('aria-invalid', 'true');
            if (group && group.classList.contains('radio-group-container')) {
                 group.setAttribute('aria-invalid', 'true');
            }
        }
        return isValid;
    };

    const validateRadioGroup = (name: string): boolean => {
        const radioGroupFieldset = form.querySelector(`fieldset.radio-group-container input[name="${name}"]`)?.closest('fieldset.radio-group-container');
        if (!radioGroupFieldset) return true; 

        const firstRadio = radioGroupFieldset.querySelector('input[type="radio"]') as HTMLInputElement | null;
        if (!firstRadio || !(firstRadio as any)._isRadioGroupRequired) return true; // Not required

        const radios = form.elements.namedItem(name) as RadioNodeList;
        const errorSpan = radioGroupFieldset.querySelector('.error-message') as HTMLElement | null;
        if (!errorSpan) return true;

        errorSpan.textContent = '';
        radioGroupFieldset.removeAttribute('aria-invalid');

        if (radios && radios.value === '') { 
            errorSpan.textContent = 'Por favor, selecione uma opção.';
            radioGroupFieldset.setAttribute('aria-invalid', 'true');
            return false;
        }
        return true;
    };

    const validateForm = (): { isValid: boolean, firstInvalidField: HTMLElement | null } => {
        let isFormValid = true;
        let firstInvalidField: HTMLElement | null = null;
        const elements = form.elements;
        const validatedRadioGroups: string[] = [];

        for (let i = 0; i < elements.length; i++) {
            const element = elements[i] as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | HTMLButtonElement | HTMLFieldSetElement;
            
            if (element.tagName === 'BUTTON' || (element.tagName === 'FIELDSET' && !element.classList.contains('radio-group-container'))) continue;
            
            let currentFieldIsValid = true;
            if (element.type === 'radio') {
                if (!validatedRadioGroups.includes(element.name)) {
                    if (!validateRadioGroup(element.name)) {
                        currentFieldIsValid = false;
                        isFormValid = false;
                        if (!firstInvalidField) {
                             // For radio groups, focus the fieldset or the first radio button
                            firstInvalidField = element.closest('fieldset.radio-group-container') || element;
                        }
                    }
                    validatedRadioGroups.push(element.name);
                }
            } else if (element.id && (element.tagName === 'INPUT' || element.tagName === 'SELECT' || element.tagName === 'TEXTAREA')) {
                 // Check if the field is visible (relevant for conditionally shown fields)
                const group = element.closest('.form-group') as HTMLElement;
                if (group && group.style.display === 'none') {
                    continue; // Skip validation for hidden fields
                }

                if (!validateField(element as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement)) {
                    currentFieldIsValid = false;
                    isFormValid = false;
                    if (!firstInvalidField) {
                        firstInvalidField = element as HTMLElement;
                    }
                }
            }
        }
        return { isValid: isFormValid, firstInvalidField };
    };

    form.addEventListener('submit', (event) => {
        event.preventDefault(); // Prevent default submission in all cases initially
        submitButton.disabled = true; // Disable button during processing
        
        const { isValid, firstInvalidField } = validateForm();

        if (isValid) {
            const formData: FormDataValues = {};
            const elements = form.elements;

            for (let i = 0; i < elements.length; i++) {
                const element = elements[i] as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
                if (element.name && element.tagName !== 'BUTTON') {
                     // Skip hidden fields that are part of a non-selected conditional flow
                    const group = element.closest('.form-group') as HTMLElement;
                    if (group && group.style.display === 'none') {
                        formData[element.name] = undefined; // Or simply skip, depending on desired data structure
                        continue;
                    }

                    if (element.type === 'radio') {
                        if ((element as HTMLInputElement).checked) {
                            formData[element.name] = element.value;
                        }
                    } else if (element instanceof HTMLInputElement && element.type === 'number') {
                        formData[element.name] = element.value ? parseFloat(element.value) : undefined;
                    } 
                     else {
                        formData[element.name] = element.value;
                    }
                }
            }

            console.log('Form Data:', formData);
            alert('Análise enviada com sucesso! Em breve entraremos em contato.');
            form.reset(); // Reset form after successful submission

            // Reset conditional fields and their 'required' indicators
            const valorDividasGroup = document.getElementById('valorTotalDividasBancarias')?.closest('.form-group') as HTMLElement;
            if (valorDividasGroup) {
                valorDividasGroup.style.display = 'none';
                const input = valorDividasGroup.querySelector('input') as HTMLInputElement;
                const label = valorDividasGroup.querySelector('label') as HTMLLabelElement;
                input.required = false;
                input.removeAttribute('aria-required');
                input.value = ''; // Ensure value is cleared
                const indicator = label?.querySelector('.required-indicator');
                if (indicator) label.removeChild(indicator);
                 const errorSpan = valorDividasGroup.querySelector('.error-message');
                if (errorSpan) errorSpan.textContent = ''; // Clear any previous error message
            }
             // Re-enable select placeholders
            form.querySelectorAll('select').forEach(select => {
                if (select.options.length > 0 && select.options[0].disabled) {
                    select.selectedIndex = 0;
                }
                 // Clear any validation messages on selects
                const errorSpan = select.closest('.form-group')?.querySelector('.error-message');
                if (errorSpan) errorSpan.textContent = '';
                select.removeAttribute('aria-invalid');
            });
            // Clear all error messages and invalid states on other fields
            form.querySelectorAll('.form-group').forEach(group => {
                const errorSpan = group.querySelector('.error-message');
                if (errorSpan) errorSpan.textContent = '';
                const inputField = group.querySelector('input, select, textarea');
                inputField?.removeAttribute('aria-invalid');
                 if (group.classList.contains('radio-group-container')) {
                    group.removeAttribute('aria-invalid');
                }
            });


        } else {
            console.log('Form is invalid.');
            if (firstInvalidField) {
                firstInvalidField.focus();
                 // If it's a radio group container, try to focus the first radio inside
                if (firstInvalidField.classList.contains('radio-group-container')) {
                    const firstRadioInGroup = firstInvalidField.querySelector('input[type="radio"]') as HTMLInputElement | null;
                    firstRadioInGroup?.focus();
                }
            }
        }
        submitButton.disabled = false; // Re-enable button
    });

    root.appendChild(form);
};

// Initialize the App
App();
