def user_palette(request):
    if request.user.is_authenticated:
        return {"user_palette": request.user.palette}
    return {"user_palette": "palette-default"}


def mail_brief_payload(request):
    """Inject the user's oldest unread @mailman "Acceptances & rejections"
    Brief into every authenticated response context — bud landing page
    sprint 2026-05-27 ([[project-bud-landing-page-sprint]]). The base
    template renders the payload as a JSON script + auto-fires
    Brief.showBanner so the slide-down notification surfaces on the next
    page load regardless of where the invitee lands.

    Marked read by `view_post`'s existing unread-flip on GET of the
    underlying MAIL_ACCEPTANCE Post — same mark-read contract every other
    Brief kind already uses."""
    if not request.user.is_authenticated:
        return {}
    from apps.billboard.models import Brief
    brief = (
        Brief.objects
        .filter(
            owner=request.user,
            kind=Brief.KIND_MAIL_ACCEPTANCE,
            is_unread=True,
        )
        .order_by("created_at")
        .first()
    )
    if brief is None:
        return {}
    return {"mail_brief_payload": brief.to_banner_dict()}


def navbar_context(request):
    if not request.user.is_authenticated:
        return {}
    from django.db.models import Max, Q
    from django.urls import reverse
    from apps.epic.models import Room

    recent_room = (
        Room.objects.filter(
            Q(owner=request.user) | Q(gate_slots__gamer=request.user)
        )
        .annotate(last_event=Max("events__timestamp"))
        .filter(last_event__isnull=False)
        .order_by("-last_event")
        .distinct()
        .first()
    )
    if recent_room is None:
        return {}
    if recent_room.table_status:
        url = reverse("epic:room", args=[recent_room.id])
    else:
        url = reverse("epic:gatekeeper", args=[recent_room.id])
    return {"navbar_recent_room_url": url}