(function () {
    'use strict';

    function ageFromBirthYear(birthYear, currentYear) {
        if (!birthYear || birthYear <= 0) {
            return null;
        }
        var age = currentYear - birthYear;
        if (age < 0 || age > 120) {
            return null;
        }
        return age;
    }

    function updateAgePreview(select, currentYear) {
        var previewId = select.getAttribute('data-age-preview');
        if (!previewId) {
            return;
        }
        var preview = document.getElementById(previewId);
        if (!preview) {
            return;
        }
        var raw = select.value;
        if (raw === '' || raw === 'none') {
            preview.textContent = '';
            return;
        }
        var year = parseInt(raw, 10);
        if (!Number.isFinite(year)) {
            preview.textContent = '';
            return;
        }
        var age = ageFromBirthYear(year, currentYear);
        preview.textContent = age !== null ? ('約 ' + age + ' 歲') : '';
    }

    function bindProfileStatsForm(root) {
        var currentYear = parseInt(root.getAttribute('data-current-year') || String(new Date().getFullYear()), 10);
        root.querySelectorAll('[data-masseur-birth-year]').forEach(function (select) {
            updateAgePreview(select, currentYear);
            select.addEventListener('change', function () {
                updateAgePreview(select, currentYear);
            });
        });
    }

    function initAll() {
        document.querySelectorAll('[data-masseur-profile-stats-form]').forEach(bindProfileStatsForm);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initAll);
    } else {
        initAll();
    }

    window.fateInitMasseurProfileStatsAgePreview = bindProfileStatsForm;
})();
