#!/usr/bin/env python3
# EVERYTHING INSIDE THIS PROGRAM IS ENGLISH (Lars's rule 1): code, comments, interface texts, Help.  The only other languages are FILES:
#   Helpfiles\SchoolTrainer\Lang\<code>.txt      the interface in another language (sv, ru)
#   Helpfiles\SchoolTrainer\school_data.json     the questions' own material (Swedish words, banks, topic names in sv/en/ru)
#   Helpfiles\SchoolTrainer\texts.json           the question sentences of the generators in sv/ru (key = the English sentence)
# Both data files are WRITTEN by SchoolTrainer\export_school_data.js from the web edition (Kids "Skolträning"), so the PC program and the
# web/Android page ask the same things.
"""SchoolTrainer - practise typical school things: pick a school year (1-6) and a subject, or the subject first, then a topic.

A round is 10 questions; a wrong answer comes back once at the end of the round.  The stars of a topic show your best result.
Run with --selftest to check every generator without opening a window."""
import ctypes
import json
import math
import os
import platform
import random
import re
import shutil
import subprocess
import sys
import tkinter as tk
import tkinter.font as tkfont
import webbrowser

APP_NAME = "School Trainer"
APP_TITLE = APP_NAME
APP_VERSION = "1.0"

# *************** DEL 01 - INTERFACE TEXTS (ENGLISH BUILT IN; sv/ru ARE Lang FILES) *****************
STRINGS = {
    "title": "School Trainer",
    "first": "Choose first",
    "by_grade": "School year",
    "by_subject": "Subject",
    "chosen": "You chose",
    "grade_n": "Year {n}",
    "year": "year",
    "n_topics": "{n} topics",
    "pick_grade": "Which school year?",
    "pick_subject": "Which subject?",
    "pick_topic": "What do you want to practise?",
    "mixed": "Mixed",
    "help": "Help",
    "about": "About",
    "notes": "My notes",
    "back": "Back",
    "close": "Close",
    "count": "Question {i} of {n}",
    "again": "once more",
    "ok": "Answer",
    "next": "Next",
    "praise": "Correct!|Great!|Well done!|Super!|Exactly!",
    "wrong": "Not quite. The right answer: {a}",
    "win": "{n} of {t} right at the first try",
    "play_again": "Play again",
    "to_menu": "Menu",
    "read_aloud": "Read aloud",
    "help_text": ("Pick a school year 1-6 and a subject (or the subject first - choose that at the top). Then pick what to practise.\n\n"
                  "A round is 10 questions. Type number answers with the keys (or the keyboard) and press Answer. A wrong answer comes back once at the end of the round.\n\n"
                  "The stars show your best result (right at the first try): 3 stars = 90 % or more, 2 stars = 70 %, 1 star = anything.\n\n"
                  "On the keyboard: digits, comma and Backspace for number answers, 1-4 to pick a choice, Enter for Answer / Next, Escape to close a window.\n\n"
                  "The globe changes the language of the buttons AND of the questions (Swedish, English, Russian). Swedish language, Sweden geography and "
                  "nature questions are written in Swedish in every language.\n\n"
                  "My notes is a place for your own texts. The questions are practice material and do not follow one school's syllabus exactly."),
}


# *************** DEL XX - PROGRAM HOME (WHERE MY DATA LIVES) *****************
# Copy verbatim into every program.  Rules, tree and table: 02_folder_tree_and_home.md
#
# Helpfiles, Icons and Folder-exe are SIBLINGS of Py, never children.  The home
# is COMPUTED, never hardcoded, so Py\<Name>.py and Folder-exe\<Name>\<Name>.exe
# find exactly the same data.
#
# Needs:  import os, sys


def _find_home(start):
    """Walk up (at most 4 levels) to the first folder that contains Helpfiles."""
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    # BOOTSTRAP: before Helpfiles exists the walk finds nothing, and returning
    # `start` would create Helpfiles as a CHILD of Py - every later run would
    # then find that wrong one first and never correct itself.  Py and
    # Folder-exe\<Name> are always direct children of the home, so their names
    # are enough to place the home correctly.
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    up_one = os.path.dirname(start)
    if os.path.basename(up_one).lower() == "folder-exe":
        return os.path.dirname(up_one)
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower scans for this line

# Name of this program = name of the .py (or of the .exe when built).  It is
# also the name of the data folder and of the icon, and it is computed so that
# a renamed file can never go out of sync with them.
PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False)
    else os.path.abspath(__file__)))[0]

BASE_DIR       = _program_home()
HELPFILES_DIR  = os.path.join(BASE_DIR, "Helpfiles")
PROGRAM_HF_DIR = os.path.join(HELPFILES_DIR, PROGRAM_NAME)   # own data
LOG_DIR        = os.path.join(HELPFILES_DIR, "0---Empty")    # logs ONLY
ICON_DIR       = os.path.join(BASE_DIR, "Icons")             # <PROGRAM_NAME>.ico


# *************** DEL XX - WINDOW ICON (EXTERNAL .ICO) ************************
# Copy verbatim into every program.  Rules and pitfalls: 10_icons.md
#
# The icon is an EXTERNAL file:  <home>\Icons\<PROGRAM_NAME>.ico
# It is never embedded in the program and never generated by it.  If the file
# is missing the program just runs with the default icon.
#
# Needs:  import ctypes, os, platform
#         block_home.py  (PROGRAM_NAME, ICON_DIR)
#
# In main():
#     _set_app_id()                                   # BEFORE tk.Tk()
#     root = tk.Tk()
#     root.title("...")
#     ... build the UI ...
#     root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
#     root.mainloop()


def _set_app_id():
    """Own taskbar group and icon for this program.  Call BEFORE tk.Tk()."""
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "MyOrg." + PROGRAM_NAME + ".1")
    except Exception:
        pass


def _find_icon_path() -> str:
    """<home>\\Icons\\<name>.ico, else the old place next to the .py, else ""."""
    name = PROGRAM_NAME + ".ico"
    here = os.path.dirname(os.path.abspath(globals().get("__file__", "")))
    for d in (ICON_DIR, os.path.join(here, "Icons")):
        p = os.path.join(d, name)
        if os.path.isfile(p):
            return p
    return ""


def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    ico_path = _find_icon_path()
    if not ico_path:
        return

    # Channel 1: tkinter's own API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Channel 2: WM_SETICON via Win32 (taskbar and Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        # winfo_id() is tkinter's inner frame; its PARENT is the real Win32
        # window.  FindWindowW by title is the fallback (it can pick the wrong
        # window if two windows share a title).
        hwnd = user32.GetParent(root.winfo_id()) or \
               user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON, 0, 0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


# *************** DEL XX - UI HELPERS (NO BLINK, MODAL DIALOGS) ***************
# Copy verbatim into every program.  Rules: 01_CORE_always_read.md, section 5.
#
# NO BLINKING CURSORS ANYWHERE.  Use tk.Entry / tk.Text (never ttk.Entry) and set
# the values PER WIDGET when it is created - also in Toplevel dialogs and log
# windows.  Do not rely on option_add.
#
# Needs:  import tkinter as tk

NO_BLINK = dict(insertofftime=0, insertontime=9999999)


def new_entry(parent, **kw):
    """tk.Entry with a fixed (non-blinking) cursor."""
    return tk.Entry(parent, **{**NO_BLINK, **kw})


def new_text(parent, **kw):
    """tk.Text with a fixed (non-blinking) cursor."""
    return tk.Text(parent, **{**NO_BLINK, **kw})


def no_blink(w):
    """Fix the cursor of a widget that already exists.  Returns the widget."""
    try:
        w.configure(**NO_BLINK)
    except Exception:
        pass
    return w


def make_modal(top, on_escape=None):
    """Every Toplevel dialog: grab_set(), focus_force(), <Escape> - in that order.

    on_escape is called instead of top.destroy() when Escape is pressed.
    A dialog opened on top of another modal one takes the grab; when it is
    destroyed the grab goes back to the dialog underneath (otherwise that one
    stops answering the mouse)."""
    try:
        below = top.grab_current()    # the modal window we are about to cover
    except Exception:
        below = None
    try:
        top.grab_set()
    except Exception:
        pass                      # window not viewable yet - not fatal
    try:
        top.focus_force()
    except Exception:
        pass
    top.bind("<Escape>", lambda e: (on_escape or top.destroy)())

    def _give_back(e):
        if e.widget is top and below is not None:
            try:
                if below.winfo_exists():
                    below.grab_set()
            except Exception:
                pass
    top.bind("<Destroy>", _give_back, add="+")


def continue_button(parent, text, command, **kw):
    """The "Continue" / "OK" / "Next" button of a game: reacts to a mouse click,
    Enter (also the numpad one) AND Space - always, whichever widget has focus.

    Returns the tk.Button; the caller packs/grids it.  The keys are bound on the
    button's own window and only act while the button exists and is on screen,
    so an old Continue can never fire from a later screen.  Enter/Space are
    left alone while the player is typing (Entry, Text, Combobox ...).  The
    button takes focus and also handles the keys itself (stopping tk's own Space
    handling, so nothing fires twice); the window binding covers every other
    focus, and steps aside for a DIFFERENT focused button (Space presses that)."""

    def go(event=None):
        if not btn.winfo_exists() or not btn.winfo_ismapped():
            return
        if str(btn.cget("state")) == "disabled":
            return
        command()

    def key(event):
        w = btn.focus_get()
        cls = w.winfo_class() if w is not None else ""
        if cls in ("Entry", "Text", "TEntry", "TCombobox", "Spinbox", "Listbox"):
            return                                   # the player is typing
        if (event.keysym == "space" and w is not btn
                and cls in ("Button", "TButton", "Checkbutton", "Radiobutton")):
            return                                   # tk presses that other button
        go()
        return "break"

    btn = tk.Button(parent, text=text, command=go, **kw)
    top = btn.winfo_toplevel()
    seqs = ("<Return>", "<KP_Enter>", "<space>")
    ids = [(seq, top.bind(seq, key, add="+")) for seq in seqs]
    for seq in seqs:                     # focus on the button itself
        btn.bind(seq, lambda e: (go(), "break")[1])

    def cleanup(e):
        if e.widget is btn:
            for seq, fid in ids:
                try:
                    top.unbind(seq, fid)
                except Exception:
                    pass
    btn.bind("<Destroy>", cleanup, add="+")
    btn.focus_set()
    return btn


# *************** DEL XX - OPEN THINGS WITH MY OWN PROGRAMS *******************
# Copy verbatim.  A link, folder, PDF, log or image opened from here lands in MY
# programs, not in Edge / Explorer / Notepad / Adobe.  Rules and the reasons
# behind them: 20_open_with_my_programs.md
#
# Which program opens WHAT is decided in ONE file, never in code:
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
# _FALLBACK_KINDS is used only when that file cannot be read.
#
# Three rules this block must never break:
#   1. It may NEVER raise (Help must open even if WhyBrowse or the table is gone).
#   2. It may NEVER hand a thing to ITSELF (that is how you build a loop).
#   3. Popen, never run() (run() would freeze this program).
# And NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it starts another copy of this program (fork bomb, 2026-09-04).
#
# The table is read ONCE, the first time something is opened - not at start-up.
#
# Needs:  import os, sys, json, shutil, subprocess, webbrowser
#         block_home.py  (_program_home, PROGRAM_NAME)

MY_PROGRAM_NAME = PROGRAM_NAME

# Only used when DefaultHub's table cannot be read.  Same shape as the file.
_FALLBACK_KINDS = {
    "url":    {"match_type": "protocol", "match": ["http://", "https://"],
               "target_type": "suite", "target": "WhyBrowse"},
    "mail":   {"match_type": "protocol", "match": ["mailto:"],
               "target_type": "suite", "target": "F(re)email"},
    "folder": {"match_type": "folder", "match": [],
               "target_type": "suite", "target": "File_manager"},
    "pdf":    {"match_type": "extension", "match": [".pdf"],
               "target_type": "suite", "target": "PDFull"},
    "text":   {"match_type": "extension",
               "match": [".txt", ".log", ".md", ".csv", ".ini", ".cfg",
                         ".json", ".xml", ".py", ".nfo", ".srt", ".bat",
                         ".ps1"],
               "target_type": "suite", "target": "Meditor"},
    "image":  {"match_type": "extension",
               "match": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
                         ".tif", ".tiff", ".ico"],
               "target_type": "suite", "target": "SeeView"},
}
_HUB_KINDS = None


def _my_app_roots() -> list:
    """Trees to look in, nearest first.

    My own home is not always the tree that holds the other programs: a music
    program's home is 1---Musik, and Chess / Foul_bridge / Quiz_manager /
    Railroad_racing are their own worlds - none of those has a WhyBrowse or a
    DefaultHub.  So after its own home this walks UP, four levels, like
    _find_home."""
    roots, d = [], _program_home()
    for _ in range(4):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return roots


def _hub_kinds() -> dict:
    """DefaultHub's table, read once and remembered."""
    global _HUB_KINDS
    if _HUB_KINDS is not None:
        return _HUB_KINDS
    kinds = {}
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    kinds = (json.load(fh) or {}).get("kinds") or {}
                break
        except Exception:
            pass                       # unreadable or half-written: fall back
    _HUB_KINDS = kinds if isinstance(kinds, dict) and kinds else _FALLBACK_KINDS
    return _HUB_KINDS


