"""
TapIN MMA - Streamlit entry point.

This module wires together:
- UI theme & disclaimer gate
- Core services (fighters, odds, events, email, scheduler)
- UI tab classes for each section of the app
"""

import streamlit as st

from config import THEMES
from services import (
    FighterService,
    OddsService,
    EventsService,
    EmailService,
    maybe_schedule_daily_mailjob,
)
from ui_tabs import (
    FighterComparisonTab,
    UpcomingEventsTab,
    BettingInfoTab,
    FightPredictorTab,
    SettingsTab,
)

# ---------------------------------------------------------
# Basic helpers
# ---------------------------------------------------------
def _safe_rerun():
    """Try both rerun APIs so it works on older/newer Streamlit versions."""
    try:
        st.rerun()
        return
    except Exception:
        pass
    try:
        st.experimental_rerun()
    except Exception:
        pass


# ---------------------------------------------------------
# Theme + page setup
# ---------------------------------------------------------
st.set_page_config(page_title="TapIN MMA", layout="wide")

if "theme" not in st.session_state:
    st.session_state["theme"] = "Dark"

if "is_admin" not in st.session_state:
    st.session_state["is_admin"] = False

if "accepted_terms" not in st.session_state:
    st.session_state["accepted_terms"] = False

palette = THEMES[st.session_state["theme"]]

st.markdown(
    f"""
    <style>
    :root {{
        --bg: {palette['--bg']};
        --text: {palette['--text']};
        --card: {palette['--card']};
        --accent: {palette['--accent']};
    }}
    .stApp {{ background-color: var(--bg); color: var(--text); }}
    .stButton>button {{
        background: var(--accent)!important;
        color:#fff!important;
        border-radius:12px;
    }}
    .stSelectbox, .stTextInput, .stTextArea, .stDataFrame, .stExpander {{
        background: var(--card)!important;
        border-radius:14px;
    }}
    .block-container {{ padding-top: 1.2rem; }}
    </style>
    """,
    unsafe_allow_html=True,
)

st.markdown("<h1 style='text-align:center;'> TapIN MMA</h1>", unsafe_allow_html=True)

# ---------------------------------------------------------
# Legal disclaimer gate
# ---------------------------------------------------------
def render_disclaimer_gate():
    st.markdown("## Important Notice")
    st.write(
        "TapIN MMA provides fight statistics, odds information, and experimental predictions "
        "for **entertainment and educational purposes only**. "
        "Nothing in this app is financial, betting, or gambling advice."
    )
    st.write(
        "By continuing, you confirm that:\n"
        "- You are of legal age to view sports betting information in your jurisdiction.\n"
        "- You are solely responsible for any decisions you make.\n"
        "- TapIN MMA and its creators are **not liable** for any losses or consequences "
        "related to betting or gambling."
    )
    agree = st.checkbox("I have read and agree to these terms.")
    if st.button("Enter TapIN MMA"):
        if agree:
            st.session_state["accepted_terms"] = True
            _safe_rerun()
        else:
            st.error("You must check the box to continue.")


if not st.session_state["accepted_terms"]:
    render_disclaimer_gate()
    st.stop()

# ---------------------------------------------------------
# Services + scheduler
# ---------------------------------------------------------
fighter_service = FighterService()
odds_service = OddsService()
events_service = EventsService()
email_service = EmailService()

maybe_schedule_daily_mailjob(events_service, email_service)

# ---------------------------------------------------------
# Tabs + UI classes
# ---------------------------------------------------------
tabs = st.tabs(
    [
        "Fighter Comparison",
        "Upcoming Events",
        "Betting Info",
        "Fight Predictor",
        "Settings",
    ]
)

fighter_tab = FighterComparisonTab(fighter_service)
upcoming_tab = UpcomingEventsTab(events_service, email_service)
betting_tab = BettingInfoTab(odds_service)
predictor_tab = FightPredictorTab(fighter_service)
settings_tab = SettingsTab(_safe_rerun)

fighter_tab.render(tabs[0])
upcoming_tab.render(tabs[1])
betting_tab.render(tabs[2])
predictor_tab.render(tabs[3])
settings_tab.render(tabs[4])
