<script>
    (function() {
        'use strict';

        /** Strip invalid keys only — do not round or clamp while typing (so 8. / 7.35 works). */
        function stripInvalidImdbChars(el) {
            var v = String(el.value).replace(/[^0-9.]/g, '');
            var d = v.indexOf('.');
            if (d !== -1) {
                v = v.slice(0, d + 1) + v.slice(d + 1).replace(/\./g, '');
            }
            el.value = v;
        }

        /** Clamp 0–10, round to one decimal; show whole numbers without “.0”. */
        function finalizeImdbValue(el) {
            var raw = String(el.value).trim();
            if (raw === '' || raw === '.') {
                el.value = '';
                return;
            }
            var n = parseFloat(raw.replace(/[^0-9.]/g, ''));
            if (isNaN(n)) {
                el.value = '';
                return;
            }
            n = Math.min(10, Math.max(0, Math.round(n * 10) / 10));
            if (Math.abs(n - Math.round(n)) < 1e-9) {
                el.value = String(Math.round(n));
            } else {
                el.value = n.toFixed(1);
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            var el = document.getElementById('imdb_rating');
            if (!el) {
                return;
            }
            el.addEventListener('input', function() {
                stripInvalidImdbChars(el);
            });
            el.addEventListener('blur', function() {
                finalizeImdbValue(el);
            });
            var form = el.closest('form');
            if (form) {
                form.addEventListener('submit', function() {
                    finalizeImdbValue(el);
                });
            }
        });
    })();
</script>
