<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    <div layout:fragment="global">
        <th:block th:each="announcement : ${@announcementRepository.findActiveAnnouncements()}">
            <div
                class="banner mb-3"
                role="alert"
                th:data-announcement-id="|alert-${announcement.id}|"
                th:style="|--color: #${announcement.hexBackgroundColour()};|">
                <p th:style="|color: #${announcement.hexTextColour()};|" th:text="${announcement.message}"></p>
                <button
                    th:if="${announcement.isDismissible}"
                    class="fa-solid fa-times"
                    style="margin-left: auto; background: none; border: none; cursor: pointer"></button>
            </div>
        </th:block>

        <script type="application/javascript">
            // Initialize the dismissed announcements cookie when it does not yet exist
            if (typeof $.cookie("dismissed-announcements") === "undefined") {
                $.cookie("dismissed-announcements", "[]", { path: "/" });
            }

            // For every alert, check whether it is dismissed. If an alert is not dismissed, show it
            $(() => {
                const dismissedAnnouncements = JSON.parse($.cookie("dismissed-announcements"));
                $(".banner").each(function () {
                    const id = $(this).data("announcement-id");
                    if (dismissedAnnouncements.includes(id)) {
                        $(this).addClass("hidden");
                    }
                });
            });

            // Register an event listener that adds a dismissed announcement to the dedicated cookie
            $(".banner button").on("click", function () {
                const banner = $(this).closest(".banner");
                const id = banner.data("announcement-id");

                const dismissedAnnouncements = JSON.parse($.cookie("dismissed-announcements"));
                dismissedAnnouncements.push(id);

                $.cookie("dismissed-announcements", JSON.stringify(dismissedAnnouncements), {
                    path: "/",
                });

                banner.remove();
            });
        </script>
    </div>
</html>
