"""Smart Thermostat showcase dashboard built with `pylotos.ui`.

Runs identically on:
- M5Stack Cardputer ADV (240x135 + QWERTY)
- M5Stack Core2 / CoreS3 / CYD (320x240 + Touchscreen)
- M5Stack Dial (240x240 Round GC9A01 + Rotary Encoder + Touch)
- M5Stack AtomS3 (128x128 + 1-Button)
- Heltec V3 (128x64 1-bit OLED) & ESP32-C3 0.42" (72x40 micro OLED)
- Headless boards (NanoC6 / XIAO) via Desktop, Tablet, and Mobile Web UI (`:80`/`:443`)
"""

import pylotos.ui as ui

st = ui.State(
    temp=22.4,
    target=22.0,
    humidity=48,
    heat=True,
    mode="Auto",
    room="Living Room",
    hist=[21.2, 21.5, 21.9, 22.1, 22.4],
)


def _boost():
    st.target = 25.0
    st.heat = True
    app.toast("Boost -> 25C")


app = ui.App(
    "Thermostat",
    state=st,
    screens=[
        ui.Screen(
            "Overview",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Room", st.bind("temp"), unit="C", accent="cyan"),
                        ui.Gauge("Target", st.bind("target"), min=16, max=30, unit="C", accent="gold"),
                    ],
                ),
                ui.Sparkline("History", st.bind("hist"), unit="C", accent="cyan"),
                ui.StatusBadge(
                    "Heater",
                    lambda: "ACTIVE" if st.heat else "IDLE",
                    tone=lambda: "ok" if st.heat else "muted",
                ),
            ],
        ),
        ui.Screen(
            "Controls",
            children=[
                ui.Card(
                    "Climate",
                    children=[
                        ui.Switch("Heating", st.bind("heat")),
                        ui.Slider("Target", st.bind("target"), min=16, max=30, step=0.5, unit="C"),
                        ui.Select("Mode", st.bind("mode"), options=["Auto", "Eco", "Comfort"]),
                        ui.TextField("Room Name", st.bind("room")),
                        ui.Button("Boost 25C", on_click=_boost, shortcut="b"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(2000)
def _sample_temp():
    delta = 0.2 if (st.heat and st.temp < st.target) else -0.1
    st.temp = round(st.temp + delta, 1)
    hist = list(st.hist)
    hist.append(st.temp)
    if len(hist) > 20:
        hist = hist[-20:]
    st.hist = hist


async def run(cv):
    await app.run_async(cv)
