"""MixLift Streamlit app — entry point and page routing."""

import streamlit as st

st.set_page_config(
    page_title="MixLift — Marketing Mix Modeling",
    page_icon="chart_with_upwards_trend",
    layout="wide",
)

from frontend.api_client import is_authenticated
from frontend.auth_pages import show_auth_page
from frontend.billing import show_billing_page
from frontend.dashboard import show_dashboard
from frontend.recommendations import show_recommendations_page
from frontend.results import show_results_page
from frontend.training import show_training_page
from frontend.upload import show_upload_page

# Initialize session state
if "page" not in st.session_state:
    st.session_state["page"] = "dashboard"

# Sidebar
with st.sidebar:
    st.title("MixLift")

    if is_authenticated():
        if st.button("Dashboard"):
            st.session_state["page"] = "dashboard"
            st.rerun()

        project = st.session_state.get("current_project")
        if project:
            st.divider()
            st.subheader(project["name"])
            if st.button("Upload Data"):
                st.session_state["page"] = "upload"
                st.rerun()
            if st.button("Train Model"):
                st.session_state["page"] = "training"
                st.rerun()
            if st.button("Results"):
                st.session_state["page"] = "results"
                st.rerun()
            if st.button("Recommendations"):
                st.session_state["page"] = "recommendations"
                st.rerun()

        st.divider()
        if st.button("Upgrade Plan"):
            st.session_state["page"] = "billing"
            st.rerun()
        if st.button("Logout"):
            for key in ["access_token", "refresh_token", "current_project"]:
                st.session_state.pop(key, None)
            st.session_state["page"] = "dashboard"
            st.rerun()
    else:
        st.markdown("Login or register to get started.")

# Main content
if not is_authenticated():
    show_auth_page()
else:
    page = st.session_state.get("page", "dashboard")
    pages = {
        "dashboard": show_dashboard,
        "upload": show_upload_page,
        "training": show_training_page,
        "results": show_results_page,
        "recommendations": show_recommendations_page,
        "billing": show_billing_page,
    }
    page_fn = pages.get(page, show_dashboard)
    page_fn()
