(function (window, document) {
    'use strict';

    function pad2(n) {
        return n < 10 ? '0' + n : String(n);
    }

    function ymdToDisplay(ymd) {
        if (!ymd || typeof ymd !== 'string') {
            return '';
        }
        var parts = ymd.split('-');
        if (parts.length !== 3) {
            return ymd;
        }
        return parts[0] + '/' + pad2(parseInt(parts[1], 10)) + '/' + pad2(parseInt(parts[2], 10));
    }

    function displayToYmd(value) {
        var raw = String(value || '').trim();
        if (raw === '') {
            return '';
        }
        var m = raw.match(/^(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})/);
        if (!m) {
            return raw;
        }
        return m[1] + '-' + pad2(parseInt(m[2], 10)) + '-' + pad2(parseInt(m[3], 10));
    }

    function resetDateInput(input) {
        if (!input) {
            return;
        }
        if (input.__zertiJalaliPicker && typeof input.__zertiJalaliPicker.close === 'function') {
            input.__zertiJalaliPicker.close();
        }
        if (input.__zertiHijriPicker && typeof input.__zertiHijriPicker.close === 'function') {
            input.__zertiHijriPicker.close();
        }
        input.__zertiJalaliPicker = null;
        input.__zertiHijriPicker = null;
        input.removeAttribute('data-zerti-jalali-bound');
        input.removeAttribute('data-zerti-hijri-bound');
        input.removeAttribute('data-zerti-gregorian-bound');
        var hiddenPicker = input.parentNode
            ? input.parentNode.querySelector('input[type="date"][aria-hidden="true"]')
            : null;
        if (hiddenPicker && hiddenPicker !== input) {
            hiddenPicker.remove();
        }
    }

    function bindGregorianInput(input) {
        if (!input || input.getAttribute('data-zerti-gregorian-bound') === '1') {
            return;
        }
        if (input.type === 'date') {
            input.setAttribute('data-zerti-gregorian-bound', '1');
            return;
        }
        input.setAttribute('data-zerti-gregorian-bound', '1');

        var picker = document.createElement('input');
        picker.type = 'date';
        picker.className = 'visually-hidden';
        picker.setAttribute('tabindex', '-1');
        picker.setAttribute('aria-hidden', 'true');
        if (input.parentNode) {
            input.parentNode.appendChild(picker);
        }

        if (input.value) {
            picker.value = displayToYmd(input.value);
        }

        input.addEventListener('focus', function () {
            if (input.readOnly || input.disabled) {
                return;
            }
            if (input.value) {
                picker.value = displayToYmd(input.value);
            }
            if (typeof picker.showPicker === 'function') {
                try {
                    picker.showPicker();
                    return;
                } catch (errShow) {}
            }
            picker.click();
        });

        input.addEventListener('click', function (e) {
            if (input.readOnly || input.disabled) {
                return;
            }
            e.preventDefault();
            input.focus();
        });

        picker.addEventListener('change', function () {
            input.value = ymdToDisplay(picker.value);
            input.dispatchEvent(new Event('input', { bubbles: true }));
            input.dispatchEvent(new Event('change', { bubbles: true }));
        });
    }

    window.zertiInitGregorianDatepickers = function (root) {
        var admin = document.getElementById('zertiAdmin');
        if (!admin) {
            return;
        }
        var searchRoot = root && root.querySelectorAll && root !== document ? root : admin;
        if (!searchRoot.querySelectorAll) {
            return;
        }
        searchRoot
            .querySelectorAll('[data-zerti-date]:not([data-zerti-jalali-date]):not([data-zerti-hijri-date]), [data-zerti-gregorian-date], .zerti-admin-date-input[type="date"]')
            .forEach(function (input) {
                resetDateInput(input);
                bindGregorianInput(input);
            });
    };

    window.zertiResetAdminDateInputs = function (root) {
        var admin = document.getElementById('zertiAdmin');
        if (!admin) {
            return;
        }
        var searchRoot = root && root.querySelectorAll && root !== document ? root : admin;
        if (!searchRoot.querySelectorAll) {
            return;
        }
        searchRoot
            .querySelectorAll('[data-zerti-date], [data-zerti-jalali-date], [data-zerti-hijri-date], [data-zerti-gregorian-date], .zerti-admin-date-input')
            .forEach(resetDateInput);
    };
})(window, document);
