(function (global) {
    'use strict';

    var $ = global.jQuery || global.$;
    if (!$) return;

    function toJalaliString(value) {
        if (!value) return '';
        if (value instanceof Date && !isNaN(value.getTime()) && global.NeoJalaliDatePicker) {
            return global.NeoJalaliDatePicker.formatJalaliDateFromGregorian(value);
        }
        return String(value);
    }

    function toGregorianStringFromJalali(jalaliValue) {
        if (!jalaliValue || !global.NeoJalaliDatePicker) return '';
        var parts = String(jalaliValue).trim().split('/');
        if (parts.length !== 3) return '';
        var jy = parseInt(parts[0], 10);
        var jm = parseInt(parts[1], 10);
        var jd = parseInt(parts[2], 10);
        if (!jy || !jm || !jd) return '';
        var g = global.NeoJalaliDatePicker.jalaliToGregorian(jy, jm, jd);
        if (!g || g.length !== 3) return '';
        var gy = String(g[0]).padStart(4, '0');
        var gm = String(g[1]).padStart(2, '0');
        var gd = String(g[2]).padStart(2, '0');
        return gy + '-' + gm + '-' + gd;
    }

    function toUnixFromJalali(jalaliValue) {
        var greg = toGregorianStringFromJalali(jalaliValue);
        if (!greg) return null;
        var d = new Date(greg + 'T00:00:00');
        if (isNaN(d.getTime())) return null;
        return d.getTime();
    }

    function syncAltField(options, jalaliValue) {
        if (!options || !options.altField) return;
        var greg = toGregorianStringFromJalali(jalaliValue);
        if (!greg) return;
        var altEl = document.querySelector(options.altField);
        if (!altEl) return;
        altEl.value = greg;
        altEl.dispatchEvent(new Event('input', { bubbles: true }));
        altEl.dispatchEvent(new Event('change', { bubbles: true }));
    }

    function createInstance(input, options) {
        if (!global.NeoJalaliDatePicker) return null;
        var state = global.NeoJalaliDatePicker.init(input, function (selectedDate) {
            syncAltField(options, selectedDate);
            if (options && typeof options.onSelect === 'function') {
                var unixDate = toUnixFromJalali(selectedDate);
                if (unixDate !== null) {
                    options.onSelect(unixDate);
                } else {
                    options.onSelect(selectedDate);
                }
            }
        }, options || {});
        if (options && options.initialValue && options.initialValue !== false) {
            input.value = toJalaliString(options.initialValue);
            syncAltField(options, input.value);
        }
        return {
            state: state,
            destroy: function () {
                if (state && typeof state.destroy === 'function') {
                    state.destroy();
                }
            },
            setDate: function (value) {
                input.value = toJalaliString(value);
                syncAltField(options, input.value);
                input.dispatchEvent(new Event('input', { bubbles: true }));
                input.dispatchEvent(new Event('change', { bubbles: true }));
            }
        };
    }

    $.fn.persianDatepicker = function (arg, value) {
        if (typeof arg === 'string') {
            if (arg === 'destroy') {
                return this.each(function () {
                    var instance = $(this).data('persianDatepicker');
                    if (instance && typeof instance.destroy === 'function') {
                        instance.destroy();
                    }
                    $(this).removeData('persianDatepicker');
                });
            }
            if (arg === 'setDate') {
                return this.each(function () {
                    var instance = $(this).data('persianDatepicker');
                    if (instance && typeof instance.setDate === 'function') {
                        instance.setDate(value);
                    } else {
                        this.value = toJalaliString(value);
                    }
                });
            }
            return this;
        }

        var options = arg || {};
        return this.each(function () {
            var instance = createInstance(this, options);
            if (instance) {
                $(this).data('persianDatepicker', instance);
            }
        });
    };
})(window);
