"""Textual App — main application shell for the onboarding TUI."""

from __future__ import annotations

from pathlib import Path

from textual.app import App
from textual.binding import Binding

from cde_onboard.progress import ProgressManager


class OnboardApp(App[None]):
    """The ONA onboarding TUI application."""

    TITLE = "ONA Onboarding"
    SUB_TITLE = "Interactive developer environment tutorials"
    CSS_PATH = Path(__file__).parent / "styles" / "app.tcss"

    BINDINGS = [
        Binding("q", "quit", "Quit", show=True, priority=True),
        Binding("escape", "back", "Back", show=True),
    ]

    def __init__(self, start_lesson: int | None = None) -> None:
        super().__init__()
        self.progress = ProgressManager()
        self._start_lesson = start_lesson

    def on_mount(self) -> None:
        """Push the initial screen on mount."""
        if self._start_lesson is not None:
            from cde_onboard.screens.lesson import LessonScreen

            self.push_screen(LessonScreen(self._start_lesson, self.progress))
        else:
            from cde_onboard.screens.welcome import WelcomeScreen

            self.push_screen(WelcomeScreen(self.progress))

    async def action_back(self) -> None:
        """Pop the current screen, or quit if on the last screen."""
        if len(self.screen_stack) > 2:
            self.pop_screen()
        elif len(self.screen_stack) == 2:
            # On last pushed screen — pop it and show welcome
            self.pop_screen()
            if self._start_lesson is not None:
                # Launched with --lesson N, no welcome underneath — push one
                from cde_onboard.screens.welcome import WelcomeScreen

                self.push_screen(WelcomeScreen(self.progress))
        else:
            self.exit()
