document.addEventListener('DOMContentLoaded', () => {
    initConditionalFields();
    initDependents();
    initMasks();
    initDataTable();
    initFilePreviews();
    scrollToFirstError();
});

function initConditionalFields() {
    document.querySelectorAll('.toggle-field').forEach((field) => {
        const updateState = () => {
            const target = document.querySelector(field.dataset.target);
            if (!target) return;
            target.classList.toggle('is-hidden', String(field.value) !== '1');
        };

        field.addEventListener('change', updateState);
        updateState();
    });
}

function initDependents() {
    const wrapper = document.getElementById('dependents-wrapper');
    const addButton = document.getElementById('add-dependent');

    if (!wrapper || !addButton) return;

    const reindex = () => {
        [...wrapper.querySelectorAll('.dependent-card')].forEach((card, index) => {
            const title = card.querySelector('h3');
            if (title) title.textContent = `Dependente ${index + 1}`;

            card.querySelectorAll('input, select').forEach((input) => {
                const name = input.getAttribute('name');
                if (name) {
                    input.setAttribute('name', name.replace(/dependents\[\d+\]/, `dependents[${index}]`));
                }
            });
        });
    };

    addButton.addEventListener('click', () => {
        const newIndex = wrapper.querySelectorAll('.dependent-card').length;
        const card = document.createElement('div');

        card.className = 'dependent-card border rounded-4 p-3';
        card.innerHTML = `
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h3 class="h6 mb-0">Dependente ${newIndex + 1}</h3>
                <button type="button" class="btn btn-sm btn-outline-danger remove-dependent">Remover</button>
            </div>
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">Nome completo</label>
                    <input type="text" class="form-control" name="dependents[${newIndex}][full_name]">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Data de nascimento</label>
                    <input type="date" class="form-control" name="dependents[${newIndex}][birth_date]">
                </div>
                <div class="col-md-3">
                    <label class="form-label">CPF</label>
                    <input type="text" class="form-control js-cpf" name="dependents[${newIndex}][cpf]">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Deficiência?</label>
                    <select class="form-select" name="dependents[${newIndex}][has_disability]">
                        <option value="0">Não</option>
                        <option value="1">Sim</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Local/cidade de nascimento</label>
                    <input type="text" class="form-control" name="dependents[${newIndex}][birth_city]">
                </div>
            </div>
        `;

        wrapper.appendChild(card);
        initMasks();
        reindex();
    });

    wrapper.addEventListener('click', (event) => {
        const button = event.target.closest('.remove-dependent');
        if (!button) return;

        const card = button.closest('.dependent-card');
        if (card && wrapper.querySelectorAll('.dependent-card').length > 1) {
            card.remove();
            reindex();
        }
    });
}

function initMasks() {
    applyMask('.js-cpf', cpfMask);
    applyMask('.js-phone', phoneMask);
    applyMask('.js-cep', cepMask);
    applyMask('.js-cnpj', cnpjMask);
    applyMask('.js-money', moneyMask);
}

function applyMask(selector, formatter) {
    document.querySelectorAll(selector).forEach((input) => {
        input.removeEventListener('input', input._maskHandler || (() => { }));

        const handler = () => {
            input.value = formatter(input.value);
        };

        input._maskHandler = handler;
        input.addEventListener('input', handler);
    });
}

function initFilePreviews() {
    document.querySelectorAll('.js-file-preview').forEach((input) => {
        const wrapper = document.querySelector(input.dataset.previewTarget);
        const image = document.querySelector(input.dataset.previewImage);
        const meta = document.querySelector(input.dataset.previewMeta);

        if (!wrapper || !image || !meta) return;

        input.addEventListener('change', () => {
            const file = input.files && input.files[0] ? input.files[0] : null;
            const media = wrapper.querySelector('.upload-preview__media');

            if (!file) {
                wrapper.classList.add('is-empty');
                if (media) media.classList.add('d-none');
                image.removeAttribute('src');
                meta.innerHTML = `
                    <div class="upload-preview__filename">Nenhum arquivo selecionado</div>
                    <div class="upload-preview__hint">A miniatura aparece aqui quando você escolher uma imagem.</div>
                `;
                return;
            }

            wrapper.classList.remove('is-empty');

            if (file.type.startsWith('image/')) {
                const objectUrl = URL.createObjectURL(file);

                image.src = objectUrl;
                if (media) media.classList.remove('d-none');

                meta.innerHTML = `
                    <div class="upload-preview__filename">${escapeHtml(file.name)}</div>
                    <div class="upload-preview__hint">Pré-visualização da imagem selecionada</div>
                `;

                image.onload = () => URL.revokeObjectURL(objectUrl);
                return;
            }

            if (media) media.classList.add('d-none');
            image.removeAttribute('src');

            meta.innerHTML = `
                <div class="upload-preview__filename">${escapeHtml(file.name)}</div>
                <div class="upload-preview__hint">Arquivo selecionado. Prévia visual disponível apenas para imagens.</div>
            `;
        });
    });
}

