"""HMI Showcase: Themes, Priority Notifications, RLE Fonts & Semantic Icons.

Demonstrates Phase 3A `pylotos.ui` capabilities:
- Live runtime theme switching (`dark` Aviator, `light`, `high_contrast`) synced across LCD & Web
- Priority-queued `NotificationManager` (`info`, `ok`, `warn`, `err` preemption + unread badges)
- Proportional 5x7 / RLE bitmap typography (`sm`, `md`, `lg`, `xl`)
- 20 semantic 16x16 / 24x24 monochrome icons rendered inside a `CanvasBox`

Run locally:
    pylotos-sim examples/hmi_themes_and_alerts.py --board m5stack_core2 --port 8080
"""

import pylotos.ui as ui

st = ui.State(
    theme_name="dark",
    icon_size=16,
    font_preset="md",
    sample_text="PylotOS 2B-2",
    unread=0,
)


def _apply_theme(val):
    ui.theme_manager.set_theme(val)
    app.notify("Theme -> " + str(val), level="info", icon="settings")


def _push_level(lvl, msg, ic):
    app.notify(msg, level=lvl, icon=ic, duration_ms=2800)
    st.unread = app.notifications.unread_count


def _draw_showcase(cv, x, y, w, h):
    pal = cv.palette
    cv.rect(x, y, w, h, pal["border"])
    icons_row = ("wifi", "ble", "bolt", "cpu", "shield", "bell")
    sz = int(st.icon_size)
    ix = x + 6
    iy = y + 6
    for idx, name in enumerate(icons_row):
        if ix + sz > x + w - 4:
            break
        col = pal["gold"] if (idx % 2 == 1) else pal["cyan"]
        ui.draw_icon(cv, name, ix, iy, col=col, size=sz)
        ix += sz + 6

    ty = iy + sz + 6
    if ty + 10 <= y + h:
        ui.draw_text(
            cv,
            st.sample_text,
            x + 6,
            ty,
            col=pal["white"],
            font=str(st.font_preset),
            max_width=max(24, w - 12),
        )


app = ui.App(
    "HMI Studio",
    state=st,
    screens=[
        ui.Screen(
            "Themes & Fonts",
            icon="settings",
            children=[
                ui.CanvasBox(height=54, draw=_draw_showcase, label="RLE Font & Icon Atlas"),
                ui.Card(
                    "Appearance",
                    children=[
                        ui.Select(
                            "Theme",
                            st.bind("theme_name"),
                            options=["dark", "light", "high_contrast"],
                            on_change=_apply_theme,
                        ),
                        ui.Select(
                            "Font Size",
                            st.bind("font_preset"),
                            options=["sm", "md", "lg", "xl"],
                        ),
                        ui.Select(
                            "Icon Scale",
                            st.bind("icon_size"),
                            options=[12, 16, 24],
                        ),
                        ui.TextField("Banner Text", st.bind("sample_text")),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "Alerts",
            icon="bell",
            children=[
                ui.StatusBadge(
                    "Queue",
                    lambda: "{} unread".format(app.notifications.unread_count),
                    tone=lambda: "warn" if app.notifications.unread_count > 0 else "ok",
                ),
                ui.Card(
                    "Priority Preemption",
                    children=[
                        ui.Button(
                            "Info Toast",
                            on_click=lambda: _push_level("info", "Telemetry synced", "cloud"),
                            shortcut="i",
                        ),
                        ui.Button(
                            "Success Alert",
                            on_click=lambda: _push_level("ok", "Boot confirmed (asym-v1)", "check"),
                            shortcut="o",
                        ),
                        ui.Button(
                            "Warning Alert",
                            on_click=lambda: _push_level("warn", "EU868 duty at 80%", "warn"),
                            shortcut="w",
                        ),
                        ui.Button(
                            "Critical Error (Preempts!)",
                            on_click=lambda: _push_level("err", "Bus fault recovered", "error"),
                            shortcut="e",
                        ),
                        ui.Button(
                            "Mark All Read",
                            on_click=lambda: (
                                app.notifications.mark_all_read(),
                                setattr(st, "unread", 0),
                                app.mark_dirty(),
                            ),
                        ),
                    ],
                ),
            ],
        ),
    ],
)


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