# Django
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

# Third party
from cms.toolbar_base import CMSToolbar
from cms.toolbar_pool import toolbar_pool

# Project
from cookie_optin.conf.settings import ENABLE_OVERVIEW
from cookie_optin.utils import is_kapt_user


@toolbar_pool.register
class KlaroToolbar(CMSToolbar):
    """Adds a 'Statistiques' menu to the CMS toolbar that opens the consent overview modal.
    Uses a menu with position=-1 so it appears last (after Help and Language menus).
    Shown when COOKIE_OPTIN_ENABLE_OVERVIEW is True, or for Kapt users (with distinct label).
    """

    def populate(self):
        show_for_all = ENABLE_OVERVIEW
        show_for_kapt = not show_for_all and is_kapt_user(self.request.user)
        if not show_for_all and not show_for_kapt:
            return
        overview_url = reverse("cookie_optin:overview")
        visitor_url = reverse("cookie_optin:visitor_overview")
        menu_label = _("Statistiques (Kapt)") if show_for_kapt else _("Statistiques")
        klaro_menu = self.toolbar.get_or_create_menu("klaro", menu_label, position=-1)
        klaro_menu.add_modal_item(
            _("Suivi des consentements"), url=overview_url, on_close=None
        )
        klaro_menu.add_modal_item(_("Visiteurs"), url=visitor_url, on_close=None)