function onlyDigits(v) {
    return v.replace(/\D/g, '');
}

function cpfMask(v) {
    v = onlyDigits(v).slice(0, 11);
    v = v.replace(/(\d{3})(\d)/, '$1.$2');
    v = v.replace(/(\d{3})(\d)/, '$1.$2');
    return v.replace(/(\d{3})(\d{1,2})$/, '$1-$2');
}

function phoneMask(v) {
    v = onlyDigits(v).slice(0, 11);

    if (v.length <= 10) {
        v = v.replace(/(\d{2})(\d)/, '($1) $2');
        return v.replace(/(\d{4})(\d)/, '$1-$2');
    }

    v = v.replace(/(\d{2})(\d)/, '($1) $2');
    return v.replace(/(\d{5})(\d)/, '$1-$2');
}

function cepMask(v) {
    v = onlyDigits(v).slice(0, 8);
    return v.replace(/(\d{5})(\d)/, '$1-$2');
}

function cnpjMask(v) {
    v = onlyDigits(v).slice(0, 14);
    v = v.replace(/^(\d{2})(\d)/, '$1.$2');
    v = v.replace(/^(\d{2})\.(\d{3})(\d)/, '$1.$2.$3');
    v = v.replace(/\.(\d{3})(\d)/, '.$1/$2');
    return v.replace(/(\d{4})(\d)/, '$1-$2');
}

function moneyMask(v) {
    v = v.replace(/[^\d,]/g, '').replace(',', '.');
    const n = parseFloat(v);
    if (Number.isNaN(n)) return '';
    return n.toFixed(2).replace('.', ',');
}

function initDataTable() {
    const table = document.getElementById('admissions-table');
    if (!table || typeof window.DataTable === 'undefined') return;

    const tbody = table.querySelector('tbody');
    const headerCells = table.querySelectorAll('thead th').length;
    const rows = tbody ? Array.from(tbody.querySelectorAll('tr')) : [];

    if (!rows.length) return;

    const invalidRow = rows.some((row) => row.children.length !== headerCells);
    if (invalidRow) return;

    new DataTable(table, {
        language: {
            search: 'Filtrar resultados:',
            lengthMenu: 'Mostrar _MENU_ registros',
            info: 'Mostrando _START_ a _END_ de _TOTAL_ registros',
            paginate: {
                first: 'Primeira',
                last: 'Última',
                next: 'Próxima',
                previous: 'Anterior'
            },
            zeroRecords: 'Nenhum resultado encontrado',
            infoEmpty: 'Nenhum registro disponível',
            infoFiltered: '(filtrado de _MAX_ registros)'
        },
        order: [[0, 'desc']],
        pageLength: 10
    });
}

function escapeHtml(value) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };

    return String(value).replace(/[&<>"']/g, (m) => map[m]);
}

function scrollToFirstError() {
    const firstInvalid = document.querySelector('.is-invalid, .field-error');
    if (!firstInvalid) return;

    const target = firstInvalid.classList.contains('field-error')
        ? firstInvalid.previousElementSibling || firstInvalid
        : firstInvalid;

    window.requestAnimationFrame(() => {
        target.scrollIntoView({ behavior: 'smooth', block: 'center' });
        if (typeof target.focus === 'function') {
            target.focus({ preventScroll: true });
        }
    });
}
