/******************************************************************************
 * Copyright (c) 2024, 2025 Contributors to the Eclipse Foundation
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the terms
 * of the MIT License which is available at https://opensource.org/licenses/MIT
 *
 *  SPDX-License-Identifier: MIT
 *****************************************************************************/

let ESCET_DEBUG_NEWS= false;

async function initNews() {
    // Nothing to do if this page is not the news page and does not contain news teasers.
    var isTeaser;
    if (document.getElementById('news') !== null) {
        isTeaser = false;
    } else if (document.getElementById('news-teasers') !== null) {
        isTeaser = true;
    } else {
        return;
    }

    // Get news data.
    var newsData = null;
    if (ESCET_DEBUG_NEWS) {
        // Delay a bit to simulate that loading the news taking some time.
        await new Promise(resolve => setTimeout(resolve, 1000));

        // Set up news data, with tags.
        newsData = {
            'tags': {
                'community': {
                    'background': 'rgba(13,110,253,.2)',
                    'text': '#666'
                },
                'event': {
                    'background': 'rgba(220,53,69,.2)',
                    'text': '#666'
                },
                'project': {
                    'background': 'rgba(25,135,84,.2)',
                    'text': '#666'
                },
                'release': {
                    'background': 'rgba(255,193,7,.25)',
                    'text': '#666'
                }
            },
            'items': []
        };

        // Add some dummy news items.
        for (let i = 0; i < 20; i++) {
            const date = new Date();
            date.setDate(date.getDate() -i);
            newsData['items'].push({
                'title': `<em>News</em> item ${i + 1}`,
                'message': 'This is a <em>news message</em> with some text that describes the news.',
                'date': date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(),
                'tag': (i % 4 == 0) ? 'community' : (i % 4 == 1) ? 'event' : (i % 4 == 2) ? 'project' : 'release',
            });
        }
    } else {
        // Get the news data from the nightly release. All versions of the website take the news from there, to ensure
        // that they always show the latest news.
        //
        // We access the news data file by date, to get the current version of the news data, regardless of server
        // 'max-age' headers and browser caching. Since only minutes are included in the URL postfix, and not seconds,
        // this should still cache for a minute.
        const date = new Date();
        const postfix = '?v=' + date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + '--'
                              + date.getHours() + '-' + date.getMinutes();
        const url = '/escet/nightly/_shared/news.json' + postfix;
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
            },
        });
        if (!response.ok) {
            throw new Error(`Failed to load news: ${response.status}.`);
        }
        newsData = await response.json();
    }

    // For teasers, display only the latest three news items.
    if (isTeaser) {
        newsData['items'].splice(3);
    }

    // Add news items.
    const newsItemsElem = document.getElementById('news-items');
    for (const newsItem of newsData['items']) {
        // Get information from the news item.
        const title = newsItem['title'].trim();
        const message = newsItem['message'].trim();
        const dateText = newsItem['date'].trim();
        const dateParts = dateText.split('-');
        const date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
        const dateFormatted = date.toLocaleDateString('en-US', {year: 'numeric', month: 'long', day: 'numeric'});
        const tag = newsItem['tag'].trim();
        const tagBgColor = newsData['tags'][tag]['background'];
        const tagTextColor = newsData['tags'][tag]['text'];

        // Add the appropriate HTML elements for the full news item for the teaser.
        if (isTeaser) {
            // Create the table row.
            const rowElem = document.createElement('tr');
            rowElem.classList.add('align-top');

            // Add tag cell.
            const tagCellElem = document.createElement('td');
            tagCellElem.classList.add('pe-2');
            tagCellElem.classList.add('pe-md-3');
            tagCellElem.classList.add('text-nowrap');
            rowElem.appendChild(tagCellElem);

            const tagSpanElem = document.createElement('span');
            tagSpanElem.classList.add('badge');
            tagSpanElem.classList.add('rounded-pill');
            tagSpanElem.style.backgroundColor = tagBgColor;
            tagSpanElem.style.color = tagTextColor;
            tagSpanElem.innerHTML = tag;
            tagCellElem.appendChild(tagSpanElem);

            // Add date cell.
            const dateCellElem = document.createElement('td');
            dateCellElem.classList.add('pe-2');
            dateCellElem.classList.add('pe-md-3');
            dateCellElem.classList.add('text-nowrap');
            rowElem.appendChild(dateCellElem);

            const dateSpanElem = document.createElement('span');
            dateSpanElem.classList.add('text-muted');
            dateSpanElem.classList.add('fst-italic');
            dateSpanElem.innerHTML = dateFormatted;
            dateCellElem.appendChild(dateSpanElem);

            // Get news page URL.
            var newsPageUrl = 'news.html';
            for (var level = 0; level < newsItemsElem.dataset.pageLevel; level++) {
                newsPageUrl = '../' + newsPageUrl;
            }

            // Add title cell.
            const titleCellElem = document.createElement('td');
            rowElem.appendChild(titleCellElem);

            const titleAElem = document.createElement('a');
            titleAElem.classList.add('text-decoration-none');
            titleAElem.classList.add('text-reset');
            titleAElem.innerHTML = title;
            titleAElem.href = newsPageUrl;
            titleCellElem.appendChild(titleAElem);

            // Add the row to the table.
            newsItemsElem.appendChild(rowElem);
        } else {
            // Create the card.
            const cardElem = document.createElement('div');
            cardElem.classList.add('news-item');
            cardElem.classList.add('card');
            cardElem.classList.add('shadow-sm');
            cardElem.classList.add('mb-4');

            // Add the body.
            const cardBodyElem = document.createElement('div');
            cardBodyElem.classList.add('card-body');
            cardElem.appendChild(cardBodyElem);

            // Add the title.
            const cardTitleElem = document.createElement('h5');
            cardTitleElem.classList.add('card-title');
            cardTitleElem.innerHTML = title;
            cardBodyElem.appendChild(cardTitleElem);

            // Add the news message.
            const cardMessageElem = document.createElement('p');
            cardMessageElem.classList.add('card-text');
            cardMessageElem.innerHTML = message;
            cardBodyElem.appendChild(cardMessageElem);

            // Add the footer.
            const cardFooterElem = document.createElement('div');
            cardFooterElem.classList.add('news-item-footer');
            cardBodyElem.appendChild(cardFooterElem);

            // Add the tag.
            const tagElem = document.createElement('span');
            tagElem.classList.add('badge');
            tagElem.classList.add('rounded-pill');
            tagElem.classList.add('me-3');
            tagElem.style.backgroundColor = tagBgColor;
            tagElem.style.color = tagTextColor;
            tagElem.innerHTML = tag;
            cardFooterElem.appendChild(tagElem);

            // Add the date of the news item.
            const cardDateElem = document.createElement('span');
            cardDateElem.classList.add('text-muted');
            cardDateElem.classList.add('fst-italic');
            cardDateElem.innerHTML = dateFormatted;
            cardFooterElem.appendChild(cardDateElem);

            // Add the card to the page.
            newsItemsElem.appendChild(cardElem);
        }
    }

    // Remove placeholder news items.
    const placeholderElems = Array.from(document.getElementsByClassName('placeholder-news-item'));
    for (const placeholderElem of placeholderElems) {
        placeholderElem.remove();
    }
}

initNews();
