(function () {
    'use strict';

    function isDarkTheme() {
        var docEl = document.documentElement;
        var body = document.body;

        // Common theme markers used by Django admin themes / dark-mode packages
        var markers = [
            docEl && docEl.getAttribute('data-theme'),
            docEl && docEl.getAttribute('data-color-scheme'),
            body && body.getAttribute('data-theme'),
            body && body.getAttribute('data-color-scheme')
        ].filter(Boolean).join(' ').toLowerCase();

        var classNames = [
            docEl && docEl.className,
            body && body.className
        ].filter(Boolean).join(' ').toLowerCase();

        if (markers.indexOf('dark') !== -1 || classNames.indexOf('dark') !== -1) return true;

        // Fallback to OS preference
        try {
            return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
        } catch (e) {
            return false;
        }
    }

    function applyThemeToDatepickerContainers() {
        var dark = isDarkTheme();
        var containers = document.querySelectorAll('.ndp-container');
        if (!containers || !containers.length) return;

        containers.forEach(function (c) {
            c.classList.remove('ndp-dark');
            c.classList.remove('ndp-light');
            c.classList.add(dark ? 'ndp-dark' : 'ndp-light');
        });
    }

    function initNepaliDatePickers() {
        var inputs = document.querySelectorAll('.nepkit-datepicker:not(.nepali-datepicker-initialized)');
        if (!inputs || !inputs.length) return;

        inputs.forEach(function (el) {
            // Nepali Datepicker v5 exposes `element.NepaliDatePicker(options)`
            if (typeof el.NepaliDatePicker === 'function') {
                el.NepaliDatePicker({
                    dateFormat: 'YYYY-MM-DD'
                });
                el.classList.add('nepali-datepicker-initialized');

                // Ensure theme is applied when the picker is actually shown.
                // (The plugin often creates/inserts DOM on focus.)
                var applySoon = function () {
                    // Run twice: once immediately, once after paint.
                    applyThemeToDatepickerContainers();
                    window.setTimeout(applyThemeToDatepickerContainers, 0);
                };

                el.addEventListener('focus', applySoon);
                el.addEventListener('click', applySoon);
            }
        });
    }

    // Initialize on page load
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initNepaliDatePickers);
    } else {
        initNepaliDatePickers();
    }

    // Keep in sync if system theme changes (fallback path)
    if (window.matchMedia) {
        try {
            var mql = window.matchMedia('(prefers-color-scheme: dark)');
            if (mql && typeof mql.addEventListener === 'function') {
                mql.addEventListener('change', applyThemeToDatepickerContainers);
            } else if (mql && typeof mql.addListener === 'function') {
                mql.addListener(applyThemeToDatepickerContainers);
            }
        } catch (e) {
            // ignore
        }
    }

    // Re-initialize when Django admin adds inlines dynamically
    if (typeof django !== 'undefined' && django.jQuery) {
        django.jQuery(document).on('formset:added', function () {
            initNepaliDatePickers();
        });
    }

    // Also listen for DOM changes (admin popups/other dynamic content)
    if (typeof MutationObserver !== 'undefined') {
        var observer = new MutationObserver(function () {
            initNepaliDatePickers();
            applyThemeToDatepickerContainers();
        });
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }
})();
