export async function initTodayPage() {

    const today = new Date();
    document.getElementById('weekday').textContent = today.toLocaleDateString('de-DE', { weekday: 'long' });
    document.getElementById('date').textContent = today.toLocaleDateString('de-DE', { day: '2-digit', month: 'long', year: 'numeric' });

    const miniColor = getMiniColor(today);
    const miniAmount = getMiniAmount(today);

    document.getElementById('summary-color').textContent = miniColor;
    document.getElementById('summary-count').textContent = miniAmount;

    const modal = document.getElementById('task-modal');
    if (!modal) return;

    try {
        const [tasksResponse, placementsResponse] = await Promise.all([
            fetch('data/tasks.json'),
            fetch('data/placements.json')
        ]);

        const taskData = await tasksResponse.json();
        const placementData = await placementsResponse.json();

        setupTaskModal(modal, taskData);
        setupPlacementViewer(placementData);
    } catch (error) {
        console.error('Error while loading data:', error);
    }
}

function setupTaskModal(modal, taskData) {
    const modalIcon = document.getElementById('modal-icon');
    const modalTitle = document.getElementById('modal-title');
    const modalDescription = document.getElementById('modal-description');
    const modalSteps = document.getElementById('modal-steps');
    const closeBtn = modal.querySelector('.modal-close');
    const segContainer = document.getElementById('task-segmented-control');

    document.querySelectorAll('.task-card').forEach(card => {
        card.addEventListener('click', () => {
            const data = taskData[card.dataset.task];
            if (!data) return;

            modalIcon.src = data.icon;
            modalTitle.textContent = data.title;

            if (data.description) {
                modalDescription.textContent = data.description;
                modalDescription.style.display = '';
            } else {
                modalDescription.style.display = 'none';
            }

            const steps = data.steps;
            let sections = [];
            let isFlat = false;

            if (Array.isArray(steps) && steps.length > 0) {
                if (typeof steps[0] === 'object' && steps[0].steps && Array.isArray(steps[0].steps)) {
                    sections = steps;
                } else {
                    sections = [{ title: null, steps: steps }];
                    isFlat = true;
                }
            } else {
                sections = [{ title: null, steps: [] }];
                isFlat = true;
            }

            const renderSteps = (stepsArray) => {
                modalSteps.innerHTML = stepsArray.map(step => `<li>${step}</li>`).join('');
            };

            if (sections.length > 1 && !isFlat) {
                segContainer.style.display = 'flex';
                segContainer.innerHTML = '';

                sections.forEach((section, index) => {
                    const btn = document.createElement('button');
                    btn.className = 'segmented-btn' + (index === 0 ? ' active' : '');
                    btn.textContent = section.title;
                    btn.dataset.index = index;
                    btn.addEventListener('click', () => {
                        segContainer.querySelectorAll('.segmented-btn').forEach(b => b.classList.remove('active'));
                        btn.classList.add('active');
                        renderSteps(sections[index].steps);
                    });
                    segContainer.appendChild(btn);
                });

                renderSteps(sections[0].steps);
            } else {
                segContainer.style.display = 'none';
                if (sections.length === 1) {
                    renderSteps(sections[0].steps);
                } else {
                    renderSteps(steps); // Fallback
                }
            }

            modal.classList.add('active');
        });
    });

    // Schließen
    closeBtn?.addEventListener('click', () => modal.classList.remove('active'));
    modal.addEventListener('click', (e) => {
        if (e.target === modal) modal.classList.remove('active');
    });
}
function setupPlacementViewer(placementData) {
    let currentIndex = 0;
    let showIncense = false;

    const placementImage = document.getElementById('placement-image');
    const placementLabel = document.getElementById('placement-label');
    const prevBtn = document.getElementById('placement-prev');
    const nextBtn = document.getElementById('placement-next');
    const weihrauchToggle = document.getElementById('incense-toggle');
    const koerbchenLegend = document.getElementById('basket-toggle');
    const weihrauchLegend = document.getElementById('incense-legend');
    const kerzeLabel = document.getElementById('kerze-label');

    function updatePlacement() {
        const dataset = showIncense ? placementData.withWeihrauch : placementData.standard;
        const currentItem = dataset[currentIndex];

        if (!currentItem) return;

        placementImage.src = currentItem.image;
        placementLabel.textContent = currentItem.label;
        kerzeLabel.textContent = showIncense ? 'Kerze & Kollekte' : 'Kerze';

        const isEntranceWithIncense = showIncense && currentIndex === 0;
        koerbchenLegend.style.display = isEntranceWithIncense ? 'none' : '';
        weihrauchLegend.style.display = isEntranceWithIncense ? '' : 'none';
    }

    prevBtn?.addEventListener('click', () => {
        currentIndex = (currentIndex - 1 + 3) % 3;
        updatePlacement();
    });

    nextBtn?.addEventListener('click', () => {
        currentIndex = (currentIndex + 1) % 3;
        updatePlacement();
    });

    weihrauchToggle?.addEventListener('click', () => {
        showIncense = !showIncense;
        weihrauchToggle.classList.toggle('active', showIncense);
        updatePlacement();
    });

    updatePlacement();
}

function getOstern(jahr) {
    const a = jahr % 19;
    const b = jahr % 4;
    const c = jahr % 7;
    const k = Math.floor(jahr / 100);
    const p = Math.floor((13 + 8 * k) / 25);
    const q = Math.floor(k / 4);
    const M = (15 - p + k - q) % 30;
    const N = (4 + k - q) % 7;
    const d = (19 * a + M) % 30;
    const e = (2 * b + 4 * c + 6 * d + N) % 7;
    const days = 22 + d + e;

    if (days <= 31) {
        return new Date(jahr, 2, days);
    } else {
        return new Date(jahr, 3, days - 31);
    }
}

function tageDifferenz(datum1, datum2) {
    const day = 24 * 60 * 60 * 1000;
    return Math.round((datum1 - datum2) / day);
}

function getMiniColor(targetDate) {
    const year = targetDate.getFullYear();
    const easter = getOstern(year);
    const diffToEaster = tageDifferenz(targetDate, easter);

    const month = targetDate.getMonth();
    const day = targetDate.getDate();
    const wochentag = targetDate.getDay();

    if ((month === 11 && day >= 24) || (month === 0 && day <= 10)) {
        return "GRÜN";
    }

    if (diffToEaster >= -46 && diffToEaster <= -1) {
        if (diffToEaster === -7 || diffToEaster === -2) {
            return "ROT";
        }
        return "LILA";
    }

    if (diffToEaster >= 0 && diffToEaster <= 50) {
        if (diffToEaster === 50) {
            return "ROT";
        }
        return "GRÜN";
    }

    let holyEvening = new Date(year, 11, 24);
    let fourthAdvent = new Date(year, 11, 24 - holyEvening.getDay());
    let firstAdvent = new Date(fourthAdvent);
    firstAdvent.setDate(fourthAdvent.getDate() - 21);

    if (targetDate >= firstAdvent && targetDate < holyEvening) {
        return "LILA";
    }

    return "GRÜN";
}

function getMiniAmount(targetDate) {
    const amount = (targetDate.getDay() === 0 || targetDate.getDay() === 6) ? 6 : 4;

    return amount;
}