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


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"))
        if "onglet" not in st.session_state:
            st.session_state.onglet = instructions_text

        onglet_choisi = None
        onglets = [
            str(_("navigation.instructions")),
            str(_("navigation.personnalisation")),
            str(_("navigation.analyse")),
            str(_("navigation.visualisations")),
            str(_("navigation.fiches"))
        ]

        for nom in onglets:
            if st.session_state.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"
        #
        if st.session_state.onglet == instructions_text:
            if "theme_mode" not in st.session_state:
                st.session_state.theme_mode = str(_("sidebar.theme_light"))

            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(st.session_state.theme_mode),
                horizontal=True,
                label_visibility="hidden"
            )

            st.markdown("""
                        <hr />
                    </div>
                </nav>""", unsafe_allow_html=True)
        else :
            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)

            st.info(str(_("sidebar.theme_instructions_only")))

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

            theme = st.session_state.theme_mode

        connexion()

        if st.session_state.get("logged_in", False):
            bouton_deconnexion()

        # === RERUN SI BESOIN ===
        if (onglet_choisi and onglet_choisi != st.session_state.onglet) or (theme != st.session_state.theme_mode):
            if onglet_choisi:  # Ne met à jour que si on a cliqué
                st.session_state.onglet = onglet_choisi
            st.session_state.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: #145a1a;
                    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)
