{% load bloomerp %}

<script>
    document.addEventListener('htmx:afterSettle', function() {
        var calendarEl = document.getElementById('{{id}}');
        var calendar = new FullCalendar.Calendar(calendarEl, {
            initialView: 'dayGridMonth',
            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,listWeek'
            },
            footerToolbar: {
                left: 'prevYear,nextYear',
                right: 'dayGridDay,timeGridDay'
            },
            events: [
                {% for item in queryset %}
                {
                    title: '{{ item|escapejs }}',
                    start: '{{ item.date_start|date:parse }}', 
                    {% if item.date_end %}end: '{{ item.date_end|date:parse }}',{% endif %}
                    url: '{{ item|detail_view_url }}',
                    color: getRandomColor()
                },
                {% endfor %}
            ],
            eventDidMount: function(info) {
                updateEventCount(calendar);
            }
        });
        calendar.render();
    });

    function getRandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

    function updateEventCount(calendar) {
        var eventCount = calendar.getEvents().length;
        var eventCountButton = document.querySelector('.fc-eventCount-button');
        if (eventCountButton) {
            eventCountButton.innerText = 'Events: ' + eventCount;
        }
    }
</script>

<div id='{{id}}' class="mt-4"></div>
