"""
Frontend module for the Market Dashboard.

Uses Streamlit to display market data in a web dashboard.
All data fetching is handled by the backend module.
"""

import streamlit as st

from backend.backend_app import get_daily_changes, get_ticker_name
from data.tickers import (
    TICKERS_Main,
    TICKERS_Ai,
    TICKERS_Forex,
    TICKER_CURRENCIES,
    SIGNIFICANT_CHANGE,
)


def display_summary(title: str, closing_prices, daily_changes: dict) -> None:
    """
    Displays a market summary section in the Streamlit application.

    Args:
        title (str):
            Section title.
        closing_prices:
            DataFrame of closing prices.
        daily_changes (dict):
            Dictionary of ticker → percentage change.
    """
    st.subheader(title)

    significant_changes = 0
    columns = st.columns(3)
    container = st.container(border=True)

    with container:
        for index, (ticker, percentage_change) in enumerate(
            daily_changes.items()
        ):
            if index % 3 == 0:
                columns = st.columns(3)
            column = columns[index % 3]

            latest_price = closing_prices[ticker].dropna().iloc[-1]
            highest_price = closing_prices[ticker].dropna().max()
            currency = TICKER_CURRENCIES.get(ticker, "")

            if abs(percentage_change) >= SIGNIFICANT_CHANGE:
                significant_changes += 1

            with column:
                st.metric(
                    label=ticker,
                    value=f"{latest_price:.2f} {currency}",
                    delta=f"{percentage_change:+.2f}%\n",
                    border=False,
                    help=get_ticker_name(ticker),
                )
                st.caption(
                    f"📈 Highest price in the last 6 months: "
                    f"{highest_price:.2f} {currency}"
                )

    if significant_changes > 0:
        st.warning(
            f"⚠️ {significant_changes} "
            f"significant change"
            f"{'s' if significant_changes != 1 else ''}"
        )


def run_frontend() -> None:
    """
    Runs the Streamlit market dashboard.
    This is the main entry point when Streamlit executes this file.
    """
    st.set_page_config(
        page_title="Market Dashboard",
        page_icon="📈",
        layout="wide",
    )

    st.title("📈 Market Dashboard")

    st.write(
        "Daily percentage changes for selected ETFs and currency pairs."
    )

    st.divider()

    main_prices, main_changes = get_daily_changes(TICKERS_Main)
    display_summary("🌎 Main ETFs", main_prices, main_changes)

    st.divider()

    ai_prices, ai_changes = get_daily_changes(TICKERS_Ai)
    display_summary("🤖 AI ETFs", ai_prices, ai_changes)

    st.divider()

    forex_prices, forex_changes = get_daily_changes(TICKERS_Forex)
    display_summary("💱 Forex", forex_prices, forex_changes)


if __name__ == "__main__":
    run_frontend()