def _target_for(thing, is_folder: bool = False) -> str:
    """Which of my programs opens this?  "" means: let Windows decide."""
    low = str(thing).lower()
    ext = "" if is_folder else os.path.splitext(low)[1]
    for k in (_hub_kinds() or {}).values():
        try:
            mt = k.get("match_type")
            match = [str(m).lower() for m in (k.get("match") or [])]
            if mt == "folder":
                hit = is_folder
            elif mt == "protocol":
                hit = (not is_folder) and any(low.startswith(m) for m in match)
            elif mt == "extension":
                hit = bool(ext) and ext in match
            else:
                hit = False
            if hit:
                if k.get("target_type") == "suite":
                    return str(k.get("target") or "")
                return ""              # "system" - deliberately Windows' job
        except Exception:
            continue
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of my .py programs with, or "".

    A 0-byte file is an App Execution Alias
    (%LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe and friends) - not an
    interpreter - and which() finds it first wherever the Store stub is on PATH."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
        cands.append(sys.executable)
    cands.append(shutil.which("pythonw"))
    cands.append(shutil.which("python"))
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs",
                        "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            cands.append(os.path.join(base, d, "pythonw.exe"))
    except OSError:
        pass
    for c in cands:
        try:
            if c and os.path.isfile(c) and os.path.getsize(c) > 0:
                return c
        except OSError:
            pass
    return ""


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, a build is only the fallback: the .py is the file that is
    actually edited, so it is always current, while a build can be days old
    (2026-09-05: File_manager's build had no command-line handling at all).
    A build is used only when there is no source or no interpreter."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    cmd = work = None
    for home in _my_app_roots():
        script = os.path.join(home, "Py", name + ".py")
        exe = os.path.join(home, "Folder-exe", name, name + ".exe")
        if os.path.isfile(script):
            pyw = _real_pythonw()
            if pyw:
                cmd, work = [pyw, script, str(argument)], os.path.dirname(script)
                break
        if os.path.isfile(exe):           # no source, or no interpreter
            cmd, work = [exe, str(argument)], os.path.dirname(exe)
            break
        if os.path.isfile(script):
            break                         # found the tree; do not look further
    if not cmd:
        return False
    try:
        subprocess.Popen(cmd, cwd=work or None)
        return True
    except Exception:
        return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass


# *************** DEL xx - TOOL POPUPS: MOVABLE, ZOOMABLE, NON-MODAL **********
# block_popups.py - copy verbatim into a program (needs: import os, tkinter as tk,
# tkinter.font as tkfont).  Two parts:
#
#   ToolPopup   a window beside the main window that you can DRAG, ZOOM (the
#               [-] 100% [+] bar, or Ctrl+mouse wheel), and close with Esc.
#               Position, zoom and "is it open" live in the PROGRAM'S OWN
#               settings dict (`store`), under three key names the program
#               picks - so they survive a restart.  Subclass it and write
#               build(self, s): s is the zoom as a float (1.0 = 100 %).  Draw
#               into self.body, or call self.canvas_area(w, h) and draw on the
#               canvas it returns (it gets a scrollbar by itself when the
#               screen is too small for the whole thing).
#
#   PlayerTextPopup  the PLAYER'S OWN TEXT, written and saved inside the program
#               (tactics, house rules, "good to remember").  Every file
#               <Helpfiles>\<program>\Playertext-<name>.txt is one text; what
#               follows the prefix is what the drop-down offers; the chosen text
#               is shown in a box with scrollbars + mouse wheel and can be edited
#               right there (saved by itself a second after the last key, and
#               when the popup closes or another text is picked).  [New...]
#               starts another text.  Nothing is ever deleted by the program.
#               An empty text never creates a file.  Call .save_now() from the
#               program's own on_close.
#
# The program supplies:
#   store      its settings dict (mutated in place)
#   keys       (show_key, pos_key, zoom_key) for a ToolPopup, e.g. ("show_aid","popup_pos","popup_zoom");
#              (show_key, pos_key, zoom_key, sel_key) for PlayerTextPopup, e.g.
#              ("show_playertext","playertext_pos","playertext_zoom","playertext_sel")
#              NB: pick names that do not collide with a text-key prefix the
#              program's self-test scans for (a "aid_*" setting broke one).
#   on_change  callable that saves the settings (e.g. lambda: save_settings(S))
#   theme      dict: bg panel fg dim accent btn btnfg field field_fg
#   on_closed  callable run after the popup closed itself (tick boxes off ...)
#   on_key     optional; Space/Enter forwarded to the game ("Play").  NEVER for
#              the notes popup - it is typed into.
#
# Open it once at start-up for a game's aid (show_key true), open the player
# text from a menu / button.  The main window keeps working: nothing here grabs input.

POPUP_ZOOMS = (50, 60, 70, 80, 90, 100, 115, 130, 150)


def popup_lines(font, texts, width):
    """How many lines the LONGEST of `texts` needs at `width` px (greedy word
    wrap).  Gives a label one fixed height whatever the language
    (01_CORE item 6)."""
    best = 1
    for t in texts:
        lines = 0
        for para in t.split("\n"):
            cur, n = "", 1
            for w in para.split():
                trial = (cur + " " + w).strip()
                if cur and font.measure(trial) > width:
                    n += 1
                    cur = w
                else:
                    cur = trial
            lines += n
        best = max(best, lines)
    return best


class ToolPopup(object):
    resizable = False

    def __init__(self, root, store, keys, on_change, theme, title,
                 on_closed=None, on_key=None):
        self.root, self.store, self.theme = root, store, theme
        self.k_show, self.k_pos, self.k_zoom = keys
        self.on_change, self.on_closed = on_change, on_closed
        self.move_job = None
        self._cv = self._bar = None
        self._full_h = 0
        top = self.top = tk.Toplevel(root)
        top.title(title)
        top.configure(bg=theme["bg"])
        top.resizable(self.resizable, self.resizable)
        top.transient(root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", lambda e: self.close())
        top.bind("<Control-MouseWheel>",
                 lambda e: self.step(1 if e.delta > 0 else -1))
        if on_key:
            for key in ("<Return>", "<KP_Enter>", "<space>"):
                top.bind(key, lambda e: on_key())
        bar = self.toolbar = tk.Frame(top, bg=theme["panel"])
        bar.pack(fill="x")
        self._btn(bar, u"−", lambda: self.step(-1)).pack(
            side="left", padx=(6, 0), pady=3)
        self.lbl_zoom = tk.Label(bar, width=5, bg=theme["panel"],
                                 fg=theme["fg"], font=("Segoe UI", 9, "bold"))
        self.lbl_zoom.pack(side="left")
        self._btn(bar, "+", lambda: self.step(1)).pack(side="left")
        self._btn(bar, "100%", lambda: self.set_zoom(100), w=5).pack(
            side="left", padx=(6, 0))
        self.extra_toolbar(bar)
        self.body = tk.Frame(top, bg=theme["bg"])
        self.body.pack(fill="both", expand=True)
        self._rebuild()
        self._place(store.get(self.k_pos))
        top.bind("<Configure>", self._configured)

    # ---- for subclasses ------------------------------------------------------
    def build(self, s):
        raise NotImplementedError

    def extra_toolbar(self, bar):
        pass

    def before_rebuild(self):
        pass

    def before_close(self):
        pass

    # ---- zoom ----------------------------------------------------------------
    def zoom(self):
        z = self.store.get(self.k_zoom, 100)
        return z if z in POPUP_ZOOMS else 100

    def step(self, d):
        i = POPUP_ZOOMS.index(self.zoom()) + d
        self.set_zoom(POPUP_ZOOMS[max(0, min(len(POPUP_ZOOMS) - 1, i))])

    def set_zoom(self, z):
        if z == self.zoom():
            return
        self.store[self.k_zoom] = z
        self.on_change()
        self._rebuild()
        self._place(self._where())          # the size changed: stay on screen

    def _btn(self, parent, text, cmd, w=3):
        th = self.theme
        return tk.Button(parent, text=text, command=cmd, width=w, bd=0,
                         relief="flat", bg=th["btn"], fg=th["btnfg"],
                         activebackground=th["accent"], takefocus=0,
                         cursor="hand2", font=("Segoe UI", 9, "bold"))

    def _rebuild(self):
        self.before_rebuild()
        for w in self.body.winfo_children():
            w.destroy()
        self._cv = None
        self.lbl_zoom.configure(text="%d%%" % self.zoom())
        self.build(self.zoom() / 100.0)
        self.top.update_idletasks()
        self._fit()

    # ---- a canvas that scrolls only when the screen is too small --------------
    def canvas_area(self, w, h):
        th = self.theme
        frame = tk.Frame(self.body, bg=th["bg"])
        frame.pack(padx=6)
        cv = tk.Canvas(frame, width=w, height=h, bg=th["bg"], bd=0,
                       highlightthickness=0, scrollregion=(0, 0, w, h))
        cv.pack(side="left")
        bar = tk.Scrollbar(frame, command=cv.yview, bg=th["panel"])
        cv.configure(yscrollcommand=bar.set)
        cv.bind("<MouseWheel>", lambda e: cv.yview_scroll(
            -1 if e.delta > 0 else 1, "units"))
        self._cv, self._bar, self._full_h = cv, bar, h
        return cv

    def resize_canvas(self, h):
        """The drawing is finished and turned out `h` px high."""
        h = int(h)
        w = int(self._cv.cget("width"))
        self._cv.configure(height=h, scrollregion=(0, 0, w, h))
        self._full_h = h

    def _fit(self):
        cv = self._cv
        if cv is None:
            return
        cv.configure(height=self._full_h)
        self._bar.pack_forget()
        self.top.update_idletasks()
        excess = self.top.winfo_reqheight() - (self.top.winfo_screenheight() - 90)
        if excess > 0:
            cv.configure(height=max(240, self._full_h - excess))
            self._bar.pack(side="left", fill="y")

    # ---- position ------------------------------------------------------------
    def _where(self):
        return [self.top.winfo_x(), self.top.winfo_y()]

    def _place(self, pos):
        top, root = self.top, self.root
        top.update_idletasks()
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        w, h = top.winfo_reqwidth(), top.winfo_reqheight()
        ok = (isinstance(pos, (list, tuple)) and len(pos) == 2
              and all(isinstance(v, int) for v in pos)
              and -w + 60 < pos[0] < sw - 60 and 0 <= pos[1] < sh - 60)
        if ok:
            x, y = pos
            x = min(x, max(0, sw - w)) if x + w > sw + 40 else x
        else:                               # default: right of the main window
            root.update_idletasks()
            x = root.winfo_x() + root.winfo_width() + 8
            y = root.winfo_y()
            if x + w > sw:                  # no room: hug the screen edge
                x = max(0, sw - w)
            y = max(0, min(y, sh - h - 40))
        top.geometry("+%d+%d" % (x, y))

    def _configured(self, event):
        if event.widget is not self.top:
            return
        if self.move_job:
            self.top.after_cancel(self.move_job)
        self.move_job = self.top.after(400, self._moved)

    def _moved(self):
        self.move_job = None
        try:
            self.store[self.k_pos] = [int(v) for v in self._where()]
            self.on_change()
        except Exception:
            pass

    def retitle(self, title):
        self.top.title(title)

    def close(self):
        try:
            self.before_close()
        except Exception:
            pass
        if self.move_job:
            try:
                self.top.after_cancel(self.move_job)
            except Exception:
                pass
        try:
            self.top.destroy()
        except Exception:
            pass
        self.store[self.k_show] = False
        self.on_change()
        if self.on_closed:
            self.on_closed()


PLAYERTEXT_PREFIX = "Playertext-"
PLAYERTEXT_DEFAULT_LABELS = {
    "hint": "Your own text - saved by itself as Playertext-<name>.txt in the "
            "program's Helpfiles folder.  Every such file there can be picked above.",
    "folder": "Folder", "new": "New...", "wrap": "Wrap",
    "newname": "Name of the new text (tactics, remember, house rules ...):",
    "ok": "OK", "cancel": "Cancel"}


def playertext_names(folder):
    """The <name> of every Playertext-<name>.txt in `folder`, sorted.  A
    Notes.txt from the first version of this block becomes Playertext-Notes.txt."""
    try:
        old, new = (os.path.join(folder, "Notes.txt"),
                    os.path.join(folder, PLAYERTEXT_PREFIX + "Notes.txt"))
        if os.path.isfile(old) and not os.path.exists(new):
            os.replace(old, new)
    except OSError:
        pass
    out = []
    try:
        for n in os.listdir(folder):
            if (n.lower().startswith(PLAYERTEXT_PREFIX.lower())
                    and n.lower().endswith(".txt")
                    and len(n) > len(PLAYERTEXT_PREFIX) + 4):
                out.append(n[len(PLAYERTEXT_PREFIX):-4])
    except OSError:
        pass
    return sorted(out, key=lambda s: s.lower())


def playertext_clean(name):
    """A name that is safe in a file name (no \\ / : * ? " < > |)."""
    bad = '<>:"/\\|?*'
    name = "".join(c for c in name if c not in bad and ord(c) >= 32)
    return name.strip().strip(".")[:40]


class PlayerTextPopup(ToolPopup):
    """The player's own text, written and saved INSIDE the program: tactics,
    house rules, things to remember.  Every file
    <Helpfiles>/<program>/Playertext-<name>.txt is one text; the part after
    the prefix is what the drop-down offers, and the chosen one is shown in a
    box with a scrollbar and mouse-wheel scrolling (and a horizontal bar when
    "Wrap" is off).  Typing saves by itself a second later and on close/switch.
    [New...] starts another text.  Nothing is ever deleted by the program.
    keys = (show_key, pos_key, zoom_key, selected_name_key)
    labels() -> dict with any of PLAYERTEXT_DEFAULT_LABELS' keys (a language
    switch calls relabel() which asks again).  Call .save_now() from the
    program's own on_close."""
    resizable = True

    def __init__(self, root, store, keys, on_change, theme, title, folder,
                 labels, on_closed=None, default_name="Notes"):
        self.folder, self.labels = folder, labels
        self.k_sel = keys[3]
        self.txt = self.hbar = self.btn_folder = self.lbl_status = None
        self.save_job = None
        self.dirty = False
        self.saved = None                   # None = no file yet
        names = playertext_names(folder)
        sel = store.get(self.k_sel)
        self.name = sel if sel in names else (names[0] if names else default_name)
        self.content = self._read(self.name)
        self.wrap = None
        ToolPopup.__init__(self, root, store, keys[:3], on_change, theme,
                           title, on_closed)
        self.wrap = self.wrap or tk.BooleanVar(value=True)
        self.top.after(80, self._focus)

    def _l(self, key):
        try:
            return self.labels().get(key) or PLAYERTEXT_DEFAULT_LABELS[key]
        except Exception:
            return PLAYERTEXT_DEFAULT_LABELS[key]

    def _path(self, name=None):
        return os.path.join(self.folder,
                            PLAYERTEXT_PREFIX + (name or self.name) + ".txt")

    def _focus(self):
        try:
            self.txt.focus_set()
        except Exception:
            pass

    def _read(self, name):
        self.saved = None
        self.dirty = False
        try:
            if os.path.isfile(self._path(name)):
                with open(self._path(name), encoding="utf-8-sig",
                          errors="replace") as fh:
                    text = fh.read()
                self.saved = text
                return text
        except Exception:
            pass
        return ""

    def extra_toolbar(self, bar):
        self.btn_folder = self._btn(bar, self._l("folder"), self._open_folder,
                                    w=8)
        self.btn_folder.pack(side="right", padx=6)

    def _open_folder(self):
        try:
            os.makedirs(self.folder, exist_ok=True)
            os.startfile(self.folder)
        except Exception:
            pass

    def before_rebuild(self):
        if self.txt is not None:
            try:
                self.content = self.txt.get("1.0", "end-1c")
            except Exception:
                pass

    def build(self, s):
        th = self.theme
        if self.wrap is None:
            self.wrap = tk.BooleanVar(value=True)
        row = tk.Frame(self.body, bg=th["bg"])
        row.pack(fill="x", padx=6, pady=(6, 0))
        tk.Label(row, text=PLAYERTEXT_PREFIX, bg=th["bg"], fg=th["dim"],
                 font=("Segoe UI", 9)).pack(side="left")
        names = playertext_names(self.folder)
        if self.name not in names:
            names = sorted(names + [self.name], key=lambda x: x.lower())
        self.var_name = tk.StringVar(value=self.name)
        om = tk.OptionMenu(row, self.var_name, *names, command=self._picked)
        om.configure(bg=th["btn"], fg=th["btnfg"], activebackground=th["accent"],
                     highlightthickness=0, bd=0, relief="flat", takefocus=0,
                     font=("Segoe UI", 9, "bold"), cursor="hand2")
        om["menu"].configure(bg=th["btn"], fg=th["btnfg"],
                             activebackground=th["accent"],
                             font=("Segoe UI", 9))
        om.pack(side="left")
        self._btn(row, self._l("new"), self._new, w=8).pack(side="left", padx=6)
        tk.Checkbutton(row, text=self._l("wrap"), variable=self.wrap,
                       command=self._wrap_changed, bg=th["bg"], fg=th["fg"],
                       selectcolor=th["panel"], activebackground=th["bg"],
                       activeforeground=th["accent"], highlightthickness=0,
                       takefocus=0, font=("Segoe UI", 9)).pack(side="right")
        box = tk.Frame(self.body, bg=th["panel"])
        box.pack(fill="both", expand=True, padx=6, pady=(4, 2))
        box.grid_rowconfigure(0, weight=1)
        box.grid_columnconfigure(0, weight=1)
        vbar = tk.Scrollbar(box, orient="vertical", bg=th["panel"])
        self.hbar = tk.Scrollbar(box, orient="horizontal", bg=th["panel"])
        self.txt = tk.Text(
            box, width=46, height=18, undo=True, bd=0, highlightthickness=0,
            padx=8, pady=6, bg=th["field"], fg=th["field_fg"],
            insertbackground=th["field_fg"], insertofftime=0,
            insertontime=1000,                           # no blinking cursor
            wrap="word" if self.wrap.get() else "none",
            font=("Segoe UI", max(7, int(round(10 * s)))),
            yscrollcommand=vbar.set, xscrollcommand=self.hbar.set)
        self.txt.grid(row=0, column=0, sticky="nsew")
        vbar.grid(row=0, column=1, sticky="ns")
        vbar.configure(command=self.txt.yview)
        self.hbar.configure(command=self.txt.xview)
        self._wrap_changed()
        self.txt.insert("1.0", self.content)
        self.txt.edit_modified(False)
        self.txt.edit_reset()

        def modified(e):
            if self.txt.edit_modified():
                self.txt.edit_modified(False)
                self._changed()
        self.txt.bind("<<Modified>>", modified)
        self.lbl_status = tk.Label(self.body, anchor="w", justify="left",
                                   bg=th["bg"], fg=th["dim"],
                                   font=("Segoe UI", 8), wraplength=420,
                                   text=self._l("hint"))
        self.lbl_status.pack(fill="x", padx=8, pady=(0, 4))

    def _wrap_changed(self):
        on = self.wrap.get()
        self.txt.configure(wrap="word" if on else "none")
        if on:
            self.hbar.grid_forget()
        else:
            self.hbar.grid(row=1, column=0, sticky="ew")

    def _picked(self, name):
        if name != self.name:
            self._switch(name)

    def _switch(self, name):
        self.save_now()
        self.txt = None                     # do not cache the old text
        self.name = name
        self.content = self._read(name)
        self.store[self.k_sel] = name
        self.on_change()
        self._rebuild()
        self._focus()

    def _new(self):
        th = self.theme
        self.save_now()
        dlg = tk.Toplevel(self.top)
        dlg.title(self._l("new"))
        dlg.transient(self.top)
        dlg.configure(bg=th["bg"])
        dlg.resizable(False, False)
        tk.Label(dlg, text=self._l("newname"), bg=th["bg"], fg=th["fg"],
                 font=("Segoe UI", 9)).pack(padx=14, pady=(12, 4))
        var = tk.StringVar()
        ent = tk.Entry(dlg, textvariable=var, width=30, bd=0,
                       bg=th["field"], fg=th["field_fg"],
                       insertbackground=th["field_fg"], insertofftime=0,
                       insertontime=1000, font=("Segoe UI", 10))
        ent.pack(padx=14, ipady=3)

        def ok(event=None):
            nm = playertext_clean(var.get())
            dlg.destroy()
            if nm:
                existing = {n.lower(): n for n in playertext_names(self.folder)}
                self._switch(existing.get(nm.lower(), nm))
        row = tk.Frame(dlg, bg=th["bg"])
        row.pack(pady=10)
        self._btn(row, self._l("ok"), ok, w=8).pack(side="left", padx=4)
        self._btn(row, self._l("cancel"), dlg.destroy, w=8).pack(side="left",
                                                                  padx=4)
        dlg.bind("<Return>", ok)
        dlg.bind("<Escape>", lambda e: dlg.destroy())
        dlg.update_idletasks()
        dlg.geometry("+%d+%d" % (self.top.winfo_x() + 40, self.top.winfo_y() + 80))
        dlg.grab_set()
        ent.focus_force()

    def _changed(self):
        self.dirty = True
        if self.save_job:
            self.top.after_cancel(self.save_job)
        self.save_job = self.top.after(1000, self.save_now)

    def save_now(self):
        if self.save_job:
            try:
                self.top.after_cancel(self.save_job)
            except Exception:
                pass
            self.save_job = None
        if self.txt is None or not self.dirty:
            return
        try:
            text = self.txt.get("1.0", "end-1c")
        except Exception:
            return
        self.content = text
        if self.saved is None and not text.strip():
            self.dirty = False              # an empty text never makes a file
            return
        try:
            os.makedirs(self.folder, exist_ok=True)
            tmp = self._path() + ".tmp"
            with open(tmp, "w", encoding="utf-8") as fh:
                fh.write(text)
            os.replace(tmp, self._path())
            self.saved, self.dirty = text, False
        except Exception:
            pass

    def before_close(self):
        self.save_now()

    def relabel(self, title):
        self.retitle(title)
        self.btn_folder.configure(text=self._l("folder"))
        self._rebuild()


# *************** DEL XX - LANGUAGE PICKER (GLOBE ICON) ************************
# Copy verbatim into every game.  Rules: 40_games.md, "Language switch".
#
# A tiny globe (drawn on a Canvas, so it is the same size in every language and
# needs no emoji font) that sits in the main window ALWAYS - not buried in
# Settings.  Click it -> a menu with every language the game has, each under its
# OWN name in its OWN script (English, Svenska, Русский, Deutsch ...), so a
# player who ended up in a language they cannot read can still find their way
# back.  The current language carries a bullet.
#
# Needs:  import tkinter as tk
#
# Call:   pick = make_language_picker(parent, LANGS, get_lang, set_lang,
#                                     bg="#1e1e2e", fg="#e0e0e0")
#         pick.pack(side="right", padx=6)     # or .grid(...)
#   LANGS     tuple/list of language codes the game has, e.g. ("en","sv","ru")
#   get_lang  () -> current code
#   set_lang  (code) -> switch the game to that language (rebuild the texts)
# Menu labels are NEVER translated - that is the whole point.

NATIVE_LANGUAGE_NAMES = {
    "en": "English",   "sv": "Svenska",    "ru": "Русский",   "de": "Deutsch",
    "fr": "Français",  "es": "Español",    "pt": "Português", "it": "Italiano",
    "nl": "Nederlands", "da": "Dansk",     "no": "Norsk",     "fi": "Suomi",
    "pl": "Polski",    "cs": "Čeština",    "hu": "Magyar",    "tr": "Türkçe",
    "uk": "Українська", "el": "Ελληνικά",  "ja": "日本語",     "zh": "中文",
    "ko": "한국어",     "ar": "العربية",   "he": "עברית",
}

GLOBE_SIZE = 20     # px; roughly a checkbox.  Fixed, whatever the language.


def _draw_globe(cv, fg):
    """Outline globe: circle, equator, one meridian ellipse, two parallels."""
    s = GLOBE_SIZE
    m = 2
    cv.delete("all")
    cv.create_oval(m, m, s - m, s - m, outline=fg, width=1)
    cv.create_line(m, s // 2, s - m, s // 2, fill=fg)                # equator
    cv.create_oval(s // 2 - 4, m, s // 2 + 4, s - m, outline=fg)      # meridians
    cv.create_line(s // 2, m, s // 2, s - m, fill=fg)                 # axis
    cv.create_arc(m, m + 4, s - m, s - m - 4, start=0, extent=180,
                  style="arc", outline=fg)                            # parallels
    cv.create_arc(m, m + 4, s - m, s - m - 4, start=180, extent=180,
                  style="arc", outline=fg)


def make_language_picker(parent, langs, get_lang, set_lang,
                         bg="#1e1e2e", fg="#e0e0e0", hover="#89b4fa"):
    """Return the globe Canvas; the caller packs/grids it."""
    cv = tk.Canvas(parent, width=GLOBE_SIZE, height=GLOBE_SIZE, bg=bg,
                   highlightthickness=0, cursor="hand2", takefocus=0)
    _draw_globe(cv, fg)

    def popup(event=None):
        menu = tk.Menu(cv, tearoff=0)
        cur = get_lang()
        for code in langs:
            name = NATIVE_LANGUAGE_NAMES.get(code, code)
            menu.add_command(label=("\u25cf  " if code == cur else "    ") + name,
                             command=lambda c=code: set_lang(c))
        x = cv.winfo_rootx()
        y = cv.winfo_rooty() + GLOBE_SIZE + 2
        try:
            menu.tk_popup(x, y)
        finally:
            menu.grab_release()

    cv.bind("<Button-1>", popup)
    cv.bind("<Enter>", lambda e: _draw_globe(cv, hover))
    cv.bind("<Leave>", lambda e: _draw_globe(cv, fg))
    return cv


# *************** DEL xx - LANGUAGE FILES (Lang\<code>.txt) ********************
# block_language_files.py - copied from Speed_Circuit.py DEL 04b (2026-10-02).
# Rules: 40_games.md, "Languages are FILES in a language folder".
#
# ONLY ENGLISH IS BUILT IN (2026-10-03): the STRINGS table holds one English
# text per key, {key: "text"}.  A tuple is still read, so an old game keeps the
# columns it already has - set BUILTIN_LANGS to those codes IN COLUMN ORDER,
# e.g. ("en", "sv", "ru").  Every other language - SWEDISH INCLUDED in a new
# game - is a FILE  Helpfiles\<Program>\Lang\<code>.txt  made by HTTP-Claude,
# never by Code-Claude.  The globe menu (block_language_picker.py) iterates LANGS, which
# looks at the folder again every time, so dropping in de.txt adds German with
# no code change.  A file overrides the built-in text; a missing file, key or
# line falls back to the built-in text (English): the game never fails.
#
# The program must already have, ABOVE this block:
#   import os, re
#   PROGRAM_HF_DIR      (block_home.py)         APP_TITLE
#   STRINGS             {key: "English text"}    NATIVE_LANGUAGE_NAMES (block_language_picker.py)
# and must call:  LANG = Language(saved code)  -  tr("key", a=1)  everywhere
# (replace the old tr/LANG pair), and in main():
#   if "--export-lang" in sys.argv[1:]:
#       for p in export_lang_files(): print(p)
#       sys.exit(0)
# --export-lang writes Lang\en.txt (one file per code in BUILTIN_LANGS): the
# template Lars gives to HTTP-Claude for sv/ru/<designer's language>.  Texts built from pieces in code must be
# templates with {placeholders} (grammar differs between languages).

BUILTIN_LANGS = ("en",)
LANG_DIR = os.path.join(PROGRAM_HF_DIR, "Lang")
_LANG_CODE_RE = re.compile(r"^[a-z]{2,3}$")


def _row(key):
    """STRINGS[key] as a tuple - a plain English string becomes a 1-tuple."""
    row = STRINGS.get(key)
    if row is None:
        return ()
    if isinstance(row, str):
        return (row,)
    return tuple(row)


def _unescape(t):
    return re.sub(r"\\(.)", lambda m: "\n" if m.group(1) == "n" else m.group(1), t)


def _escape(t):
    return t.replace("\\", "\\\\").replace("\n", "\\n")


def read_lang_file(code):
    """-> ({key: text}, native name or None).  Never raises."""
    texts, name = {}, None
    try:
        with open(os.path.join(LANG_DIR, code + ".txt"), encoding="utf-8-sig", errors="replace") as fh:
            for raw in fh:
                line = raw.rstrip("\r\n")
                if not line.strip() or line.lstrip().startswith("#") or "=" not in line:
                    continue
                k, v = line.split("=", 1)
                k, v = k.strip(), _unescape(v.strip())
                if k == "name":
                    name = v
                elif k and v:
                    texts[k] = v
    except Exception:
        pass
    return texts, name


def scan_langs():
    """Codes of every language the game has: the built-in ones plus every Lang/<code>.txt."""
    codes = list(BUILTIN_LANGS)
    try:
        for n in sorted(os.listdir(LANG_DIR)):
            c = os.path.splitext(n)[0].lower()
            if n.lower().endswith(".txt") and _LANG_CODE_RE.match(c) and c not in codes:
                codes.append(c)
                nm = read_lang_file(c)[1]
                if nm:
                    NATIVE_LANGUAGE_NAMES.setdefault(c, nm)
    except OSError:
        pass
    return codes


class LangList(object):
    """What the globe menu iterates: looked at again every time it opens."""

    def __iter__(self):
        return iter(scan_langs())

    def __len__(self):
        return len(scan_langs())

    def __contains__(self, c):
        return c in scan_langs()


LANGS = LangList()


class Language(object):
    """The current language; tr() reads it."""

    def __init__(self, code="en"):
        self.code = "en"
        self.idx = 0
        self.ext = {}
        self.set(code)

    def set(self, code):
        if code not in scan_langs():
            code = "en"
        self.code = code
        self.idx = BUILTIN_LANGS.index(code) if code in BUILTIN_LANGS else 0
        self.ext = read_lang_file(code)[0]


LANG = Language("en")


def tr(key, **kw):
    row = _row(key)
    text = LANG.ext.get(key)
    if text is None:
        if not row:
            return key
        text = row[LANG.idx] if LANG.idx < len(row) else row[0]
    if kw:
        try:
            text = text.format(**kw)
        except Exception:
            try:
                text = (row[0] if row else key).format(**kw)
            except Exception:
                pass
    return text


def t_en(key, **kw):
    """The same string, always in English - this is what the FILE gets."""
    row = _row(key)
    if not row:
        return key
    text = row[0]
    if kw:
        try:
            text = text.format(**kw)
        except Exception:
            pass
    return text


def export_lang_files():
    """Writes the built-in languages as Lang/<code>.txt (templates for translators)."""
    os.makedirs(LANG_DIR, exist_ok=True)
    out = []
    for i, code in enumerate(BUILTIN_LANGS):
        path = os.path.join(LANG_DIR, code + ".txt")
        with open(path, "w", encoding="utf-8", newline="\n") as fh:
            fh.write("# %s - interface texts (%s).  One text per line: key = text\n" % (APP_TITLE, code))
            fh.write("# Keep the keys and every {placeholder}; \\n is a line break; # starts a comment.\n")
            fh.write("name = %s\n" % NATIVE_LANGUAGE_NAMES.get(code, code))
            for k in STRINGS:
                row = _row(k)
                fh.write("%s = %s\n" % (k, _escape(row[i] if i < len(row) else row[0])))
        out.append(path)
    return out


# *************** DEL XX - ABOUT DIALOG (TEMPLATE) ****************************
# A TEMPLATE, not verbatim: adapt look / colours / emoji / name to the program,
# but KEEP THE MESSAGE (creator, documentation link, small gift).
# NOT for games - games never carry anything tied to me (see 40_games.md; they
# name the designers instead).
#
# Rules: About closes with ESC; Toplevel order grab_set(), focus_force(), <Escape>
# (make_modal does it).  Links open through open_url(), never webbrowser directly.
# The program NAME shown here has no "Issu" part (Issus, Issu's ...); only the
# creator line keeps Lars "Issu" Olsson.
#
# Needs:  import tkinter as tk
#         block_ui_helpers.py (make_modal)   block_open.py (open_url)
#
# Call:   show_about(root, "MyProgram", "What it is, in one line", "🏢")
# Change the colours by passing colors={...} that match the program's palette.

DOC_URL     = ("https://docs.google.com/document/d/"
               "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
REVOLUT_URL = "https://revolut.me/lars72oeh"
PAYPAL_URL  = "https://paypal.me/issusbarn"
WISE_URL    = "https://wise.com/pay/me/larsdenniso"

ABOUT_COLORS = dict(bg="#1e1e2e", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa",
                    sep="#3a3a4e", box="#252535", hover="#b4d4ff")


def show_about(root, app_name, tagline, emoji="🏢", colors=None):
    """Stylish About dialog with documentation link and donation info."""
    c = {**ABOUT_COLORS, **(colors or {})}

    top = tk.Toplevel(root)
    top.title("About " + app_name)
    top.configure(bg=c["bg"])
    top.resizable(False, False)
    top.transient(root)
    make_modal(top)                              # grab_set, focus_force, Escape

    # Header
    hdr = tk.Frame(top, bg=c["bg"])
    hdr.pack(fill="x")
    tk.Label(hdr, text=emoji, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 36)).pack(pady=(18, 0))
    tk.Label(hdr, text=app_name, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 20, "bold")).pack()
    tk.Label(hdr, text=tagline, bg=c["bg"], fg=c["dim"],
             font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20)

    # Creator
    tk.Label(top, text='Created by  Lars "Issu" Olsson', bg=c["bg"], fg=c["fg"],
             font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

    def link(parent, text, url, size=9, **pack):
        lbl = tk.Label(parent, text=text, bg=parent.cget("bg"), fg=c["accent"],
                       font=("Segoe UI", size, "underline"), cursor="hand2")
        lbl.pack(**pack)
        lbl.bind("<Button-1>", lambda e: open_url(url))
        lbl.bind("<Enter>",    lambda e: lbl.configure(fg=c["hover"]))
        lbl.bind("<Leave>",    lambda e: lbl.configure(fg=c["accent"]))
        return lbl

    link(top, "📄  View documentation", DOC_URL, pady=(6, 2))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20, pady=(14, 0))

    # Donation
    # Lars's wording since 2026-11-07 (rule 30): ENGLISH in every language
    tk.Label(top, text="Focusing on us instead of cha-ching\nbut if you like " + app_name +
                       ", you are welcome to send a token of appreciation",
             bg=c["bg"], fg=c["dim"], font=("Segoe UI", 8, "italic"),
             wraplength=300, justify="center").pack(pady=(10, 6))
    box = tk.Frame(top, bg=c["box"], padx=16, pady=10)
    box.pack(fill="x", padx=20, pady=(0, 6))
    for text, url in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL),
                      ("Wise", WISE_URL)):
        link(box, text, url, pady=1)

    tk.Button(top, text="Close", width=10, command=top.destroy).pack(pady=(8, 16))
    return top


# *************** DEL 20 - SETTINGS AND DATA FILES *****************
# ToDo: read the question aloud (the web edition does it with the browser's voice); a Windows voice would need SAPI through COMSPEC-safe code.
THEME = dict(bg="#1b2340", panel="#2b3766", fg="#ffffff", dim="#a8b4d8", accent="#ffd45e", btn="#2b3766", btnfg="#ffffff",
             field="#ffffff", field_fg="#20263a", good="#3faa78", bad="#c0392b", right="#3faa78", wrong="#c0392b")
SETTINGS_PATH = os.path.join(PROGRAM_HF_DIR, "settings.json")
ROUND = 10
D = {}      # school_data.json
TX = {}     # texts.json: English sentence -> [sv, ru]


def load_settings():
    s = {"lang": "", "order": "grade", "best": {}, "rounds": 0}
    try:
        with open(SETTINGS_PATH, encoding="utf-8") as fh:
            s.update(json.load(fh))
    except Exception:
        pass
    if not isinstance(s.get("best"), dict):
        s["best"] = {}
    return s


def save_settings(s):
    try:
        os.makedirs(PROGRAM_HF_DIR, exist_ok=True)
        with open(SETTINGS_PATH, "w", encoding="utf-8") as fh:
            json.dump(s, fh, ensure_ascii=False, indent=1)
    except Exception:
        pass


def load_data():
    """Reads the two data files.  Raises a readable error when they are missing."""
    global D, TX
    try:
        with open(os.path.join(PROGRAM_HF_DIR, "school_data.json"), encoding="utf-8") as fh:
            D = json.load(fh)
        with open(os.path.join(PROGRAM_HF_DIR, "texts.json"), encoding="utf-8") as fh:
            TX = json.load(fh)
    except Exception as e:
        raise RuntimeError("The data files school_data.json / texts.json are missing in\n%s\n(%s)" % (PROGRAM_HF_DIR, e))


# *************** DEL 21 - TEXT HELPERS (CONTENT LANGUAGE = THE PROGRAM LANGUAGE) *****************
def clang():
    return LANG.code if LANG.code in ("sv", "en", "ru") else "en"


def T(en):
    """A sentence of a generator in the content language (the key is its English text)."""
    c = clang()
    if c == "en":
        return en
    row = TX.get(en)
    if not row:
        return en
    return row[0] if c == "sv" else row[1]


def L(triple):
    """'sv¦en¦ru' (or 'sv¦ru') -> the text in the content language."""
    p = triple.split("¦")
    c = clang()
    if len(p) >= 3:
        return p[{"sv": 0, "en": 1, "ru": 2}[c]] or p[1] or p[0]
    if len(p) == 2:
        return p[1] if c == "ru" else p[0]
    return p[0]


def fmt(n):
    """A number the way people write it (decimal comma in Swedish and Russian)."""
    s = ("%.9f" % n).rstrip("0").rstrip(".") if n != int(n) else str(int(n))
    if clang() != "en":
        s = s.replace(".", ",")
    return s


def fill(tpl, *vars_):
    return re.sub(r"\{(\d+)\}", lambda m: str(vars_[int(m.group(1))]) if int(m.group(1)) < len(vars_) else m.group(0), tpl)


def rnd(x):
    return math.floor(x + 0.5)


def dec(x, d=1):
    p = 10 ** d
    return rnd(x * p) / p


def ri(a, b):
    return random.randint(a, b)


def pick(a):
    return random.choice(a)


def shuf(a):
    a = list(a)
    random.shuffle(a)
    return a


def cap(s):
    return s[:1].upper() + s[1:]


def choices_of(correct, wrongs, n=4):
    out = [str(correct)]
    for w in wrongs:
        w = str(w)
        if w not in out:
            out.append(w)
        if len(out) >= n:
            break
    return shuf(out)


# *************** DEL 22 - GENERATORS (MATHS AND SIMILAR) *****************
# Every generator is  GEN[name](grade) -> question dict:
#   text, big, pic (a tuple that draw_picture understands), kind "num" | "choice", answer, choices, unit, key
GEN = {}
SHAPES = [("circle", 0, 1), ("triangle", 3, 1), ("square", 4, 1), ("rectangle", 4, 1), ("pentagon", 5, 2), ("hexagon", 6, 2), ("octagon", 8, 3), ("rhombus", 4, 3)]
SOLIDS = [("cube", 8, 12, 6), ("cuboid", 8, 12, 6), ("square pyramid", 5, 8, 5), ("triangular prism", 6, 9, 5), ("triangular pyramid", 4, 6, 4)]
CLASSES = {"N": "noun", "V": "verb", "A": "adjective", "P": "pronoun", "R": "preposition", "D": "adverb", "C": "conjunction"}
OBJECTS = ["apples", "marbles", "stickers", "books", "pencils"]
NAMES = ["Anna", "Leo", "Mira", "Ali", "Sara", "Max"]


def lim_for(g):
    return 10 if g == 1 else (20 if random.random() < 0.5 else 100) if g == 2 else [0, 10, 100, 1000, 10000, 100000, 1000000][g]


def pair(g, sub):
    if g >= 5 and random.random() < (0.3 if g == 5 else 0.45):
        y = dec(ri(11, 999) / 10)
        x = dec(y + ri(1, 600) / 10)
        return (x, y, True) if sub else (y, dec(ri(11, 999) / 10), True)
    lim = lim_for(g)
    lo = 1 if g <= 2 else lim // 10
    if sub:
        a = ri(2, 10) if g == 1 else ri(max(lo, 5), lim)
        return a, ri(1, max(1, a - 1)), False
    a = ri(1, 9) if g == 1 else ri(max(lo, 2), lim - 1)
    b = ri(1, 10 - a) if g == 1 else ri(min(max(1, lo), max(1, lim - a)), max(1, lim - a))
    return a, b, False


def g_add(g):
    a, b, d = pair(g, False)
    return {"big": "%s + %s = ?" % (fmt(a), fmt(b)), "kind": "num", "answer": dec(a + b, 1 if d else 0), "key": "a%s+%s" % (a, b)}


def g_sub(g):
    a, b, d = pair(g, True)
    return {"big": "%s − %s = ?" % (fmt(a), fmt(b)), "kind": "num", "answer": dec(a - b, 1 if d else 0), "key": "s%s-%s" % (a, b)}


def g_half(g):
    lim = 10 if g == 1 else 50 if g == 2 else 500
    if random.random() < 0.5:
        n = ri(1, lim)
        return {"text": fill(T("What is double {0}?"), n), "kind": "num", "answer": n * 2, "key": "d%d" % n}
    n = ri(1, lim // 2) * 2
    return {"text": fill(T("What is half of {0}?"), n), "kind": "num", "answer": n // 2, "key": "h%d" % n}


def g_compare(g):
    if g <= 2:
        lim = 20 if g == 1 else 100
        a = ri(0, lim)
        b = a if random.random() < 0.15 else ri(0, lim)
    elif g == 3:
        a = ri(100, 999)
        b = a if random.random() < 0.2 else (a + ri(-30, 30) if random.random() < 0.5 else ri(100, 999))
    else:
        a = dec(ri(10, 990) / 10)
        b = a if random.random() < 0.15 else (dec(a + ri(-5, 5) / 10) if random.random() < 0.5 else dec(ri(10, 990) / 10))
        if b < 0:
            b = 1.5
    ans = "<" if a < b else ">" if a > b else "="
    return {"text": T("Which sign goes between the numbers?"), "big": "%s  ?  %s" % (fmt(a), fmt(b)), "kind": "choice", "answer": ans, "choices": ["<", "=", ">"], "key": "c%s_%s" % (a, b)}


def g_evenodd(g):
    n = ri(0, 10 * 2 if g == 1 else 100 if g == 2 else 1000)
    ev, od = T("Even"), T("Odd")
    return {"text": T("Is the number even or odd?"), "big": str(n), "kind": "choice", "answer": od if n % 2 else ev, "choices": [ev, od], "key": "e%d" % n}


def g_seq(g):
    ln, arr = 5, []
    if g == 1:
        s, f = ri(0, 20), pick([1, 1, 2, 5, 10])
        if random.random() < 0.25:
            s += f * 5
            f = -f
        arr = [s + f * i for i in range(ln)]
    elif g == 2:
        f = pick([2, 3, 4, 5, 10, 20, 25, -2, -5, -10])
        s = ri(40, 100) if f < 0 else ri(0, 40)
        arr = [s + f * i for i in range(ln)]
    elif g == 3:
        f = pick([3, 4, 6, 7, 8, 25, 50, 100, -4, -25, -50])
        s = ri(300, 900) if f < 0 else ri(0, 300)
        arr = [s + f * i for i in range(ln)]
    elif g == 4:
        f = pick([12, 15, 35, 75, 250, 500, -15, -250, 0.5, 0.25])
        s = ri(1000, 3000) if f < 0 else ri(0, 5) if f < 1 else ri(0, 500)
        arr = [dec(s + f * i, 2) for i in range(ln)]
    elif g == 5:
        if random.random() < 0.5:
            m, s = pick([2, 3]), ri(1, 4)
            arr = [s * m ** i for i in range(ln)]
        else:
            f = pick([0.5, 0.25, 1.5, 2.5, -0.5, 0.2])
            s = ri(5, 12) if f < 0 else ri(0, 9)
            arr = [dec(s + f * i, 2) for i in range(ln)]
    else:
        k = random.random()
        if k < 0.34:
            s, m = ri(1, 3), pick([2, 3, 4])
            arr = [s * m ** i for i in range(ln)]
        elif k < 0.67:
            o = ri(1, 3)
            arr = [i * i + o - 1 for i in range(1, ln + 1)]
        else:
            t, o = 0, ri(1, 5)
            for i in range(1, ln + 1):
                t += i
                arr.append(t + o - 1)
    ans = arr.pop()
    return {"text": T("What number comes last?"), "big": ",  ".join(fmt(x) for x in arr) + ",  ?", "kind": "num", "answer": ans, "key": "q" + "_".join(str(x) for x in arr)}


def g_tables(g):
    sets = {2: [2, 5, 10], 3: [2, 3, 4, 5, 6, 10], 4: [2, 3, 4, 5, 6, 7, 8, 9, 10], 5: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 6: [3, 4, 6, 7, 8, 9, 11, 12]}
    a = pick(sets[g])
    b = ri(1, 10 if g <= 3 else 12)
    c = a * b
    kind = ri(0, 9) if g >= 3 else 0
    if kind <= 5:
        return {"big": ("%d × %d" % (a, b) if random.random() < 0.5 else "%d × %d" % (b, a)) + " = ?", "kind": "num", "answer": c, "key": "t%dx%d" % (a, b)}
    if kind <= 7:
        return {"big": "%d × ?  = %d" % (a, c), "kind": "num", "answer": b, "key": "tm%dx%d" % (a, b)}
    return {"big": "%d ÷ %d = ?" % (c, a), "kind": "num", "answer": b, "key": "td%d/%d" % (c, a)}


def mulq(a, b, op="×", dd=0, key="m"):
    return {"big": "%s %s %s = ?" % (fmt(a), op, fmt(b)), "kind": "num", "answer": dec(a * b, 3) if dd else a * b, "key": "%s%s_%s" % (key, a, b)}


def g_mul(g):
    if g == 4:
        k = ri(0, 2)
        if k == 0:
            return mulq(ri(11, 99), ri(2, 9))
        if k == 1:
            return mulq(ri(12, 99), pick([10, 100]), key="mp")
        return mulq(ri(2, 9) * 10, ri(2, 9))
    k = ri(0, 4)
    if g == 5:
        if k <= 1:
            return mulq(ri(101, 999), ri(2, 9))
        if k == 2:
            return mulq(ri(11, 30), ri(11, 30))
        if k == 3:
            return mulq(dec(ri(11, 99) / 10), ri(2, 9), dd=1, key="md")
        return mulq(dec(ri(11, 99) / 10), pick([10, 100]), dd=1, key="md")
    if k <= 1:
        return mulq(ri(23, 99), ri(12, 49))
    if k == 2:
        return mulq(dec(ri(11, 999) / 100, 2), pick([10, 100, 1000]), dd=1, key="md")
    if k == 3:
        return mulq(dec(ri(2, 9) / 10), dec(ri(2, 9) / 10), dd=1, key="mdd")
    return mulq(dec(ri(12, 99) / 10), ri(3, 12), dd=1, key="md")


def whole_times(a, b, r):
    return {"text": fill(T("How many whole times does {0} fit into {1}?"), a, a * b + r), "kind": "num", "answer": b, "key": "dr%d_%d_%d" % (a, b, r)}


def divq(c, a, dd=0, key="d"):
    return {"big": "%s ÷ %s = ?" % (fmt(c), fmt(a)), "kind": "num", "answer": dec(c / a, 3) if dd else c // a, "key": "%s%s_%s" % (key, c, a)}


def g_div(g):
    if g == 3:
        a = pick([2, 3, 4, 5, 6, 10])
        return divq(a * ri(1, 10), a)
    if g == 4:
        k = ri(0, 2)
        if k == 0:
            a = ri(2, 9)
            return divq(a * ri(11, 30), a)
        if k == 1:
            a = ri(2, 9)
            return whole_times(a, ri(4, 12), ri(1, a - 1))
        a = pick([10, 100])
        b = ri(2, 99) * 10
        return {"big": "%d ÷ %d = ?" % (b * a // 10, a), "kind": "num", "answer": b // 10, "key": "dp%d_%d" % (a, b)}
    if g == 5:
        k = ri(0, 2)
        if k == 0:
            a = ri(2, 9)
            return divq(a * ri(101, 300), a)
        if k == 1:
            a = ri(3, 9)
            return whole_times(a, ri(20, 120), ri(1, a - 1))
        a = ri(11, 30)
        return divq(a * ri(11, 40), a)
    k = ri(0, 3)
    if k == 0:
        c = ri(1, 40) * 2 + 1
        return {"big": "%d ÷ 2 = ?" % c, "kind": "num", "answer": c / 2, "key": "dd%d" % c}
    if k == 1:
        return divq(dec(ri(11, 999) / 10), pick([10, 100]), dd=1, key="dp")
    if k == 2:
        return divq(ri(1, 30), pick([4, 5, 8]), dd=1, key="dq")
    a = ri(12, 40)
    return divq(a * ri(12, 90), a)


def g_place(g):
    digs = shuf([1, 2, 3, 4, 5, 6, 7, 8, 9])
    dc = ri(0, 1 if g == 5 else 2) if g >= 5 else 0
    ln = {2: 2, 3: 3, 4: 4, 5: 5, 6: 6}[g]
    ds = digs[:ln + dc]
    p = ri(0, len(ds) - 1)
    d = ds[p]
    pw = len(ds) - dc - 1 - p
    txt = ""
    for i, x in enumerate(ds):
        if dc and i == len(ds) - dc:
            txt += "." if clang() == "en" else ","
        txt += str(x)
        if not dc or i < len(ds) - dc - 1:
            left = len(ds) - dc - 1 - i
            if left > 0 and left % 3 == 0:
                txt += " "
    return {"text": fill(T("How much is the digit {0} worth in the number?"), d), "big": txt, "kind": "num", "answer": dec(d * 10 ** pw, 3), "key": "p%s%d" % (txt, d)}


ROUND_TEXT = {0.1: "Round to the nearest tenth", 1: "Round to the nearest whole number", 10: "Round to the nearest ten", 100: "Round to the nearest hundred", 1000: "Round to the nearest thousand"}


def g_round(g):
    if g == 3:
        step, n = 10, ri(11, 99)
    elif g == 4:
        step, n = pick([10, 100]), ri(101, 999)
    elif g == 5:
        step = pick([10, 100, 1000, 1])
        n = dec(ri(11, 999) / 10) if step == 1 else ri(1001, 9999)
    else:
        step = pick([100, 1000, 1, 0.1])
        n = dec(ri(11, 9999) / 100, 2) if step == 1 else dec(ri(101, 9999) / 1000, 3) if step == 0.1 else ri(10001, 99999)
    if step >= 1 and float(n).is_integer() and n % step == 0:
        n += 3
    ans = dec(rnd(n / step + 1e-9) * step, 3)
    return {"text": T(ROUND_TEXT[step]), "big": fmt(n), "kind": "num", "answer": ans, "key": "r%s_%s" % (n, step)}


def gcd(a, b):
    return a if not b else gcd(b, a % b)


def g_frac(g):
    kinds = ["pie"] if g == 3 else ["pie", "bar", "of", "of"] if g == 4 else ["pie", "of", "of", "cmp", "equiv", "add"] if g == 5 else ["of", "cmp", "equiv", "add", "dec", "cmp2"]
    kind = pick(kinds)
    if kind in ("pie", "bar"):
        n = pick([2, 3, 4, 5, 6, 8] if g == 3 else [2, 3, 4, 5, 6, 8, 10])
        k = ri(1, n - 1)
        ans = "%d/%d" % (k, n)
        wr = ["%d/%d" % (n - k, n), "%d/%d" % (k, n - k), "%d/%d" % (k + 1 if k + 1 < n else (k - 1 or 1), n), "%d/%d" % (k, n + 1), "1/%d" % n]
        wr = [w for w in wr if int(w.split("/")[1]) > 0 and int(w.split("/")[0]) * n != k * int(w.split("/")[1])]
        return {"text": T("What fraction is coloured?"), "pic": ("bar" if kind == "bar" else "pie", k, n), "kind": "choice", "answer": ans, "choices": choices_of(ans, wr), "key": "f%d_%d%s" % (k, n, kind)}
    if kind == "of":
        b = pick([2, 3, 4, 5, 10] if g == 4 else [2, 3, 4, 5, 6, 8, 10])
        a = pick([x for x in (1, 1, 1, 2, 3) if x < b]) if g == 4 else ri(1, b - 1)
        n = b * ri(1, 6 if g == 4 else 12)
        return {"text": fill(T("What is {0}/{1} of {2}?"), a, b, n), "kind": "num", "answer": n // b * a, "key": "fo%d_%d_%d" % (a, b, n)}
    if kind == "cmp":
        if random.random() < 0.5:
            b = ri(3, 12)
            c, a = b, ri(1, b - 1)
            d = ri(1, b - 1)
            while d == a:
                d = ri(1, b - 1)
        else:
            a = ri(1, 4)
            c, b = a, ri(a + 1, 10)
            d = ri(a + 1, 10)
            while d == b:
                d = ri(a + 1, 10)
        ans = "%d/%d" % (a, b) if a / b > c / d else "%d/%d" % (c, d)
        return {"text": T("Which fraction is larger?"), "kind": "choice", "answer": ans, "choices": shuf(["%d/%d" % (a, b), "%d/%d" % (c, d)]), "key": "fc%d%d%d%d" % (a, b, c, d)}
    if kind == "cmp2":
        p = pick([(1, 2, 2, 3), (1, 3, 1, 4), (2, 3, 3, 4), (3, 4, 4, 5), (1, 2, 3, 5), (2, 5, 1, 3), (5, 6, 3, 4), (3, 8, 1, 3), (4, 7, 1, 2), (5, 8, 2, 3)])
        a, b, c, d = (p[2], p[3], p[0], p[1]) if random.random() < 0.5 else p
        return {"text": T("Which fraction is larger?"), "kind": "choice", "answer": "%d/%d" % (a, b) if a / b > c / d else "%d/%d" % (c, d), "choices": shuf(["%d/%d" % (a, b), "%d/%d" % (c, d)]), "key": "fc2%d%d%d%d" % (a, b, c, d)}
    if kind == "equiv":
        b = ri(2, 6)
        a = ri(1, b - 1)
        m = ri(2, 5)
        if gcd(a, b) != 1:
            return g_frac(g)
        return {"text": T("Fill in the missing number:"), "big": "%d/%d = ?/%d" % (a, b, b * m), "kind": "num", "answer": a * m, "key": "fe%d_%d_%d" % (a, b, m)}
    if kind == "add":
        b = ri(4, 12)
        a = ri(1, b - 2)
        c = ri(1, b - a - 1 or 1)
        if a + c >= b:
            return g_frac(g)
        ans = "%d/%d" % (a + c, b)
        return {"text": T("Work out (answer as a fraction):"), "big": "%d/%d + %d/%d = ?" % (a, b, c, b), "kind": "choice", "answer": ans, "choices": choices_of(ans, ["%d/%d" % (a + c, b + b), "%d/%d" % (a + c + 1, b), "%d/%d" % (a + c - 1 or 1, b), "%d/%d" % (a, b + c)]), "key": "fa%d_%d_%d" % (a, b, c)}
    p = pick([(1, 2, 0.5), (1, 4, 0.25), (3, 4, 0.75), (1, 5, 0.2), (2, 5, 0.4), (3, 5, 0.6), (1, 10, 0.1), (7, 10, 0.7), (1, 8, 0.125), (3, 10, 0.3), (4, 5, 0.8)])
    return {"text": T("Write the fraction as a decimal:"), "big": "%d/%d = ?" % (p[0], p[1]), "kind": "num", "answer": p[2], "key": "fd%d_%d" % (p[0], p[1])}


def g_percent(g):
    p = pick([50, 25, 10, 75] if g == 5 else [50, 25, 10, 75, 20, 5, 30, 40, 60, 90])
    unit = 100 // gcd(p, 100)
    n = unit * ri(1, max(1, (200 if g == 5 else 400) // unit))
    if g == 6 and random.random() < 0.25:
        q = pick([10, 20, 25, 50, 75])
        w = (100 // gcd(q, 100)) * ri(1, 6)
        return {"text": fill(T("What percent is {0} of {1}?"), w * q // 100, w), "kind": "num", "answer": q, "unit": "%", "key": "pp%d_%d" % (q, w)}
    return {"text": fill(T("What is {0}% of {1}?"), p, n), "kind": "num", "answer": n * p / 100, "key": "pc%d_%d" % (p, n)}


def g_clock(g):
    h = ri(1, 12)
    m = pick([0, 0, 30]) if g == 1 else pick([0, 15, 30, 45]) if g == 2 else ri(0, 11) * 5 if g == 3 else ri(0, 59)

    def f(hh, mm):
        return "%d:%02d" % ((hh - 1 + 12) % 12 + 1, mm)
    ans = f(h, m)
    wr = [f(h, (m + 30) % 60), f(h % 12 + 1, m), f((h + 10) % 12 + 1, m), f(h, (m + 15) % 60), f(h, (m + 45) % 60)]
    if m % 5 == 0 and h != m // 5:
        wr.insert(0, f(12 if m == 0 else m // 5, h * 5 % 60))
    if g >= 4 and m > 0:
        wr[:0] = [f(h, m + (-1 if m > 29 else 1)), f(h, min(59, m + 5))]
    return {"text": T("What time is it?"), "pic": ("clock", h, m), "kind": "choice", "answer": ans, "choices": choices_of(ans, wr), "key": "k%d:%d" % (h, m)}


def g_money(g):
    if g <= 2:
        coins = [1, 2, 5, 10] if g == 1 else [5, 10, 20, 50, 100]
        parts = sorted([pick(coins) for _ in range(ri(2, 4 if g == 1 else 5))], reverse=True)
        return {"text": T("How much money is it?"), "big": "  +  ".join("%d kr" % x for x in parts), "kind": "num", "answer": sum(parts), "unit": "kr", "key": "$" + "+".join(str(x) for x in parts)}
    pay = pick([50, 100]) if g == 3 else pick([100, 200, 500])
    price = ri(6 if g == 3 else 11, pay - 1)
    return {"text": fill(T("You buy something for {0} kr and pay {1} kr. How much change do you get?"), price, pay), "kind": "num", "answer": pay - price, "unit": "kr", "key": "$c%d_%d" % (price, pay)}


UNITS = [("m", "cm", 100, 2, 6), ("h", "min", 60, 2, 6), ("kg", "g", 1000, 3, 6), ("l", "dl", 10, 3, 6), ("km", "m", 1000, 3, 6), ("cm", "mm", 10, 4, 6),
         ("dl", "cl", 10, 5, 6), ("min", "s", 60, 4, 6), ("l", "ml", 1000, 5, 6), ("dl", "ml", 100, 6, 6), ("hg", "g", 100, 5, 6)]


def g_units(g):
    fr, to, f, _a, _b = pick([u for u in UNITS if u[3] <= g <= u[4]])
    use_dec = g >= 5 and f >= 10 and random.random() < 0.4
    v = dec(ri(2, 99) / 10) if use_dec else ri(1, 5 if g <= 3 else 20)
    if random.random() < 0.6:
        return {"text": T("Convert:"), "big": "%s %s = ? %s" % (fmt(v), fr, to), "kind": "num", "answer": dec(v * f, 3), "unit": to, "key": "u%s%s%s" % (v, fr, to)}
    big = dec(v * f, 3)
    return {"text": T("Convert:"), "big": "%s %s = ? %s" % (fmt(big), to, fr), "kind": "num", "answer": v, "unit": fr, "key": "ur%s%s%s" % (big, to, fr)}


def g_shapes(g):
    pool = [s for s in SHAPES if s[2] <= g]
    sh = pick(pool)
    if random.random() < 0.4:
        return {"text": fill(T("How many corners does the shape “{0}” have?"), T(sh[0])), "pic": ("shape", sh[0]), "kind": "num", "answer": sh[1], "key": "sc" + sh[0]}
    ans = T(sh[0])
    return {"text": T("What is the shape called?"), "pic": ("shape", sh[0]), "kind": "choice", "answer": ans, "choices": choices_of(ans, shuf([T(x[0]) for x in pool if x is not sh])), "key": "sn" + sh[0]}


def g_solids(g):
    s = pick(SOLIDS)
    w = ri(1, 3)
    tpl = ["How many corners does the solid “{0}” have?", "How many edges does the solid “{0}” have?", "How many faces does the solid “{0}” have?"][w - 1]
    return {"text": fill(T(tpl), T(s[0])), "kind": "num", "answer": s[w], "key": "so%s%d" % (s[0], w)}


def g_perim(g):
    lim = {3: 9, 4: 15, 5: 25, 6: 40}[g]
    w, h = ri(2, lim), ri(2, lim)
    k = pick(["p"] if g == 3 else ["p", "a"] if g == 4 else ["a", "a", "t", "p"] if g == 5 else ["a", "t", "t", "side"])
    if k == "p":
        return {"text": T("What is the perimeter?"), "pic": ("rect", w, h), "kind": "num", "answer": 2 * (w + h), "unit": "cm", "key": "pr%d_%d" % (w, h)}
    if k == "a":
        return {"text": T("What is the area?"), "pic": ("rect", w, h), "kind": "num", "answer": w * h, "unit": "cm²", "key": "pa%d_%d" % (w, h)}
    if k == "t":
        b, hh = ri(2, lim // 2) * 2, ri(2, lim)
        return {"text": T("What is the area of the triangle?"), "pic": ("tri", b, hh), "kind": "num", "answer": b * hh // 2, "unit": "cm²", "key": "pt%d_%d" % (b, hh)}
    s = ri(2, 20)
    return {"text": fill(T("A square has a perimeter of {0} cm. How long is one side?"), 4 * s), "kind": "num", "answer": s, "unit": "cm", "key": "ps%d" % s}


def g_angles(g):
    if g == 6 and random.random() < 0.5:
        if random.random() < 0.5:
            a, b = ri(30, 80), ri(30, 80)
            return {"text": fill(T("Two angles of a triangle are {0}° and {1}°. How big is the third angle?"), a, b), "kind": "num", "answer": 180 - a - b, "unit": "°", "key": "at%d_%d" % (a, b)}
        a = ri(10, 80)
        return {"text": fill(T("Two angles together make a right angle. One is {0}°. How big is the other?"), a), "kind": "num", "answer": 90 - a, "unit": "°", "key": "ar%d" % a}
    deg = pick([ri(20, 80), 90, ri(100, 170), 180, ri(15, 85), ri(95, 175)])
    nm = {"a": T("acute"), "r": T("right"), "o": T("obtuse"), "s": T("straight")}
    ans = nm["a"] if deg < 90 else nm["r"] if deg == 90 else nm["o"] if deg < 180 else nm["s"]
    return {"text": T("What kind of angle is it?"), "pic": ("angle", deg), "kind": "choice", "answer": ans, "choices": shuf(list(nm.values())), "key": "ac%d" % deg}


def g_word(g):
    obj, nm = T(pick(OBJECTS)), shuf(NAMES)
    n1, n2 = T(nm[0]), T(nm[1])
    top = {2: 20, 3: 100, 4: 1000, 5: 10000, 6: 10000}[g]
    small = {2: 9, 3: 10}.get(g, 12)
    kinds = ["add", "sub", "diff"]
    if g >= 3:
        kinds += ["mul", "div", "time"]
    if g >= 4:
        kinds += ["two", "mul"]
    if g >= 5:
        kinds.append("speed")
    if g >= 6:
        kinds.append("pct")
    k = pick(kinds)
    unit = ""
    if k == "add":
        a, b = ri(top // 5, top // 2), ri(2, top // 2)
        v, ans, tpl = [a, obj, b], a + b, "There are {0} {1} on the shelf. Then {2} more are added. How many {1} are there now?"
    elif k == "sub":
        a = ri(top // 3, top)
        b = ri(2, a // 2)
        v, ans, tpl = [a, obj, b], a - b, "A basket holds {0} {1}. {2} are taken out. How many {1} are left?"
    elif k == "diff":
        a = ri(top // 3, top)
        b = ri(2, a - 1)
        v, ans, tpl = [a, b, obj, n1, n2], a - b, "{3} has {0} {2} and {4} has {1}. How many more {2} does {3} have?"
    elif k == "mul":
        a, b = ri(2, small), ri(2, 25 if g >= 4 else small)
        v, ans, tpl = [a, b, obj], a * b, "There are {0} boxes with {1} {2} in each. How many {2} are there altogether?"
    elif k == "div":
        a, b = ri(2, small), ri(2, 20 if g >= 4 else 10)
        v, ans, tpl = [a * b, obj, a], b, "{0} {1} are shared equally between {2} children. How many {1} does each child get?"
    elif k == "time":
        h = ri(1, 4)
        m = ri(1, 5) * 5 + (ri(0, 4) if g >= 4 else 0)
        v, ans, tpl = [h, m], h * 60 + m, "How many minutes is {0} hours and {1} minutes?"
    elif k == "two":
        p, n = ri(12, 95), ri(2, 5)
        pay = (p * n // 100 + 1) * 100
        v, ans, unit, tpl = [p, n, pay], pay - p * n, "kr", "A book costs {0} kr. You buy {1} books and pay with {2} kr. How much change do you get?"
    elif k == "speed":
        a, h = ri(30, 120), ri(2, 9)
        v, ans, unit, tpl = [a, h], a * h, "km", "A train travels {0} km every hour. How far does it go in {1} hours?"
    else:
        p = pick([10, 20, 25, 50])
        cls = (100 // p) * ri(1, 6)
        v, ans, tpl = [cls, p], cls * p // 100, "A class has {0} pupils. {1}% of them are girls. How many girls is that?"
    return {"text": cap(fill(T(tpl), *[fmt(x) if isinstance(x, (int, float)) else x for x in v])), "kind": "num", "answer": ans, "unit": unit, "key": "w%s%s" % (k, "_".join(str(x) for x in v))}


# ---- Swedish and nature generators
def g_alpha(g):
    A = D["alphabet"]
    lim = 10 if g == 1 else 29
    i, k = ri(1, lim - 2), ri(0, 2)
    pool = A[:12] if g == 1 else A

    def ch(x):
        return choices_of(x, shuf([p for p in pool if p != x]))
    if k == 0:
        return {"text": T("Which letter comes after?"), "big": A[i], "kind": "choice", "answer": A[i + 1], "choices": ch(A[i + 1]), "key": "an%d" % i}
    if k == 1:
        return {"text": T("Which letter comes before?"), "big": A[i], "kind": "choice", "answer": A[i - 1], "choices": ch(A[i - 1]), "key": "ap%d" % i}
    return {"text": T("Which letter is missing?"), "big": "%s  ?  %s" % (A[i - 1], A[i + 1]), "kind": "choice", "answer": A[i], "choices": ch(A[i]), "key": "am%d" % i}


def g_vowel(g):
    x = pick([a for a in D["alphabet"] if a != "W" or g > 1])
    v, c = T("vowel"), T("consonant")
    return {"text": T("Is the letter a vowel or a consonant?"), "big": x + " " + x.lower(), "kind": "choice", "answer": v if x in D["vowels"] else c, "choices": [v, c], "key": "v" + x}


def g_days(g):
    Dd, M = D["days"], D["months"]
    k, i, j = ri(0, 1 if g == 1 else 3 if g == 2 else 6), ri(0, 6), ri(0, 11)

    def ch(items, idx):
        return choices_of(items[idx], shuf([x for n, x in enumerate(items) if n != idx]))
    if k == 0:
        return {"text": fill(T("Which day comes after {0}?"), Dd[i]), "kind": "choice", "answer": Dd[(i + 1) % 7], "choices": ch(Dd, (i + 1) % 7), "key": "da%d" % i}
    if k == 1:
        return {"text": fill(T("Which day comes before {0}?"), Dd[i]), "kind": "choice", "answer": Dd[(i + 6) % 7], "choices": ch(Dd, (i + 6) % 7), "key": "db%d" % i}
    if k == 2:
        return {"text": fill(T("Which month comes after {0}?"), M[j]), "kind": "choice", "answer": M[(j + 1) % 12], "choices": ch(M, (j + 1) % 12), "key": "ma%d" % j}
    if k == 3:
        return {"text": fill(T("Which month comes before {0}?"), M[j]), "kind": "choice", "answer": M[(j + 11) % 12], "choices": ch(M, (j + 11) % 12), "key": "mb%d" % j}
    if k == 4:
        return {"text": fill(T("Which month is number {0} of the year?"), j + 1), "kind": "choice", "answer": M[j], "choices": ch(M, j), "key": "mn%d" % j}
    if k == 5:
        q = pick([("How many days are in a week?", 7), ("How many months are in a year?", 12), ("How many days does February have in a normal year?", 28), ("How many days are in a normal year?", 365), ("How many days does June have?", 30)])
        return {"text": T(q[0]), "kind": "num", "answer": q[1], "key": "dq%d" % q[1]}
    wd = ri(0, 4)
    return {"text": fill(T("It is {0}. What day is it in two days?"), Dd[wd]), "kind": "choice", "answer": Dd[wd + 2], "choices": ch(Dd, wd + 2), "key": "d2%d" % wd}


def g_wordclass(g):
    keys = ["N", "V", "A"] if g <= 4 else list(CLASSES)
    k = pick(keys)
    w = pick(D["words"][k].split(" "))
    if random.random() < 0.4:
        others = [pick(D["words"][x].split(" ")) for x in shuf([y for y in keys if y != k])[:3]]
        return {"text": fill(T("Which of the words is a {0}?"), T(CLASSES[k])), "kind": "choice", "answer": w, "choices": shuf([w] + others), "key": "wcx" + k + w}
    ans = T(CLASSES[k])
    return {"text": fill(T("What word class is “{0}”?"), w), "kind": "choice", "answer": ans, "choices": choices_of(ans, [T(CLASSES[x]) for x in shuf([y for y in keys if y != k])]), "key": "wc" + w}


def g_animals(g):
    items = []
    for line in D["animals"].strip().split("\n"):
        p = line.split("|")
        items.append((int(p[0]), p[1], p[2]))
    pool = [x for x in items if g - 2 <= x[0] <= g] or [x for x in items if x[0] <= g]
    it = pick(pool)
    keys = ["M", "B", "F", "I"] if g <= 2 else ["M", "B", "F", "I", "R", "A"] if g <= 4 else ["M", "B", "F", "I", "R", "A", "S"]
    em, nm = it[1].split(" ")[0], " ".join(it[1].split(" ")[1:])
    ans = L(D["groups"][it[2]])
    return {"text": fill(T("Which animal group does a {0} belong to?"), nm), "big": em, "kind": "choice", "answer": ans, "choices": choices_of(ans, [L(D["groups"][x]) for x in shuf([y for y in keys if y != it[2]])]), "key": "an" + it[1]}


GEN.update({"add": g_add, "sub": g_sub, "half": g_half, "compare": g_compare, "evenodd": g_evenodd, "seq": g_seq, "tables": g_tables, "mul": g_mul, "div": g_div,
            "place": g_place, "round": g_round, "frac": g_frac, "percent": g_percent, "clock": g_clock, "money": g_money, "units": g_units, "shapes": g_shapes,
            "solids": g_solids, "perim": g_perim, "angles": g_angles, "word": g_word, "alpha": g_alpha, "vowel": g_vowel, "days": g_days, "wordclass": g_wordclass,
            "animals": g_animals})


# *************** DEL 23 - TEXT BANKS (QUESTIONS FROM LINES) *****************
_BANK_CACHE = {}


def bank_items(name):
    if name not in _BANK_CACHE:
        items = []
        for line in D["banks"].get(name, "").strip().split("\n"):
            if not line:
                continue
            p = line.split("|")
            gr = p[0].split("-")
            items.append({"gmin": int(gr[0]), "gmax": int(gr[1]) if len(gr) > 1 else 6, "pr": p[1], "a": p[2], "w": [x for x in (p[3] if len(p) > 3 else "").split(";") if x]})
        _BANK_CACHE[name] = items
    return _BANK_CACHE[name]


def bank_question(tp, g):
    allit = bank_items(tp["bank"])
    pool = [i for i in allit if i["gmin"] <= g <= i["gmax"] and i["gmin"] >= g - 2]
    if len(pool) < 6:
        pool = [i for i in allit if i["gmin"] <= g <= i["gmax"]]
    if not pool:
        pool = allit
    it = pick(pool)
    swap = bool(tp.get("swap"))
    prompt, ansraw = (it["a"], it["pr"]) if swap else (it["pr"], it["a"])
    wrongs = list(it["w"])
    if tp.get("compound"):
        a, b = it["pr"].split(" + ")
        wrongs = [x for x in (b + a, a + " " + b, a + "-" + b, a + b) if x != it["a"]]
    ans = L(ansraw)
    wr = [L(x) for x in wrongs]
    if tp.get("fill", True) is not False and len(wr) < 3:
        fp = shuf([L(o["pr"] if swap else o["a"]) for o in allit if o["gmin"] <= g and o is not it])
        for x in fp:
            if len(wr) >= 3:
                break
            if x != ans and x not in wr:
                wr.append(x)
    tpl = L(tp["q"])
    vars_ = [] if tp.get("none") else [L(x) for x in prompt.split("~")]
    if tp.get("big"):
        big, text = vars_[0], tpl.replace("{0}", "").strip()
    else:
        big, text = None, fill(tpl, *vars_)
    return {"text": text, "big": big, "kind": "choice", "answer": ans, "choices": choices_of(ans, shuf(wr)), "key": "%s|%s|%s" % (tp["id"], it["pr"], it["a"])}


def make_question(tp, g):
    for _ in range(4):
        try:
            q = GEN[tp["gen"]](g) if tp.get("gen") else bank_question(tp, g)
            q.setdefault("big", None)
            q.setdefault("text", "")
            q["topic"] = tp
            if q["kind"] == "num" and not math.isfinite(q["answer"]):
                continue
            if q["kind"] == "choice" and str(q["answer"]) not in q["choices"]:
                continue
            return q
        except Exception:
            continue
    return None


def next_question(pool, g, seen):
    for _ in range(16):
        q = make_question(pick(pool), g)
        if q and q["key"] not in seen:
            seen.add(q["key"])
            return q
    return None


def topics_of(subject, g):
    return [t for t in D["topics"] if (not subject or t["subj"] == subject) and (not g or t["g"][0] <= g <= t["g"][1])]


def stars_of(pct):
    return 3 if pct >= 90 else 2 if pct >= 70 else 1 if pct >= 1 else 0


# *************** DEL 24 - PICTURES ON A CANVAS *****************
def draw_picture(cv, pic, W=300, H=190):
    """Draws a picture tuple on the canvas (the web edition draws the same things as SVG in a 200x190 box)."""
    cv.delete("all")
    s = min(W / 200.0, H / 190.0)
    ox, oy = (W - 200 * s) / 2, (H - 190 * s) / 2

    def P(x, y):
        return ox + x * s, oy + y * s

    def poly(pts, fill_c, width=4):
        flat = [c for p in pts for c in P(*p)]
        cv.create_polygon(*flat, fill=fill_c, outline="#20263a", width=width, joinstyle="round")

    def txt(x, y, t, size=14, color="#ffffff", anchor="center"):
        cv.create_text(*P(x, y), text=t, fill=color, font=("Segoe UI", int(size * s), "bold"), anchor=anchor)
    kind = pic[0]
    if kind == "clock":
        h, m = pic[1], pic[2]
        x0, y0 = P(6, 6)
        x1, y1 = P(194, 194 - 6)
        cv.create_oval(*P(6, 1), *P(194, 189), fill="#fffdf6", outline="#20263a", width=5)
        for i in range(60):
            a = i * math.pi / 30
            r1 = 80 if i % 5 == 0 else 86
            cv.create_line(*P(100 + r1 * math.sin(a), 95 - r1 * math.cos(a)), *P(100 + 90 * math.sin(a), 95 - 90 * math.cos(a)), fill="#20263a", width=3 if i % 5 == 0 else 1)
        for i in range(1, 13):
            a = i * math.pi / 6
            txt(100 + 66 * math.sin(a), 95 - 66 * math.cos(a), str(i), 15, "#20263a")
        ha, ma = ((h % 12) + m / 60.0) * math.pi / 6, m * math.pi / 30
        cv.create_line(*P(100, 95), *P(100 + 44 * math.sin(ha), 95 - 44 * math.cos(ha)), fill="#20263a", width=max(4, int(8 * s)), capstyle="round")
        cv.create_line(*P(100, 95), *P(100 + 68 * math.sin(ma), 95 - 68 * math.cos(ma)), fill="#c0392b", width=max(3, int(5 * s)), capstyle="round")
        cv.create_oval(*P(94, 89), *P(106, 101), fill="#20263a", outline="")
    elif kind == "pie":
        k, n = pic[1], pic[2]
        for i in range(n):
            a0, a1 = -90 + i * 360.0 / n, -90 + (i + 1) * 360.0 / n
            cv.create_arc(*P(20, 15), *P(180, 175), start=-a1, extent=a1 - a0, fill="#ff7043" if i < k else "#fff3e0", outline="#20263a", width=3, style="pieslice")
    elif kind == "bar":
        k, n = pic[1], pic[2]
        for i in range(n):
            cv.create_rectangle(*P(10 + i * 180.0 / n, 55), *P(10 + (i + 1) * 180.0 / n, 125), fill="#ff7043" if i < k else "#fff3e0", outline="#20263a", width=3)
    elif kind == "shape":
        sid = pic[1]
        if sid == "circle":
            cv.create_oval(*P(28, 23), *P(172, 167), fill="#ff8a65", outline="#20263a", width=5)
        elif sid == "square":
            poly([(30, 25), (170, 25), (170, 165), (30, 165)], "#81c784", 5)
        elif sid == "rectangle":
            poly([(15, 45), (185, 45), (185, 145), (15, 145)], "#ffd54f", 5)
        elif sid == "rhombus":
            poly([(100, 15), (180, 95), (100, 175), (20, 95)], "#aed581", 5)
        else:
            n, rot, col = {"triangle": (3, -math.pi / 2, "#4fc3f7"), "pentagon": (5, -math.pi / 2, "#ba68c8"), "hexagon": (6, 0, "#4db6ac"), "octagon": (8, math.pi / 8, "#f06292")}[sid]
            poly([(100 + 72 * math.cos(rot + i * 2 * math.pi / n), 95 + 72 * math.sin(rot + i * 2 * math.pi / n)) for i in range(n)], col, 5)
    elif kind == "rect":
        w, h = pic[1], pic[2]
        sc = min(125.0 / w, 100.0 / h)
        rw, rh = w * sc, h * sc
        x, y = 12 + (125 - rw) / 2, (150 - rh) / 2 + 5
        cv.create_rectangle(*P(x, y), *P(x + rw, y + rh), fill="#bbdefb", outline="#20263a", width=4)
        txt(x + rw / 2, y - 10, "%d cm" % w, 16)
        txt(x + rw + 8, y + rh / 2, "%d cm" % h, 16, anchor="w")
    elif kind == "tri":
        b, h = pic[1], pic[2]
        poly([(20, 140), (180, 140), (120, 25)], "#c8e6c9", 4)
        cv.create_line(*P(120, 25), *P(120, 140), fill="#c0392b", width=3, dash=(6, 4))
        txt(100, 160, "%d cm" % b, 16)
        txt(126, 88, "%d cm" % h, 16, anchor="w")
    elif kind == "angle":
        deg = pic[1]
        vx, vy, Ln = 40, 140, 130
        rad = math.radians(deg)
        cv.create_line(*P(vx, vy), *P(vx + Ln, vy), fill="#ffffff", width=6, capstyle="round")
        cv.create_line(*P(vx, vy), *P(vx + Ln * math.cos(rad), vy - Ln * math.sin(rad)), fill="#ffffff", width=6, capstyle="round")
        if deg == 90:
            cv.create_line(*P(vx + 22, vy), *P(vx + 22, vy - 22), *P(vx, vy - 22), fill="#ff6b5a", width=3)
        elif deg < 180:
            cv.create_arc(*P(vx - 34, vy - 34), *P(vx + 34, vy + 34), start=0, extent=deg, style="arc", outline="#ff6b5a", width=3)


# *************** DEL 25 - SELF TEST (--selftest, no window) *****************
def selftest(languages=("sv", "en", "ru"), per=120):
    """Every topic x every year x every content language: no crash, answers present, no leftovers like {0} / NaN."""
    load_data()
    bad, count = 0, 0
    src = open(os.path.abspath(__file__), encoding="utf-8").read()
    for m in re.finditer(r"\bT\(\"((?:[^\"\\]|\\.)*)\"\)", src):
        en = m.group(1).replace("\\u201c", "“").replace("\\u201d", "”")
        if en not in TX and not en.startswith("%"):
            print("MISSING TRANSLATION:", en)
            bad += 1
    for lang in languages:
        LANG.code = lang
        for tp in D["topics"]:
            for g in range(tp["g"][0], tp["g"][1] + 1):
                for _ in range(per):
                    q = make_question(tp, g)
                    count += 1
                    where = "%s/%s/%d" % (lang, tp["id"], g)
                    if not q:
                        print("NO QUESTION", where)
                        bad += 1
                        continue
                    blob = " ".join([q["text"] or "", q["big"] or "", str(q["answer"])] + list(q.get("choices") or []))
                    if re.search(r"undefined|NaN|\{\d\}|None", blob) or not (q["text"] or q["big"] or q.get("pic")):
                        print("BAD TEXT", where, blob)
                        bad += 1
                    if q["kind"] == "choice" and (len(set(q["choices"])) != len(q["choices"]) or str(q["answer"]) not in q["choices"] or not 2 <= len(q["choices"]) <= 4):
                        print("BAD CHOICES", where, q["choices"], q["answer"])
                        bad += 1
                    if q["kind"] == "num" and len(str(q["answer"])) > 12:
                        print("FLOAT", where, q["answer"])
                        bad += 1
    LANG.code = "en"
    print("selftest: %d questions, %d problems" % (count, bad))
    return 1 if bad else 0


# *************** DEL 26 - THE WINDOW *****************
class App(object):
    def __init__(self, root):
        self.root = root
        self.S = load_settings()
        if not self.S.get("lang") or self.S["lang"] not in LANGS:
            self.S["lang"] = "sv" if "sv" in LANGS else "en"
        LANG.set(self.S["lang"])
        self.pick = {"grade": 0, "subject": ""}
        self.timer = None
        self.round = None
        self.playtext = None
        root.title(APP_NAME)
        root.configure(bg=THEME["bg"])
        root.geometry("940x720")
        root.resizable(False, False)
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        root.bind("<Key>", self.on_key)
        self.fonts = dict(big=("Segoe UI", 26, "bold"), mid=("Segoe UI", 18, "bold"), norm=("Segoe UI", 12), small=("Segoe UI", 10))
        self.build_shell()
        self.show_home()

    # ---- shell: the top bar stays, the body is swapped
    def build_shell(self):
        for w in self.root.winfo_children():
            w.destroy()
        bar = tk.Frame(self.root, bg=THEME["panel"], height=48)
        bar.pack(fill="x")
        bar.pack_propagate(False)
        tk.Label(bar, text="\U0001F393  " + tr("title"), bg=THEME["panel"], fg=THEME["accent"], font=("Segoe UI", 15, "bold")).pack(side="left", padx=14)
        self.btn(bar, tr("about"), lambda: show_about(self.root, APP_NAME, "Practise school things, year by year", "\U0001F393"), 9).pack(side="right", padx=(2, 12), pady=8)
        self.btn(bar, tr("help"), self.show_help, 9).pack(side="right", padx=2, pady=8)
        self.btn(bar, tr("notes"), self.open_notes, 18).pack(side="right", padx=2, pady=8)
        make_language_picker(bar, LANGS, lambda: LANG.code, self.set_language, bg=THEME["panel"], fg=THEME["fg"]).pack(side="right", padx=10)
        self.body = tk.Frame(self.root, bg=THEME["bg"])
        self.body.pack(fill="both", expand=True)

    def set_language(self, code):
        LANG.set(code)
        self.S["lang"] = code
        save_settings(self.S)
        self.stop_round()
        self.build_shell()
        self.show_home()

    def btn(self, parent, text, cmd, width=None, bg=None, fg=None, font=None, **kw):
        return tk.Button(parent, text=text, command=cmd, width=width, bg=bg or THEME["btn"], fg=fg or THEME["btnfg"], activebackground=THEME["accent"],
                         activeforeground="#20263a", relief="flat", bd=0, font=font or self.fonts["norm"], cursor="hand2", **kw)

    def clear_body(self):
        self.cancel_timer()
        for w in self.body.winfo_children():
            w.destroy()

    def cancel_timer(self):
        if self.timer:
            try:
                self.root.after_cancel(self.timer)
            except Exception:
                pass
            self.timer = None

    def stop_round(self):
        self.cancel_timer()
        self.round = None

    # ---- the first page
    def first_done(self):
        return self.pick["grade"] if self.S["order"] == "grade" else self.pick["subject"]

    def second_done(self):
        return self.pick["subject"] if self.S["order"] == "grade" else self.pick["grade"]

    def show_home(self):
        self.stop_round()
        self.clear_body()
        o, P = self.S["order"], self.pick
        box = tk.Frame(self.body, bg=THEME["bg"])
        box.pack(fill="both", expand=True, padx=24, pady=14)
        first, second = self.first_done(), self.second_done()
        top = tk.Frame(box, bg=THEME["bg"], height=44)
        top.pack(fill="x")
        top.pack_propagate(False)
        if not first:
            tk.Label(top, text=tr("first"), bg=THEME["bg"], fg=THEME["dim"], font=self.fonts["norm"]).pack(side="left")
            for key, label in (("grade", tr("by_grade")), ("subject", tr("by_subject"))):
                self.btn(top, label, lambda k=key: self.set_order(k), 12, bg=THEME["accent"] if o == key else None, fg="#20263a" if o == key else None).pack(side="left", padx=6)
        else:
            self.btn(top, "◀  " + tr("back"), self.home_back, 10).pack(side="left")
            tk.Label(top, text=tr("chosen") + ":", bg=THEME["bg"], fg=THEME["dim"], font=self.fonts["norm"]).pack(side="left", padx=10)
            if P["grade"]:
                self.btn(top, tr("grade_n", n=P["grade"]) + "  ✕", lambda: self.clear_pick("grade"), None, bg=THEME["accent"], fg="#20263a").pack(side="left", padx=4)
            if P["subject"]:
                sj = next(s for s in D["subjects"] if s["id"] == P["subject"])
                self.btn(top, sj["icon"] + " " + L(sj["name"]) + "  ✕", lambda: self.clear_pick("subject"), None, bg=THEME["accent"], fg="#20263a").pack(side="left", padx=4)
        if not first:
            self.grade_grid(box) if o == "grade" else self.subject_grid(box)
        elif not second:
            self.subject_grid(box) if o == "grade" else self.grade_grid(box)
        else:
            self.topic_list(box)

    def set_order(self, k):
        self.S["order"] = k
        save_settings(self.S)
        self.show_home()

    def clear_pick(self, which):
        self.pick[which] = 0 if which == "grade" else ""
        self.show_home()

    def home_back(self):
        P = self.pick
        if self.second_done():
            P["subject" if self.S["order"] == "grade" else "grade"] = "" if self.S["order"] == "grade" else 0
        elif self.first_done():
            P["grade" if self.S["order"] == "grade" else "subject"] = 0 if self.S["order"] == "grade" else ""
        self.show_home()

    def heading(self, parent, text):
        tk.Label(parent, text=text, bg=THEME["bg"], fg=THEME["accent"], font=self.fonts["mid"], anchor="w").pack(fill="x", pady=(10, 8))

    def grade_grid(self, box):
        self.heading(box, tr("pick_grade"))
        gr = tk.Frame(box, bg=THEME["bg"])
        gr.pack(fill="x")
        for g in range(1, 7):
            n = len(topics_of(self.pick["subject"], g)) if self.pick["subject"] else 0
            sub = tr("n_topics", n=n) if self.pick["subject"] else tr("year")
            b = tk.Button(gr, text="%d\n%s" % (g, sub), command=lambda g=g: self.choose_grade(g), width=16, height=3, bg=THEME["btn"], fg=THEME["accent"],
                          activebackground=THEME["accent"], relief="flat", font=("Segoe UI", 16, "bold"), cursor="hand2",
                          state="disabled" if self.pick["subject"] and n == 0 else "normal")
            b.grid(row=(g - 1) // 3, column=(g - 1) % 3, padx=8, pady=8)

    def subject_grid(self, box):
        self.heading(box, tr("pick_subject"))
        gr = tk.Frame(box, bg=THEME["bg"])
        gr.pack(fill="x")
        for i, s in enumerate(D["subjects"]):
            n = len(topics_of(s["id"], self.pick["grade"]))
            b = tk.Button(gr, text="%s  %s\n%s" % (s["icon"], L(s["name"]), tr("n_topics", n=n)), command=lambda s=s: self.choose_subject(s["id"]), width=30, height=3,
                          bg=THEME["btn"], fg=THEME["fg"], activebackground=THEME["accent"], relief="flat", font=("Segoe UI", 14, "bold"), cursor="hand2",
                          state="disabled" if n == 0 else "normal")
            b.grid(row=i // 2, column=i % 2, padx=8, pady=8)

    def choose_grade(self, g):
        self.pick["grade"] = g
        self.show_home()

    def choose_subject(self, s):
        self.pick["subject"] = s
        self.show_home()

    def topic_list(self, box):
        self.heading(box, tr("pick_topic"))
        wrap = tk.Frame(box, bg=THEME["bg"])
        wrap.pack(fill="both", expand=True)
        cv = tk.Canvas(wrap, bg=THEME["bg"], highlightthickness=0)
        sb = tk.Scrollbar(wrap, orient="vertical", command=cv.yview)
        inner = tk.Frame(cv, bg=THEME["bg"])
        inner.bind("<Configure>", lambda e: cv.configure(scrollregion=cv.bbox("all")))
        cv.create_window((0, 0), window=inner, anchor="nw", width=860)
        cv.configure(yscrollcommand=sb.set)
        cv.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        cv.bind("<Enter>", lambda e: cv.bind_all("<MouseWheel>", lambda ev: cv.yview_scroll(-1 * (ev.delta // 120), "units")))
        cv.bind("<Leave>", lambda e: cv.unbind_all("<MouseWheel>"))
        P = self.pick
        topics = topics_of(P["subject"], P["grade"])

        def row(icon, name, best_key, cmd):
            best = self.S["best"].get(best_key, 0)
            st = stars_of(best)
            text = "%s   %s" % (icon, name)
            f = tk.Frame(inner, bg=THEME["btn"])
            f.pack(fill="x", pady=3)
            b = tk.Button(f, text=text, command=cmd, anchor="w", bg=THEME["btn"], fg=THEME["fg"], activebackground=THEME["accent"], activeforeground="#20263a",
                          relief="flat", font=("Segoe UI", 14, "bold"), cursor="hand2", padx=14, pady=8)
            b.pack(side="left", fill="x", expand=True)
            tk.Label(f, text="★" * st + "☆" * (3 - st) + ("  %d %%" % best if best else ""), bg=THEME["btn"], fg=THEME["accent"], font=self.fonts["norm"], width=16, anchor="e").pack(side="right", padx=10)
        if len(topics) > 1:
            row("\U0001F3B2", tr("mixed"), "mix_%s_%d" % (P["subject"], P["grade"]), lambda: self.begin(topics, P["grade"], True))
        for tp in topics:
            row(tp["icon"], L(tp["name"]), "%s_%d" % (tp["id"], P["grade"]), lambda tp=tp: self.begin([tp], P["grade"], False))

    # ---- a round
    def begin(self, topics, g, mixed):
        seen, queue = set(), []
        for _ in range(ROUND):
            q = next_question(topics, g, seen)
            if not q and len(queue) >= 4:
                break
            if not q:
                q = make_question(random.choice(topics), g)
            if q:
                queue.append({"q": q, "retry": False, "miss": False})
        self.round = {"topics": topics, "g": g, "mixed": mixed, "subject": self.pick["subject"], "queue": queue, "total": max(1, len(queue)), "resolved": 0, "first_ok": 0,
                      "cur": None, "answered": False, "typed": ""}
        self.build_quiz()
        self.show_question()

    def build_quiz(self):
        self.clear_body()
        R = self.round
        head = tk.Frame(self.body, bg=THEME["bg"])
        head.pack(fill="x", padx=18, pady=(10, 0))
        self.btn(head, "◀  " + tr("back"), self.show_home, 10).pack(side="left")
        title = tr("grade_n", n=R["g"]) + "  ·  " + (L(next(s for s in D["subjects"] if s["id"] == R["subject"])["name"]) if R["mixed"] else L(R["topics"][0]["name"]))
        tk.Label(head, text=title, bg=THEME["bg"], fg=THEME["fg"], font=self.fonts["mid"]).pack(side="left", padx=16)
        self.lbl_count = tk.Label(head, text="", bg=THEME["bg"], fg=THEME["dim"], font=self.fonts["norm"])
        self.lbl_count.pack(side="right")
        self.bar = tk.Canvas(self.body, height=10, bg=THEME["panel"], highlightthickness=0)
        self.bar.pack(fill="x", padx=18, pady=(8, 0))
        main = tk.Frame(self.body, bg=THEME["bg"])
        main.pack(fill="both", expand=True, padx=18, pady=8)
        left = tk.Frame(main, bg=THEME["bg"], width=560)
        left.pack(side="left", fill="both")
        left.pack_propagate(False)
        self.right = tk.Frame(main, bg=THEME["bg"], width=330)
        self.right.pack(side="right", fill="both")
        self.right.pack_propagate(False)
        self.lbl_q = tk.Label(left, text="", bg=THEME["bg"], fg=THEME["fg"], font=("Segoe UI", 17, "bold"), wraplength=540, justify="center", height=3)
        self.lbl_q.pack(fill="x")
        self.pic = tk.Canvas(left, width=540, height=250, bg=THEME["bg"], highlightthickness=0)
        self.pic.pack()
        self.lbl_msg = tk.Label(left, text="", bg=THEME["bg"], fg=THEME["fg"], font=("Segoe UI", 15, "bold"), wraplength=540, height=2)
        self.lbl_msg.pack(fill="x", pady=(6, 0))
        self.btn_next = continue_button(left, tr("next"), self.next_clicked, bg=THEME["good"], fg="#ffffff", activebackground=THEME["accent"], relief="flat", bd=0,
                                        font=("Segoe UI", 16, "bold"), width=18, height=1, cursor="hand2", state="disabled")
        self.btn_next.pack(pady=6)

    def show_question(self):
        R = self.round
        if not R:
            return
        if not R["queue"]:
            self.finish()
            return
        item = R["queue"][0]
        q = item["q"]
        R["cur"], R["answered"], R["typed"] = item, False, ""
        self.lbl_count.config(text=tr("count", i=min(R["resolved"] + 1, R["total"]), n=R["total"]) + (("  ·  " + tr("again")) if item["retry"] else ""))
        self.draw_bar()
        self.lbl_q.config(text=q["text"] or "")
        self.lbl_msg.config(text="", fg=THEME["fg"])
        self.btn_next.config(state="disabled")
        cv = self.pic
        cv.delete("all")
        if q.get("pic"):
            draw_picture(cv, q["pic"], 540, 250)
        elif q.get("big"):
            b = q["big"]
            emoji = len(b) <= 6 and any(ord(ch) > 0x2000 for ch in b)
            size = 80 if emoji else 34 if len(b) <= 26 else 22 if len(b) <= 60 else 16
            cv.create_text(270, 125, text=b, fill=THEME["accent"] if not emoji else THEME["fg"], font=("Segoe UI Emoji" if emoji else "Segoe UI", size, "bold"), width=520, justify="center")
        for w in self.right.winfo_children():
            w.destroy()
        self.choice_btns, self.val = [], None
        if q["kind"] == "choice":
            for i, c in enumerate(q["choices"]):
                b = tk.Button(self.right, text=c, command=lambda c=c, i=i: self.pick_choice(c, i), bg=THEME["btn"], fg=THEME["fg"], activebackground=THEME["accent"], activeforeground="#20263a",
                              relief="flat", font=("Segoe UI", 17, "bold"), wraplength=300, cursor="hand2")
                b.place(x=0, y=i * 78, width=330, height=68)
                self.choice_btns.append(b)
        else:
            row = tk.Frame(self.right, bg=THEME["bg"])
            row.place(x=0, y=0, width=330, height=62)
            self.val = tk.Label(row, text="?", bg=THEME["field"], fg="#9aa3bf", font=("Segoe UI", 28, "bold"), width=9)
            self.val.pack(side="left", pady=2)
            if q.get("unit"):
                tk.Label(row, text=q["unit"], bg=THEME["bg"], fg=THEME["accent"], font=("Segoe UI", 18, "bold")).pack(side="left", padx=8)
            keys = ["7", "8", "9", "4", "5", "6", "1", "2", "3", "," if (q["answer"] != int(q["answer"]) or R["g"] >= 5) else "", "0", "⌫"]
            for i, k in enumerate(keys):
                if k:
                    tk.Button(self.right, text=k, command=lambda k=k: self.key_press(k), bg=THEME["btn"], fg=THEME["fg"], activebackground=THEME["accent"], relief="flat",
                              font=("Segoe UI", 20, "bold"), cursor="hand2").place(x=(i % 3) * 112, y=72 + (i // 3) * 62, width=106, height=56)
            tk.Button(self.right, text=tr("ok"), command=self.submit, bg=THEME["good"], fg="#ffffff", activebackground=THEME["accent"], relief="flat",
                      font=("Segoe UI", 18, "bold"), cursor="hand2").place(x=0, y=72 + 4 * 62, width=330, height=58)

    def draw_bar(self):
        R = self.round
        self.bar.update_idletasks()
        w = self.bar.winfo_width() or 900
        self.bar.delete("all")
        self.bar.create_rectangle(0, 0, w * R["resolved"] / float(R["total"]), 10, fill=THEME["good"], outline="")

    def key_press(self, k):
        R = self.round
        if not R or R["answered"]:
            return
        if k == "⌫":
            R["typed"] = R["typed"][:-1]
        elif k == ",":
            if "," not in R["typed"]:
                R["typed"] += "," if R["typed"] else "0,"
        elif len(R["typed"]) < 9:
            R["typed"] = k if R["typed"] == "0" else R["typed"] + k
        if self.val is not None:
            self.val.config(text=R["typed"] or "?", fg="#20263a" if R["typed"] else "#9aa3bf")

    def submit(self):
        R = self.round
        if not R or R["answered"] or not R["typed"]:
            return
        q = R["cur"]["q"]
        try:
            v = float(R["typed"].replace(",", "."))
        except ValueError:
            return
        self.judge(abs(v - q["answer"]) < 1e-6, fmt(q["answer"]) + ((" " + q["unit"]) if q.get("unit") else ""), None)

    def pick_choice(self, c, i):
        R = self.round
        if not R or R["answered"]:
            return
        self.judge(c == str(R["cur"]["q"]["answer"]), str(R["cur"]["q"]["answer"]), i)

    def judge(self, ok, shown, idx):
        R = self.round
        item = R["cur"]
        q = item["q"]
        R["answered"] = True
        if q["kind"] == "choice":
            for i, b in enumerate(self.choice_btns):
                b.config(state="disabled", disabledforeground="#ffffff")
                if b.cget("text") == str(q["answer"]):
                    b.config(bg=THEME["right"])
                elif i == idx:
                    b.config(bg=THEME["wrong"])
        elif self.val is not None:
            self.val.config(bg=THEME["right"] if ok else THEME["wrong"], fg="#ffffff")
        if ok:
            self.root.bell() if False else None
            self.lbl_msg.config(text=random.choice(tr("praise").split("|")), fg="#7ee0a8")
            if not item["retry"] and not item["miss"]:
                R["first_ok"] += 1
            R["resolved"] += 1
            R["queue"].pop(0)
            self.cancel_timer()
            self.timer = self.root.after(850, self.after_correct)
        else:
            self.lbl_msg.config(text=tr("wrong", a=shown), fg="#ff9a8a")
            R["queue"].pop(0)
            if not item["retry"]:
                item["retry"] = item["miss"] = True
                R["queue"].append(item)
            else:
                R["resolved"] += 1
            self.btn_next.config(state="normal")
            self.btn_next.focus_set()
        self.draw_bar()

    def after_correct(self):
        self.timer = None
        self.show_question()

    def next_clicked(self):
        R = self.round
        if R and R["answered"]:
            self.cancel_timer()
            self.show_question()

    def on_key(self, ev):
        R = self.round
        if not R or R["cur"] is None or R["answered"] or self.playtext_has_focus():
            return
        q = R["cur"]["q"]
        if q["kind"] == "num":
            if ev.char and ev.char in "0123456789":
                self.key_press(ev.char)
            elif ev.char in (",", "."):
                self.key_press(",")
            elif ev.keysym == "BackSpace":
                self.key_press("⌫")
            elif ev.keysym in ("Return", "KP_Enter"):
                self.submit()
        elif ev.char and ev.char in "1234" and int(ev.char) <= len(self.choice_btns):
            self.choice_btns[int(ev.char) - 1].invoke()

    def playtext_has_focus(self):
        try:
            w = self.root.focus_get()
            return w is not None and w.winfo_class() in ("Text", "Entry", "TCombobox")
        except Exception:
            return False

    def finish(self):
        R = self.round
        key = ("mix_%s_%d" % (R["subject"], R["g"])) if R["mixed"] else "%s_%d" % (R["topics"][0]["id"], R["g"])
        pct = int(round(100.0 * R["first_ok"] / R["total"]))
        if pct > self.S["best"].get(key, 0):
            self.S["best"][key] = pct
        self.S["rounds"] = self.S.get("rounds", 0) + 1
        save_settings(self.S)
        st = stars_of(pct)
        topics, g, mixed = R["topics"], R["g"], R["mixed"]
        for w in self.right.winfo_children():
            w.destroy()
        self.pic.delete("all")
        self.pic.create_text(270, 70, text="★" * st + "☆" * (3 - st), fill=THEME["accent"], font=("Segoe UI", 54, "bold"))
        self.lbl_q.config(text=tr("win", n=R["first_ok"], t=R["total"]))
        self.lbl_msg.config(text="")
        self.btn_next.config(state="disabled")
        self.btn(self.right, tr("play_again"), lambda: self.begin(topics, g, mixed), None, bg=THEME["good"], font=("Segoe UI", 18, "bold")).place(x=0, y=20, width=330, height=64)
        self.btn(self.right, tr("to_menu"), self.show_home, None, font=("Segoe UI", 18, "bold")).place(x=0, y=100, width=330, height=64)
        self.round["cur"] = None

    # ---- help, notes, closing
    def show_help(self):
        top = tk.Toplevel(self.root)
        top.title(tr("help"))
        top.configure(bg=THEME["bg"])
        top.resizable(False, False)
        top.transient(self.root)
        make_modal(top)
        txt = new_text(top, wrap="word", width=70, height=22, bg=THEME["panel"], fg=THEME["fg"], font=("Segoe UI", 11), relief="flat", padx=12, pady=10)
        txt.insert("1.0", tr("help_text"))
        txt.config(state="disabled")
        txt.pack(padx=14, pady=(14, 8))
        self.btn(top, tr("close"), top.destroy, 12).pack(pady=(0, 14))

    def open_notes(self):
        if self.playtext is not None:
            try:
                if self.playtext.top.winfo_exists():
                    self.playtext.top.lift()
                    return
            except Exception:
                pass

        def closed():
            self.playtext = None
        self.playtext = PlayerTextPopup(
            self.root, self.S, ("show_playtext", "playtext_pos", "playtext_zoom", "playtext_sel"), lambda: save_settings(self.S),
            dict(bg=THEME["bg"], panel=THEME["panel"], fg=THEME["fg"], dim=THEME["dim"], accent=THEME["accent"], btn=THEME["btn"], btnfg=THEME["btnfg"],
                 field=THEME["panel"], field_fg=THEME["fg"]),
            tr("notes"), PROGRAM_HF_DIR, lambda: {}, on_closed=closed)

    def on_close(self):
        try:
            if self.playtext is not None:
                self.playtext.save_now()
        except Exception:
            pass
        save_settings(self.S)
        self.root.destroy()


# *************** DEL 27 - MAIN *****************
def main():
    if "--export-lang" in sys.argv[1:]:
        for p in export_lang_files():
            print(p)
        return 0
    if "--selftest" in sys.argv[1:]:
        return selftest()
    _set_app_id()
    try:
        load_data()
    except RuntimeError as e:
        r = tk.Tk()
        r.withdraw()
        from tkinter import messagebox
        messagebox.showerror(APP_NAME, str(e))
        return 1
    root = tk.Tk()
    App(root)
    root.after(0, lambda: _set_window_icon(root))
    root.mainloop()
    return 0


if __name__ == "__main__":
    sys.exit(main())
