document.addEventListener('DOMContentLoaded', function () {
    // === Multi-step Logic ===
    let currentStep = 1;
    const totalSteps = 3;

    function showStep(step) {
        document.querySelectorAll('.step-content').forEach(el => el.classList.remove('active'));
        document.getElementById('step-' + step).classList.add('active');

        // Update Progress
        document.querySelectorAll('.progress-step').forEach((el, index) => {
            if (index + 1 <= step) {
                el.classList.add('active');
                el.style.backgroundColor = 'var(--primary-color)';
                el.style.color = '#fff';
            } else {
                el.classList.remove('active');
                el.style.backgroundColor = '#fff';
                el.style.color = '#6b7280';
            }
        });

        currentStep = step;

        // Button visibility
        if (currentStep === 1) {
            document.getElementById('prevBtn').style.visibility = 'hidden';
            document.getElementById('nextBtn').style.display = 'block';
            document.getElementById('submitBtn').style.display = 'none';
        } else if (currentStep === totalSteps) {
            document.getElementById('prevBtn').style.visibility = 'visible';
            document.getElementById('nextBtn').style.display = 'none';
            document.getElementById('submitBtn').style.display = 'block';
        } else {
            document.getElementById('prevBtn').style.visibility = 'visible';
            document.getElementById('nextBtn').style.display = 'block';
            document.getElementById('submitBtn').style.display = 'none';
        }
    }

    // Initial State
    showStep(1);

    document.getElementById('nextBtn').addEventListener('click', () => {
        if (validateStep(currentStep)) {
            showStep(currentStep + 1);
        }
    });

    document.getElementById('prevBtn').addEventListener('click', () => {
        showStep(currentStep - 1);
    });

    // === Global Helper Functions ===
    window.copyText = function (elementId) {
        const textToCopy = document.getElementById(elementId).textContent;
        navigator.clipboard.writeText(textToCopy).then(() => {
            alert('Copied to clipboard!');
        });
    };

    window.copyAllDetails = function () {
        const id = document.getElementById('final-nroi-id').textContent;
        const pass = document.getElementById('final-password').textContent;
        const text = `NROI ACCOUNT DETAILS\nNROI Id: ${id}\nPassword: ${pass}`;

        navigator.clipboard.writeText(text).then(() => {
            const btn = document.querySelector('.copy-btn[onclick="copyAllDetails()"]');
            const originalHtml = btn.innerHTML;
            btn.innerHTML = '<i class="fa-solid fa-check"></i> Copied!';
            setTimeout(() => { btn.innerHTML = originalHtml; }, 2000);
        });
    };

    // Toggle Password Visibility
    document.querySelectorAll('.toggle-password').forEach(icon => {
        icon.addEventListener('click', function () {
            const targetId = this.getAttribute('data-target');
            const input = document.getElementById(targetId);
            if (input.type === 'password') {
                input.type = 'text';
                this.classList.replace('fa-eye', 'fa-eye-slash');
            } else {
                input.type = 'password';
                this.classList.replace('fa-eye-slash', 'fa-eye');
            }
        });
    });

    // === Validation ===
    function validateStep(step) {
        let isValid = true;
        const currentTab = document.getElementById('step-' + step);
        const inputs = currentTab.querySelectorAll('input[required], select[required]');

        inputs.forEach(input => {
            if (!input.value.trim()) {
                input.classList.add('invalid');
                isValid = false;
            } else {
                input.classList.remove('invalid');
            }
        });

        if (!isValid) {
            alert('Please fill in all required fields.');
            return false;
        }

        // Specific checks
        if (step === 3) {
            // Check password match
            const pass = document.getElementById('password').value;
            const confirm = document.getElementById('confirmPassword').value;
            if (pass !== confirm) {
                alert('Passwords do not match');
                return false;
            }

            // Check Active Member
            const activeMember = document.querySelector('input[name="is_active_nroi_member"]:checked');
            if (!activeMember) {
                alert('Please select if you are an active NROI member.');
                return false;
            }
            if (activeMember.value === 'no') {
                alert('You must be an active NROI member to register.');
                return false;
            }
        }

        return true;
    }

    // === Address Logic (PSGC API) ===
    const apiBase = 'https://psgc.gitlab.io/api';
    let zipcodeData = [];

    // Load Zipcode Data
    fetch('assets/data/zipcodes.json')
        .then(res => res.json())
        .then(data => {
            zipcodeData = data;
            console.log("Zipcode database loaded");
        })
        .catch(err => console.error("Could not load zipcodes:", err));

    // Fetch Regions
    fetch(`${apiBase}/regions/`)
        .then(res => res.json())
        .then(data => {
            data.sort((a, b) => a.name.localeCompare(b.name));
            const regionSelect = document.getElementById('region');
            data.forEach(reg => {
                const opt = document.createElement('option');
                opt.value = reg.code;
                opt.textContent = reg.name + ' (' + reg.regionName + ')';
                regionSelect.appendChild(opt);
            });
        });

    document.getElementById('region').addEventListener('change', function () {
        // Load Provinces
        const code = this.value;
        const provSelect = document.getElementById('province');
        provSelect.innerHTML = '<option value="">Select Province</option>';
        document.getElementById('city').innerHTML = '<option value="">Select City/Municipality</option>';
        document.getElementById('barangay').innerHTML = '<option value="">Select Barangay</option>';

        fetch(`${apiBase}/regions/${code}/provinces/`)
            .then(res => res.json())
            .then(data => {
                data.sort((a, b) => a.name.localeCompare(b.name));
                data.forEach(prov => {
                    const opt = document.createElement('option');
                    opt.value = prov.code;
                    opt.textContent = prov.name;
                    provSelect.appendChild(opt);
                });
            });
    });

    document.getElementById('province').addEventListener('change', function () {
        // Load Cities/Municipalities
        const code = this.value;
        const citySelect = document.getElementById('city');
        citySelect.innerHTML = '<option value="">Select City/Municipality</option>';
        document.getElementById('barangay').innerHTML = '<option value="">Select Barangay</option>';

        fetch(`${apiBase}/provinces/${code}/cities-municipalities/`)
            .then(res => res.json())
            .then(data => {
                data.sort((a, b) => a.name.localeCompare(b.name));
                data.forEach(city => {
                    const opt = document.createElement('option');
                    opt.value = city.code;
                    opt.textContent = city.name;
                    if (city.zipCode) {
                        opt.dataset.zip = city.zipCode;
                    }
                    citySelect.appendChild(opt);
                });
            });
    });

    document.getElementById('city').addEventListener('change', function () {
        // Load Barangays
        const code = this.value;
        const brgySelect = document.getElementById('barangay');
        const zipcodeField = document.getElementById('zipcode');

        brgySelect.innerHTML = '<option value="">Select Barangay</option>';

        // Update Zipcode Preview
        const selectedOption = this.options[this.selectedIndex];
        if (selectedOption && selectedOption.value) {
            const cityName = selectedOption.textContent.trim();
            const provinceSelect = document.getElementById('province');
            const provinceName = provinceSelect.options[provinceSelect.selectedIndex].textContent.trim();

            // Search in our new database
            const found = zipcodeData.find(item => {
                const area = item.area.toLowerCase();
                return area.includes(provinceName.toLowerCase()) && area.includes(cityName.toLowerCase());
            });

            if (found) {
                zipcodeField.value = found.zip;
                zipcodeField.classList.add('valid');
                zipcodeField.style.borderColor = 'var(--success-color)';
            } else {
                const cityCode = selectedOption.value;
                const regionPrefix = cityCode.substring(0, 2);
                zipcodeField.value = regionPrefix + "00";
                zipcodeField.classList.remove('valid');
                zipcodeField.style.borderColor = '';
            }
        }

        if (code) {
            fetch(`${apiBase}/cities-municipalities/${code}/barangays/`)
                .then(res => res.json())
                .then(data => {
                    data.sort((a, b) => a.name.localeCompare(b.name));
                    data.forEach(brgy => {
                        const opt = document.createElement('option');
                        opt.value = brgy.code;
                        opt.textContent = brgy.name;
                        brgySelect.appendChild(opt);
                    });
                });
        }
    });

    // === Auto Age Calculation ===
    document.getElementById('dob').addEventListener('change', function () {
        const dob = new Date(this.value);
        const diff_ms = Date.now() - dob.getTime();
        const age_dt = new Date(diff_ms);
        const age = Math.abs(age_dt.getUTCFullYear() - 1970);
        document.getElementById('age').value = age;
    });

    // === Email & Phone Validation ===
    const emailInput = document.getElementById('email');
    const phoneInput = document.getElementById('phone');

    emailInput.addEventListener('input', function () {
        const val = this.value;
        const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val);
        if (valid) {
            fetch('api/check_email.php?email=' + val)
                .then(r => r.json())
                .then(d => {
                    if (d.valid && d.is_unique) {
                        this.classList.add('valid');
                        this.classList.remove('invalid');
                    } else {
                        this.classList.remove('valid');
                        this.classList.add('invalid');
                    }
                });
        } else {
            this.classList.remove('valid');
            this.classList.add('invalid');
        }
    });

    const emergencyPhone = document.getElementById('emergency_phone');
    const viberPhone = document.getElementById('viber_phone');
    const telegramPhone = document.getElementById('telegram_phone');

    [phoneInput, emergencyPhone, viberPhone, telegramPhone].forEach(input => {
        if (input) {
            input.addEventListener('input', function () {
                const val = this.value.trim();
                if ((this === viberPhone || this === telegramPhone) && !val) {
                    this.classList.remove('valid', 'invalid');
                    this.style.borderColor = '';
                    return;
                }
                const hintId = this === emergencyPhone ? 'emergency-hint' : null;
                validatePhoneNumber(this, hintId);
            });
        }
    });

    function validatePhoneNumber(input, hintId = null) {
        if (!input) return;
        const val = input.value.trim();
        const validFormat = /^(09|\+639)\d{9}$/.test(val);
        const hint = hintId ? document.getElementById(hintId) : null;

        const setValid = (msg = '') => {
            input.classList.add('valid');
            input.classList.remove('invalid');
            input.style.borderColor = 'var(--success-color)';
            if (hint) { hint.textContent = msg; hint.style.color = 'var(--success-color)'; }
        };

        const setInvalid = (msg) => {
            input.classList.remove('valid');
            input.classList.add('invalid');
            input.style.borderColor = 'var(--error-color)';
            if (hint) { hint.textContent = msg; hint.style.color = 'var(--error-color)'; }
        };

        if (validFormat) {
            // Check uniqueness for ALL phone-related fields
            fetch('api/check_phone.php?phone=' + encodeURIComponent(val))
                .then(r => r.json())
                .then(d => {
                    if (d.valid && d.is_unique) {
                        setValid('Number is valid and unique.');
                    } else {
                        setInvalid(d.message || 'This number is already in use.');
                    }
                })
                .catch(() => setValid());
        } else if (val) {
            setInvalid('Format: 09xxxxxxxxx or +639xxxxxxxxx');
        } else {
            input.classList.remove('valid', 'invalid');
            input.style.borderColor = '';
        }
    }

    // === PPSA ID Validation ===
    const ppsaInput = document.querySelector('input[name="ppsa_id"]');
    if (ppsaInput) {
        ppsaInput.addEventListener('input', function () {
            const val = this.value.trim();
            if (!val) {
                this.style.borderColor = '';
                this.classList.remove('valid', 'invalid');
                return;
            }

            fetch('api/check_ppsa_id.php?ppsa_id=' + encodeURIComponent(val))
                .then(r => r.json())
                .then(d => {
                    if (d.valid && d.is_unique) {
                        this.style.borderColor = 'var(--success-color)';
                        this.classList.add('valid');
                        this.classList.remove('invalid');
                    } else {
                        this.style.borderColor = 'var(--error-color)';
                        this.classList.remove('valid');
                        this.classList.add('invalid');
                    }
                });
        });
    }

    // === Active Member Logic ===
    const activeRadiosArr = document.querySelectorAll('input[name="is_active_nroi_member"]');
    activeRadiosArr.forEach(radio => {
        radio.addEventListener('change', function () {
            const container = document.getElementById('nroi-details-container');
            const nroiIdDisplay = document.getElementById('nroi_id_display');
            const restrictionMsg = document.getElementById('nroi-restriction-msg');

            if (this.value === 'yes') {
                container.style.display = 'block';
                restrictionMsg.style.display = 'none';
                document.getElementById('submitBtn').disabled = false;
                document.getElementById('submitBtn').style.opacity = '1';

                const randomNum = Math.floor(100000 + Math.random() * 900000);
                const generatedId = `${randomNum}`;
                nroiIdDisplay.value = generatedId;
                nroiIdDisplay.placeholder = generatedId;
            } else {
                container.style.display = 'none';
                restrictionMsg.style.display = 'block';
                document.getElementById('submitBtn').disabled = true;
                document.getElementById('submitBtn').style.opacity = '0.5';
            }
        });
    });

    // === Submit Handler ===
    document.getElementById('submitBtn').addEventListener('click', function (e) {
        e.preventDefault();
        if (validateStep(3)) {
            document.getElementById('confirmModal').style.display = 'flex';
        }
    });

    document.getElementById('modalCancel').addEventListener('click', function () {
        document.getElementById('confirmModal').style.display = 'none';
    });

    document.getElementById('modalConfirm').addEventListener('click', function () {
        const form = document.getElementById('regForm');
        const formData = new FormData(form);

        const addressMapping = {
            'region': 'region',
            'province': 'province',
            'city': 'city_municipality',
            'barangay': 'barangay'
        };

        Object.keys(addressMapping).forEach(id => {
            const el = document.getElementById(id);
            if (el && el.options.length > 0 && el.selectedIndex >= 0) {
                formData.set(addressMapping[id], el.options[el.selectedIndex].text);
            }
        });


        fetch('api/register.php', {
            method: 'POST',
            body: formData
        })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('confirmModal').style.display = 'none';
                    const successModal = document.getElementById('successDetailsModal');
                    document.getElementById('final-nroi-id').textContent = data.nroi_id;
                    document.getElementById('final-password').textContent = document.getElementById('password').value;
                    successModal.style.display = 'flex';
                } else {
                    alert('Error: ' + data.message);
                    document.getElementById('confirmModal').style.display = 'none';
                }
            })
            .catch(err => {
                console.error(err);
                alert('An unexpected error occurred.');
            });
    });

    document.getElementById('successOkBtn').addEventListener('click', function () {
        window.location.href = './';
    });
});
