/**
 * تقویم شمسی سبک - بدون وابستگی خارجی
 * روی هر input با کلاس jalali-date-input فعال می‌شود.
 * data-allow-future="1" روی input یعنی انتخاب تاریخ آینده مجاز است (پیش‌فرض غیرمجاز).
 */
(function () {
    function div(a, b) { return Math.floor(a / b); }

    function gtoj(gy, gm, gd) {
        var g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
        var jy = (gy <= 1600) ? 0 : 979;
        gy -= (gy <= 1600) ? 621 : 1600;
        var gy2 = (gm > 2) ? (gy + 1) : gy;
        var days = (365 * gy) + div((gy2 + 3), 4) - div((gy2 + 99), 100) + div((gy2 + 399), 400) - 80 + gd + g_d_m[gm - 1];
        jy += 33 * div(days, 12053);
        days %= 12053;
        jy += 4 * div(days, 1461);
        days %= 1461;
        if (days > 365) {
            jy += div((days - 1), 365);
            days = (days - 1) % 365;
        }
        var jm, jd;
        if (days < 186) {
            jm = 1 + div(days, 31);
            jd = 1 + (days % 31);
        } else {
            jm = 7 + div((days - 186), 30);
            jd = 1 + ((days - 186) % 30);
        }
        return [jy, jm, jd];
    }

    function jtog(jy, jm, jd) {
        jy += 1595;
        var days = -355668 + (365 * jy) + (div(jy, 33) * 8) + div(((jy % 33) + 3), 4) + jd + ((jm < 7) ? (jm - 1) * 31 : ((jm - 7) * 30) + 186);
        var gy = 400 * div(days, 146097);
        days %= 146097;
        if (days > 36524) {
            days -= 1;
            gy += 100 * div(days, 36524);
            days %= 36524;
            if (days >= 365) days += 1;
        }
        gy += 4 * div(days, 1461);
        days %= 1461;
        if (days > 365) {
            gy += div((days - 1), 365);
            days = (days - 1) % 365;
        }
        var gd = days + 1;
        var leap = (gy % 4 === 0 && gy % 100 !== 0) || gy % 400 === 0;
        var g_days_in_month = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        var gm = 0;
        for (var i = 0; i < 12; i++) {
            if (gd <= g_days_in_month[i]) { gm = i + 1; break; }
            gd -= g_days_in_month[i];
        }
        return [gy, gm, gd];
    }

    function isLeapJalali(jy) {
        var g = jtog(jy, 12, 30);
        var back = gtoj(g[0], g[1], g[2]);
        return back[1] === 12 && back[2] === 30;
    }

    function jalaliMonthLength(jy, jm) {
        if (jm <= 6) return 31;
        if (jm <= 11) return 30;
        return isLeapJalali(jy) ? 30 : 29;
    }

    function todayJalali() {
        var now = new Date();
        return gtoj(now.getFullYear(), now.getMonth() + 1, now.getDate());
    }

    var MONTH_NAMES = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'];
    var WEEKDAYS = ['ش', 'ی', 'د', 'س', 'چ', 'پ', 'ج'];

    function buildPopup(input) {
        var allowFuture = input.dataset.allowFuture === '1';
        var today = todayJalali();

        var initial = today.slice();
        var m = input.value.match(/^(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})$/);
        if (m) {
            initial = [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)];
        }

        var pop = document.createElement('div');
        pop.className = 'jalali-datepicker-popup';
        pop.style.cssText = 'position:absolute; z-index:2000; background:#fff; border:1px solid #ccc; border-radius:8px; box-shadow:0 4px 16px rgba(0,0,0,0.15); padding:10px; width:300px; font-family:inherit;';

        var viewYear = initial[0], viewMonth = initial[1];

        function render() {
            pop.innerHTML = '';

            var header = document.createElement('div');
            header.style.cssText = 'display:flex; justify-content:space-between; align-items:center; margin-bottom:8px; gap:4px;';

            var prevBtn = document.createElement('button');
            prevBtn.type = 'button';
            prevBtn.textContent = '‹';
            prevBtn.className = 'btn btn-sm btn-light';
            prevBtn.onclick = function () {
                viewMonth--;
                if (viewMonth < 1) { viewMonth = 12; viewYear--; }
                render();
            };

            var nextBtn = document.createElement('button');
            nextBtn.type = 'button';
            nextBtn.textContent = '›';
            nextBtn.className = 'btn btn-sm btn-light';
            nextBtn.onclick = function () {
                viewMonth++;
                if (viewMonth > 12) { viewMonth = 1; viewYear++; }
                render();
            };

            var monthSelect = document.createElement('select');
            monthSelect.className = 'form-select form-select-sm';
            monthSelect.style.cssText = 'width:auto; max-width:110px; display:inline-block; font-size:12px;';
            MONTH_NAMES.forEach(function (name, idx) {
                var opt = document.createElement('option');
                opt.value = idx + 1;
                opt.textContent = name;
                if (idx + 1 === viewMonth) opt.selected = true;
                monthSelect.appendChild(opt);
            });
            monthSelect.onchange = function () {
                viewMonth = parseInt(monthSelect.value, 10);
                render();
            };

            var yearSelect = document.createElement('select');
            yearSelect.className = 'form-select form-select-sm';
            yearSelect.style.cssText = 'width:auto; max-width:80px; display:inline-block; font-size:12px;';
            var minYear = today[0] - 100;
            var maxYear = allowFuture ? (today[0] + 10) : today[0];
            for (var y = maxYear; y >= minYear; y--) {
                var yopt = document.createElement('option');
                yopt.value = y;
                yopt.textContent = y;
                if (y === viewYear) yopt.selected = true;
                yearSelect.appendChild(yopt);
            }
            yearSelect.onchange = function () {
                viewYear = parseInt(yearSelect.value, 10);
                render();
            };

            var selects = document.createElement('div');
            selects.style.cssText = 'display:flex; gap:4px;';
            selects.appendChild(yearSelect);
            selects.appendChild(monthSelect);

            header.appendChild(nextBtn);
            header.appendChild(selects);
            header.appendChild(prevBtn);
            pop.appendChild(header);

            var grid = document.createElement('div');
            grid.style.cssText = 'display:grid; grid-template-columns:repeat(7,1fr); gap:2px; text-align:center;';

            WEEKDAYS.forEach(function (w) {
                var cell = document.createElement('div');
                cell.textContent = w;
                cell.style.cssText = 'font-size:11px; color:#888; padding:4px 0;';
                grid.appendChild(cell);
            });

            // تعیین روز هفته اول ماه (شنبه=0)
            var gFirst = jtog(viewYear, viewMonth, 1);
            var jsDate = new Date(gFirst[0], gFirst[1] - 1, gFirst[2]);
            var jsDay = jsDate.getDay(); // یکشنبه=0 در جاوااسکریپت
            var startOffset = (jsDay + 1) % 7; // تبدیل به شنبه=0

            for (var i = 0; i < startOffset; i++) {
                grid.appendChild(document.createElement('div'));
            }

            var len = jalaliMonthLength(viewYear, viewMonth);
            for (var d = 1; d <= len; d++) {
                (function (day) {
                    var cell = document.createElement('button');
                    cell.type = 'button';
                    cell.textContent = day;
                    var isFuture = !allowFuture && (
                        viewYear > today[0] ||
                        (viewYear === today[0] && viewMonth > today[1]) ||
                        (viewYear === today[0] && viewMonth === today[1] && day > today[2])
                    );
                    var isToday = (viewYear === today[0] && viewMonth === today[1] && day === today[2]);
                    var isSelected = (viewYear === initial[0] && viewMonth === initial[1] && day === initial[2]);

                    cell.style.cssText = 'border:none; border-radius:4px; padding:6px 0; font-size:13px; cursor:pointer; background:' +
                        (isSelected ? '#0d6efd' : (isToday ? '#e7f1ff' : 'transparent')) +
                        '; color:' + (isSelected ? '#fff' : (isFuture ? '#ccc' : '#212529')) + ';';

                    if (isFuture) {
                        cell.disabled = true;
                    } else {
                        cell.onclick = function () {
                            var jyStr = viewYear.toString().padStart(4, '0');
                            var jmStr = viewMonth.toString().padStart(2, '0');
                            var jdStr = day.toString().padStart(2, '0');
                            input.value = jyStr + '/' + jmStr + '/' + jdStr;
                            input.classList.remove('is-invalid');
                            closePopup();
                            input.dispatchEvent(new Event('change'));
                        };
                    }
                    grid.appendChild(cell);
                })(d);
            }

            pop.appendChild(grid);

            var todayBtn = document.createElement('button');
            todayBtn.type = 'button';
            todayBtn.textContent = 'امروز';
            todayBtn.className = 'btn btn-sm btn-outline-secondary w-100 mt-2';
            todayBtn.onclick = function () {
                var jyStr = today[0].toString().padStart(4, '0');
                var jmStr = today[1].toString().padStart(2, '0');
                var jdStr = today[2].toString().padStart(2, '0');
                input.value = jyStr + '/' + jmStr + '/' + jdStr;
                input.classList.remove('is-invalid');
                closePopup();
                input.dispatchEvent(new Event('change'));
            };
            pop.appendChild(todayBtn);
        }

        render();
        return pop;
    }

    var activePopup = null;

    function closePopup() {
        if (activePopup && activePopup.parentNode) {
            activePopup.parentNode.removeChild(activePopup);
        }
        activePopup = null;
    }

    function openPopup(input) {
        closePopup();
        var pop = buildPopup(input);
        document.body.appendChild(pop);
        var rect = input.getBoundingClientRect();
        pop.style.top = (window.scrollY + rect.bottom + 4) + 'px';
        pop.style.left = (window.scrollX + rect.left) + 'px';
        activePopup = pop;

        setTimeout(function () {
            document.addEventListener('click', outsideClickHandler);
        }, 0);
    }

    function outsideClickHandler(e) {
        if (activePopup && !activePopup.contains(e.target) && !e.target.classList.contains('jalali-date-input')) {
            closePopup();
            document.removeEventListener('click', outsideClickHandler);
        }
    }

    function initInput(input) {
        if (input.dataset.jalaliInit) return;
        input.dataset.jalaliInit = '1';
        input.setAttribute('readonly', 'readonly');
        input.style.backgroundColor = '#fff';
        input.style.cursor = 'pointer';
        input.addEventListener('click', function () { openPopup(input); });
        input.addEventListener('focus', function () { openPopup(input); });
    }

    function initAll() {
        document.querySelectorAll('.jalali-date-input').forEach(initInput);
    }

    document.addEventListener('DOMContentLoaded', initAll);
    // برای فرم‌هایی که بعداً به‌صورت پویا فیلد اضافه می‌کنند
    window.initJalaliDatePickers = initAll;
})();
