import streamlit as st
from components.connexion import connexion, bouton_deconnexion
import streamlit.components.v1 as components
from utils.translations import _
from utils.persistance import get_champ_statut, maj_champ_statut

def afficher_menu():
    with st.sidebar:
        st.markdown(f"""
            <nav role="navigation" aria-label="{str(_('sidebar.menu'))}">
                <div role="region" aria-label="{str(_('sidebar.navigation'))}" class="onglets-accessibles">
        """, unsafe_allow_html=True)

        # Définir la variable instructions_text une seule fois en haut de la fonction
        instructions_text = str(_("navigation.instructions"))
        navigation_onglet = get_champ_statut("navigation_onglet")
        if navigation_onglet == "":
            navigation_onglet = instructions_text
            maj_champ_statut("navigation_onglet", navigation_onglet)

        onglet_choisi = None
        onglets = [
            str(_("navigation.instructions")),
            str(_("navigation.personnalisation")),
            str(_("navigation.analyse")),
            *([str(_("navigation.ia_nalyse"))] if not get_champ_statut("login") == "" else []),
            *([str(_("navigation.plan_d_action"))]),
            str(_("navigation.visualisations")),
            str(_("navigation.fiches"))
        ]

        for nom in onglets:
            if navigation_onglet == nom:
                st.markdown(f'<div class="bouton-fictif">{nom}</div>', unsafe_allow_html=True)
            else:
                if st.button(str(nom)):
                    onglet_choisi = nom

        st.markdown("""
                    <hr />
                </div>
            </nav>""", unsafe_allow_html=True)

        # === GESTION DU THÈME ===
        #
        # Le changement de thème induit un st.rerun qui vide les formula
        # Pour éviter de perdre les informations dans les formulaires,
        # le changement de thème n'est proposé que si l'utilisateur est sur l'onglet "Instructions"
        #
        #
        theme_mode = get_champ_statut("theme_mode")
        if theme_mode == "":
            theme_mode = str(_("sidebar.theme_light"))
            maj_champ_statut("theme_mode", theme_mode)

        theme_title = str(_("sidebar.theme"))
        st.markdown(f"""
            <section role="region" aria-label="region-theme">
                <div role="region" aria-labelledby="Theme">
                    <p id="Theme" class="decorative-heading">{theme_title}</p>
        """, unsafe_allow_html=True)

        theme_options = [
            str(_("sidebar.theme_light")),
            str(_("sidebar.theme_dark"))
        ]
        theme = st.radio(
            str(_("sidebar.theme")),
            theme_options,
            index=theme_options.index(theme_mode),
            horizontal=True,
            label_visibility="hidden"
        )
        maj_champ_statut("theme_mode", theme)

        st.markdown("""
                    <hr />
                </div>
            </nav>""", unsafe_allow_html=True)

        connexion()

        if not get_champ_statut("login") == "":
            bouton_deconnexion()

        # === RERUN SI BESOIN ===
        if (onglet_choisi and onglet_choisi != navigation_onglet) or (theme != theme_mode):
            if onglet_choisi:  # Ne met à jour que si on a cliqué
                maj_champ_statut("navigation_onglet", onglet_choisi)
            maj_champ_statut("theme_mode", theme)
            st.rerun()

#
# Important :
# Avec Selinux, il faut donner les bons droits
#
# sudo chcon -Rt httpd_sys_content_t /chemin/d/acces/assets/
#
def afficher_impact(total_bytes):
    impact_label = str(_("sidebar.impact"))
    loading_text = str(_("sidebar.loading"))

    with st.sidebar:
        components.html(f"""
    <html lang="fr">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Impact Environnemental</title>
            <style>
                body,
                html {{
                    font-family:
                        -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial,
                        sans-serif;
                }}
                /* Div réseau pour impact CO₂ */
                #network-usage {{
                    display: block;
                    font-size: small;
                    margin-top: 1rem;
                    text-align: center;
                }}
                .decorative-heading {{
                    font-size: 1.25rem;
                    font-weight: bold;
                    margin-bottom: 0.5rem;
                    color: #072c6e;
                    text-align: center;
                }}
                span {{
                    text-align: center;
                }}
            </style>
        </head>
        <body>
            <hr />
            <div role="region" aria-label="{impact_label}" class="impact-environnement">
                <p class="decorative-heading">{impact_label}</p>
                <p><span id="network-usage">{loading_text}</span></p>
            </div>

            <script>
            document.addEventListener("DOMContentLoaded", async function() {{
                try {{
                    const module = await import("/assets/impact_co2.js");
                    module.calculerImpactCO2({total_bytes});
                }} catch (error) {{
                    console.error("Erreur module impact_co2.js", error);
                }}
            }});
            </script>
        </body>
    </html>
        """)
        st.markdown("""
            <div style="text-align: center;">
                <img src="https://app.greenweb.org/api/v3/greencheckimage/fabnum-dev.peccini.fr?nocache=true" alt="This website runs on green hosting - verified by thegreenwebfoundation.org" width="200px" height="95px">
            </div>
            """, unsafe_allow_html=True)
