from __future__ import annotations

import streamlit as st

_HELP_SCREENS: list[tuple[str, str]] = [
    (
        "Start Here",
        """
### What this app is for
Think of ManeshTrader like a **weather app for price candles**.
It does not place trades. It helps you answer:
- Is the market acting strong up, strong down, or messy?
- Did we get a real signal or just noise?

### The 10-second idea
Each candle gets a label:
- `real_bull`: a strong up break
- `real_bear`: a strong down break
- `fake`: noise inside the old range

Trend rule:
- 2 real up candles in a row => bullish trend
- 2 real down candles in a row => bearish trend
- Fake candles alone do not flip trend

### Why you should care
This turns a messy chart into simple states:
- **Go with up trend**
- **Go with down trend**
- **Wait when unclear**
""",
    ),
    (
        "How To Use",
        """
### A simple 5-step routine
1. Pick one symbol.
2. Use `1d` timeframe and `6mo` period.
3. Turn on `Show live decision guide` and `Show past behavior examples`.
4. Read trend + check latest examples.
5. Decide: follow trend, or stand aside if choppy.

### Important safety notes
- This app is **analysis-only**.
- It does **not** execute orders.
- Backtests and examples are educational.
- Never risk money you cannot afford to lose.
""",
    ),
    (
        "Main Setup",
        """
### Core controls (left sidebar)
These are your main knobs.

- `Symbol`: what you are looking at (`AAPL`, `BTC-USD`).
  Why care: wrong symbol = wrong answer.
- `Timeframe`: candle size (`1d`, `4h`, `1h`, etc.).
  Why care: smaller = noisier, bigger = smoother.
- `Period`: how much history to load.
  Why care: too short can miss context, too long can feel slow.
- `Max bars`: cap on candles loaded.
  Why care: helps performance and keeps chart readable.
- `Ignore potentially live last bar`: ignores the newest unfinished candle.
  Why care: unfinished candles can lie before they close.

### Child-friendly default
Start with:
- `Timeframe = 1d`
- `Period = 6mo`
- `Ignore potentially live last bar = ON`
""",
    ),
    (
        "Filters",
        """
### Classification Filters
These help you reduce fake signals.

- `Use previous body range (ignore wicks)`
  Means: compare against candle body, not long spikes.
  Why care: reduces wick tricks.

- `Enable volume filter`
  Means: low-volume moves are treated as fake.
  Why care: weak moves often fail.

- `Volume SMA window`
  Means: how many candles used for average volume.
  Why care: bigger window = steadier average.

- `Min volume / SMA multiplier`
  Means: how much volume is required vs average.
  Why care: higher value = stricter filter.

- `Gray out fake bars`
  Means: noise bars fade visually.
  Why care: easier to focus on important candles.

- `Hide market-closed gaps (stocks)`
  Means: removes weekend/closed-market blank spaces.
  Why care: cleaner chart shape.
""",
    ),
    (
        "Training Mode",
        """
### Training & Guidance controls
Use this section to learn the model.

- `Show live decision guide`
  Why care: tells bias (long/short/neutral) in plain English.

- `Show past behavior examples`
  Why care: shows historical examples of how signals played out.

- `Overlay example entries/exits on chart`
  Why care: lets you see examples directly on candles.

- `Focus chart on selected example`
  Why care: zooms to one example so you can study it.

- `Max training examples`
  Why care: more examples = more history, but busier table.

- `Replay mode (hide future bars)` + `Replay bars shown`
  Why care: practice without seeing the future first.

### Kid version
Replay mode is like covering answers on a worksheet,
then checking if your guess was right.
""",
    ),
    (
        "Monitoring + Advanced",
        """
### Monitoring
- `Auto-refresh`
  Why care: keeps data fresh while you watch.
- `Refresh interval (seconds)`
  Why care: lower is faster updates, but more load.
- `Display Timezone (US)`
  Why care: shows audit/event/training times in your preferred U.S. timezone (default CST/CDT).
- `Use 24-hour time`
  Why care: choose `13:00` style (ON) or `1:00 PM` style (OFF).

### Advanced Signals
- `Auto-run advanced panels (slower)`
  Why care: always-updated extras, but heavier.
- `Run advanced panels now`
  Why care: one-time run when you want speed normally.
- `Show multi-timeframe confirmation`
  Why care: checks if 1h/4h/1d agree.
- `Regime filter`
  Why care: warns when market is choppy (messy).

### Compare Symbols + Alerts
- `Enable compare symbols panel`
- `Compare symbols (comma separated)`
Why care: quick side-by-side trend check.

- `Enable alert rules`
- `Alert on bullish confirmations`
- `Alert on bearish confirmations`
- `Webhook URL (optional)`
Why care: get notified instead of watching charts all day.
""",
    ),
    (
        "Backtest Controls",
        """
### What a backtest is
A backtest asks: "If we used these rules in the past, what happened?"
It is practice data, not a promise.

### Every backtest control explained
- `Slippage (bps per side)`
  Meaning: extra price loss when entering/exiting.
  Why care: real fills are rarely perfect.

- `Fee (bps per side)`
  Meaning: trading cost paid on entry and exit.
  Why care: costs can erase small wins.

- `Stop loss (%)`
  Meaning: emergency exit if price moves against you by this percent.
  Why care: limits damage.
  Note: `0` means OFF.

- `Take profit (%)`
  Meaning: lock gains once profit reaches this percent.
  Why care: prevents giving back wins.
  Note: `0` means OFF.

- `Min hold bars`
  Meaning: shortest time a trade must stay open.
  Why care: avoids instant in-and-out noise trades.

- `Max hold bars`
  Meaning: longest time a trade can stay open.
  Why care: forces an exit if nothing happens.

### Simple example
If `Stop loss = 2%`, you are saying:
"If I am down 2%, I am out."
If `Take profit = 4%`, you are saying:
"If I am up 4%, I will lock it."
""",
    ),
]


@st.dialog("Help & Quick Start", width="large")
def help_dialog() -> None:
    total = len(_HELP_SCREENS)
    if "help_screen_index" not in st.session_state:
        st.session_state["help_screen_index"] = 0

    options = [title for title, _ in _HELP_SCREENS]
    safe_index = min(max(int(st.session_state["help_screen_index"]), 0), total - 1)
    st.session_state["help_screen_index"] = safe_index

    picker_col, _ = st.columns([3, 2])
    with picker_col:
        selected_title = st.selectbox("Help Screen", options, index=safe_index)
    selected_index = options.index(selected_title)
    if selected_index != st.session_state["help_screen_index"]:
        st.session_state["help_screen_index"] = selected_index
        safe_index = selected_index

    st.caption(f"Screen {safe_index + 1} of {total}")
    st.markdown(_HELP_SCREENS[safe_index][1])

    nav_col, _ = st.columns([2, 5])
    prev_col, next_col = nav_col.columns(2)
    with prev_col:
        if st.button("Previous", disabled=safe_index == 0):
            st.session_state["help_screen_index"] = max(safe_index - 1, 0)
    with next_col:
        if st.button("Next", disabled=safe_index >= total - 1):
            st.session_state["help_screen_index"] = min(safe_index + 1, total - 1)
