# -*- coding: utf-8 -*-
"""
kalender.py
SmartHub module + Standalone: Calendar with events and notes.
- Standalone:  python kalender.py
- Module:      place the file next to main.py and launch via the hub.

Features:
- Monthly calendar with week numbers and public holidays (Sweden / UK / Russia).
- Click a day to view / edit notes.
- Events with time and reminder.
- E-mail address stored locally.
- Birthdays and personal anniversaries read live from BirthdayTracker's own
  file, Helpfiles/BirthdayTracker/persons.json - one file, one owner.
- No blinking cursors (insertofftime=0, insertontime=9999999).
- All data is saved in Helpfiles/kalender/
- Log is saved in Helpfiles/logs/
"""

# ToDo
# ----
# [x] 2026-09-05  Read birthdays and per-person events straight out of
#     BirthdayTracker's persons.json instead of keeping a second list of
#     people here. The file is only ever READ - BirthdayTracker stays its
#     owner - and it is re-read whenever its timestamp changes, so a person
#     added while the Calendar is open shows up on the next redraw.
# [x] 2026-09-05  Header toggle "🎂 Birthdays" (remembered between sessions)
#     so the layer can be turned off without losing the link.
# [x] 2026-09-05  Second toggle "✨ Extras", DEFAULT ON, adding the busy
#     stuff on top: day-count and age milestones, Swedish name days, and
#     mini-birthdays.
# [x] 2026-09-05  The grid used to be as wide as its text, so switching a
#     layer on or off RESIZED the whole calendar. It now takes the space it
#     is given - the canvas window follows the canvas in both directions and
#     every cell is measured from that, so the layout never moves again and a
#     lot more text fits.
# [x] 2026-09-05  A day with more than fits opens a popup on click (and any
#     day on double-click), where it has all the room it needs.
# [x] 2026-11-19  Phone sync (DEL 40 + DEL 41): the dicts stay the truth, CalCore mirrors them with ids / change times / reminders and
#     syncs through the CalendarApp relay with the app "Issu's Calendar" (events, day notes; birthdays go one way). Events can now be
#     CHANGED and DELETED (day window: pencil / bin) and carry several reminders (at the time, 10 min, 30 min, 1 h, 1 day before).
#     Checked by test_kalender_sync.py (core) - the window itself and the real server are not checked by a program.
# [x] 2026-11-20  Calendar 1.1: REPEATING events (day / week / month / year, every N, last day, delete one day / this and the following /
#     all) as ONE record with a "rp" field; quiet reminders ("qt": notification only on the phone).  Repeats are held back until the
#     relay says "v": 2 (an old relay would drop them).  Week view and agenda exist on the phone only.
# [x] 2026-11-24  Calendar 1.2: SEVERAL PEOPLE on one calendar, half separate (DEL 42 + relay version 3).  Every person has an own key
#     and pairing code (made under  👥 People ); every event says who sees it (only me / everybody / chosen people) and, optionally, who it
#     is about; the relay only sends a person what they may see.  Others' events cannot be changed, only left out or given own reminders.
#     Checked by test_kalender_sync.py (PeopleCase) and the relay tests; the windows and a real phone are not checked by a program.
# [x] 2026-11-24  Calendar 1.3 (phone only): 📷 photograph a paper with an appointment, circle the time / place / comment one at a time, the text
#     is read on the phone (ML Kit) and the event window opens filled in (who it is about, who sees it).  This program keeps the place and
#     comment of such events and shows them; it changes nothing else for 1.3.
# [x] 2026-11-24  Calendar 1.4 (Lars: "why must I share everything?"): NOTHING is shared by default.  Birthdays (BirthdayTracker) are shared ONE
#     PERSON AT A TIME (People > Share birthdays…, or Share… next to a birthday in the day window); the old single "all birthdays" choice is
#     gone (every birthday is back to "only me" until chosen).  "Everybody" = EVERYBODY on the calendar, whenever they were added (Lars:
#     "ALLA = ALLA"); the maker can leave single people out:  Everybody  + "except: Leo"  (audience "a!leo").  Everybody can leave out what
#     others made (✖ here, long-press on the phone, also for birthdays).
# [ ] ToDo: several weekdays in one weekly repeat (Mon+Wed+Fri) is not supported.
# [ ]            BirthdayTracker has no concept of a death date; entries
#     recorded as a person ("Mor dog") are therefore drawn like any other
#     anniversary. A "deceased" flag belongs in BirthdayTracker, not here.

import sys, json, logging
import ctypes, platform, webbrowser                      # FIX: top-level imports
from pathlib import Path
from datetime import datetime, timedelta
import calendar

import tkinter as tk
from tkinter import ttk, messagebox
import holidays
import os
import sys
import shutil
import subprocess


# ---- Where Helpfiles and Icons live -----------------------------------------
# Helpfiles is a SIBLING of the program's folder, not a child of it, so the
# answer is "the nearest folder above me that holds Helpfiles". One rule covers
# Py\, Folder-exe\<Name>\ and the old layout alike, so it stops mattering
# where the .py or the .exe is put. Capped at four levels so a stray Helpfiles
# far up the tree is not adopted by accident; nothing found means behave as
# before, which is what keeps a test copy away from live data.
def _find_home(start):
    # Py\ and Folder-exe\<Name>\ are ALWAYS direct children of home, so
    # their own name settles it. This runs BEFORE the walk: a stray
    # Helpfiles inside Py\ used to win the walk and silently became every
    # program's home - that is how Notes lost a day (2026-09-04).
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    if os.path.basename(os.path.dirname(start)).lower() == "folder-exe":
        return os.path.dirname(os.path.dirname(start))
    # Otherwise: the nearest folder above me that HAS a Helpfiles. Capped at
    # four levels so a stray one far up is not adopted by accident; nothing
    # found means behave as before, which keeps a test copy off live data.
    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
    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 checks for this before offering the swap


# *************** DEL XX - OPEN THINGS WITH MY OWN PROGRAMS *******************
# A link, a folder, a PDF, a log or an image opened from here should land in MY
# programs - not in Edge, Explorer, Notepad or Adobe.
#
# Registering them as Windows' default apps is possible but miserable, and
# Windows identifies an application by its .exe PATH: point every file type at
# pythonw.exe and Windows sees ONE app called "Python" for all of them, with
# one icon, and Default Apps cannot tell WhyBrowse from F(re)email.
#
# WHICH program opens WHAT is NOT decided here.  It is decided in one file,
#
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
#
# so changing "PDFs open in X instead of PDFull" is one edit in one place, not
# 122 edits in 122 sources.  This block only reads that table and acts on it.
# _FALLBACK_KINDS below is used only when the file cannot be read, so a
# program still works on a machine that has no DefaultHub.
#
# Three rules this block must never break:
#
#   1. It may never raise.  The Help button has to open even when WhyBrowse is
#      missing, broken, or mid-rebuild, and even when defaults.json is gone.
#   2. It may never hand a thing to ITSELF (File_manager opening a folder,
#      WhyBrowse opening a link) - that is how you build a loop.
#   3. Popen, never run().  run() would freeze this program until the browser
#      is closed again.
#
# NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it would start another copy of this program instead of Python.
# (PyManager did exactly that on 2026-09-04 and fork-bombed the machine.)
#
# Cost, measured 2026-09-05: the table is read ONCE, the first time something
# is actually opened - 0.11 ms cold, 0.05 ms warm, plus 0.04 ms of path
# checks.  Nothing is read at start-up, so start-up is not affected at all.

MY_PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False) else __file__))[0]

# 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 others: a music program
    lives in <root>\\1---Musik\\Py so its 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 it walks
    UP, exactly like _find_home, four levels."""
    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) - it is
    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 ""


_HUB_PY_ROOTS = None


def _hub_py_roots() -> list:
    """The program folders DefaultHub names, or [] meaning "find them yourself".

    EMPTY IS THE DEFAULT AND IT IS THE RIGHT ONE.  An absolute path in a data
    file is the first thing to break when the tree moves to another drive -
    which it did on 2026-09-08, C: to X:.  Nothing else in this block holds a
    drive letter: _find_home walks up from __file__, and the table stores only
    NAMES ("SeeView"), so a move costs nothing.  A list of absolute paths here
    would be the one file that has to be edited every time, and that is exactly
    what this design is for avoiding.

    So a RELATIVE entry ("1---Musik\\Py") is the intended shape: it is
    resolved against every root in _py_folders, and it survives the move too.
    An absolute one is still honoured - it is his tree - but it is on him."""
    global _HUB_PY_ROOTS
    if _HUB_PY_ROOTS is not None:
        return _HUB_PY_ROOTS
    found = []
    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:
                    found = (json.load(fh) or {}).get("py_roots") or []
                break
        except Exception:
            pass                       # unreadable or half-written: automatic
    try:
        _HUB_PY_ROOTS = [str(x).strip() for x in found if str(x).strip()]
    except Exception:
        _HUB_PY_ROOTS = []
    return _HUB_PY_ROOTS


def _py_folders() -> list:
    """Every folder that may hold <Name>.py, nearest first.

    DefaultHub's list first, then the plain <root>\\Py that has always been
    searched.  With no list this is exactly the old behaviour, which is why
    "empty means automatic" costs nothing."""
    out, roots = [], _my_app_roots()
    for entry in _hub_py_roots():
        try:
            if os.path.isabs(entry):
                out.append(entry)
            else:
                for r in roots:
                    out.append(os.path.join(r, entry))
        except Exception:
            continue
    for r in roots:
        out.append(os.path.join(r, "Py"))
    seen, uniq = set(), []
    for d in out:
        try:
            key = os.path.normcase(os.path.abspath(d))
            if key not in seen and os.path.isdir(d):
                seen.add(key)
                uniq.append(d)
        except Exception:
            continue
    return uniq


def _program_candidates(name: str) -> list:
    """Every file that could BE that program, best first.

    ALL the .py folders are searched before ANY build.  The old loop asked
    "script or exe?" one tree at a time, so a stale build in a near tree beat
    the live source in a further one - the very thing "the .py wins" exists to
    prevent."""
    out = []
    for d in _py_folders():
        try:
            p = os.path.join(d, name + ".py")
            if os.path.isfile(p):
                out.append(p)
        except Exception:
            continue
    for root in _my_app_roots():
        try:
            e = os.path.join(root, "Folder-exe", name, name + ".exe")
            if os.path.isfile(e):
                out.append(e)
        except Exception:
            continue
    return out


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

    THE .PY WINS, and a build is only the fallback.  The .exe used to be
    preferred, which was wrong on every count:

      * it is not faster - a one-folder build and the .py start in about the
        same time (the ten-times difference was one-FILE builds);
      * it does not help the hand-over - both bind the same port, so a
        running copy takes the argument whichever one is started;
      * and it is the only thing that can be OUT OF DATE.  A build from last
        week does not have this week's source in it, so preferring it means
        quietly running old code.  That is exactly what happened on
        2026-09-05: File_manager's build was a day old and had no command
        line handling at all, so "open this folder" would have opened a
        second window and dropped the path.

    WHERE it looks is DefaultHub's business now, not this block's - see
    _py_folders - so his music programs and the own worlds under 1---Annat
    can be named as targets like anything else.

    subprocess and webbrowser MUST be imported at module level for this to
    work.  They were not, in 57 of 121 programs, and because every call site
    sits inside a bare `except Exception` the failure was completely silent:
    the program simply stopped handing files to his own programs and dropped
    them all on Windows.  That is what made "Save & Open" open nothing at all
    on 2026-09-09, and it left no trace anywhere."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    for path in _program_candidates(name):
        cmd = None
        if path.lower().endswith(".py"):
            pyw = _real_pythonw()
            if pyw:
                cmd = [pyw, path, str(argument)]
            # no interpreter on this machine: try the build instead
        else:
            cmd = [path, str(argument)]
        if not cmd:
            continue
        try:
            subprocess.Popen(cmd, cwd=os.path.dirname(path) or None)
            return True
        except Exception:
            continue                      # try the next candidate
    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


# -----------------------------------------------------------------------------


# ── SmartHub metadata ──────────────────────────────────────────────────────────
WANT_HUB_DIR = True
MODULE_NAME  = "kalender"
MENU_LABEL   = "Calendar"
MENU_GROUP   = "Tools"
MENU_POS     = "auto"
APP_TITLE    = "Calendar"

# ── Directories ────────────────────────────────────────────────────────────────
APP_DIR    = Path(_program_home())
HELP_DIR   = APP_DIR / "Helpfiles"
DATA_DIR   = HELP_DIR / "kalender"
LOG_DIR    = HELP_DIR / "logs"

for _d in (DATA_DIR, LOG_DIR):
    _d.mkdir(parents=True, exist_ok=True)

EVENTS_PATH = DATA_DIR / "kalender-events.json"
NOTES_PATH  = DATA_DIR / "kalender-notes.json"
EMAIL_PATH  = DATA_DIR / "kalender-email.txt"
CFG_PATH    = DATA_DIR / "kalender-settings.json"
SYNC_PATH   = DATA_DIR / "kalender-sync.json"      # the mirror with ids + change times (DEL 40); if it is lost it is rebuilt and identical events are matched up again
RELAY_PATH  = DATA_DIR / "relay.json"              # {"url": "...", "key": "..."}  the phone-sync server; PRIVATE (holds the key)
LOG_PATH    = LOG_DIR  / "kalender.log"

# BirthdayTracker's own data, read here but never written. Both programs work
# out their home with the same _find_home rule, so this is literally the file
# Day-stalker.py opens - not a copy that has to be kept in step.
BT_DIR          = HELP_DIR / "BirthdayTracker"
BT_PERSONS_PATH = BT_DIR / "persons.json"

# ── Logging ────────────────────────────────────────────────────────────────────
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler(str(LOG_PATH), encoding="utf-8"),
        logging.StreamHandler(sys.stdout),
    ],
)
logger = logging.getLogger(APP_TITLE)

# ── No-blink helper ────────────────────────────────────────────────────────────
def no_blink(w):
    try:
        w.configure(insertofftime=0, insertontime=9_999_999)
    except Exception:
        pass

# ── Settings ───────────────────────────────────────────────────────────────────
DEFAULT_CFG = {"geometry": "1000x700",
               "show_birthdays": True,
               "show_extras": True}

def load_cfg():
    if CFG_PATH.exists():
        try:
            data = json.loads(CFG_PATH.read_text(encoding="utf-8"))
            for k, v in DEFAULT_CFG.items():
                data.setdefault(k, v)
            return data
        except Exception:
            pass
    return DEFAULT_CFG.copy()

def save_cfg(cfg):
    try:
        CFG_PATH.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
    except Exception:
        logger.exception("Could not save settings.")


# *************** DEL 01 - BIRTHDAYTRACKER LINK *******************************
# The Calendar keeps no list of people of its own. Birthdays and per-person
# anniversaries come out of the file BirthdayTracker (Day-stalker.py) owns:
# Helpfiles/BirthdayTracker/persons.json. Read-only, always - add or correct a
# person over there and it shows up here on the next redraw, with no second
# copy to drift out of step.
#
# Two layers, two toolbar checkboxes:
#
#   🎂 Birthdays (ON by default) - what is plainly IN the file: birth_date
#     (annual) and each person's events[] list ({"name":..., "date":...}).
#
#   ✨ Extras (ON by default) - the derived stuff on top: day-count
#     milestones, round-number age milestones, Swedish name days and
#     mini-birthdays. A busy day no longer costs anything: the cells are
#     measured from the window, not from their text, and whatever still does
#     not fit is one click away in the day's own window.
#
# The maths below is deliberately the same as BirthdayTracker's, so the two
# programs can never disagree about a date - see the comment on each helper.

_BT_CACHE = {"stamp": None, "persons": []}

# ── Swedish name-day almanac ──────────────────────────────────────────────────
# A copy of BirthdayTracker's _ND_LIST, taken verbatim on 2026-09-13 when
# both tables were rebuilt from Svenska Akademiens namnlängd (2022).
# Day-stalker.py stays the master: this is an almanac, not data, so there is no
# shared file to read it from the way persons.json is read. One string per
# month, the days separated by ";" in order, several names on a day separated
# by "," and an empty slot where the almanac has no name (1 Jan and 2 Feb).
# February holds 29 days; the 29th is only ever asked for in a leap year.
_ND_MONTHS = (
    ';Svea;Alfred,Alfrida;Rut;Hanna,Hannele;Kasper,Melker,Baltsar;August,Augusta;Erland;Gunnar,Gunder;Sigurd,Sigbritt;Jan,Jannike;Frideborg,Fridolf;Knut;Felix,Felicia;Laura,Lorentz;Hjalmar,Helmer;Anton,Tony;Hilda,Hildur;Henrik,Henry;Fabian,Sebastian;Agnes,Agneta;Vincent,Viktor;Frej,Freja;Erika;Paul,Pål;Bodil,Boel;Göte,Göta;Karl,Karla;Diana;Gunilla,Gunhild;Ivar,Joar',
    'Max,Maximilian;;Disa,Hjördis;Ansgar,Anselm;Agata,Agda;Dorotea,Doris;Rikard,Dick;Berta,Bert;Fanny,Franciska;Iris;Yngve,Inge;Evelina,Evy;Agne,Ove;Valentin;Sigfrid;Julia,Julius;Alexandra,Sandra;Frida,Fritiof;Gabriella,Ella;Vivianne;Hilding;Pia;Torsten,Torun;Mattias,Mats;Sigvard,Sivert;Torgny,Torkel;Lage;Maria,Maja;',
    'Albin,Elvira;Ernst,Erna;Gunborg,Gunvor;Adrian,Adriana;Tora,Tove;Ebba,Ebbe;Camilla;Siv,Saga;Torbjörn,Torleif;Edla,Ada;Edvin,Egon;Viktoria,Regina;Greger;Matilda,Maud;Kristoffer,Christel;Herbert,Gilbert;Gertrud;Edvard,Edmund;Josef,Josefina;Joakim,Kim;Bengt;Kennet,Kent;Gerda,Gerd;Gabriel,Rafael;;Emanuel;Rudolf,Ralf;Malkolm,Morgan;Jonas,Jens;Holger,Holmfrid;Ester,Noa',
    'Harald,Hervor;Gudmund,Ingemund;Ferdinand,Nanna;Marianne,Marlene;Irene,Irja;Vilhelm,William;Irma,Irmelin;Nadja,Tanja;Otto,Ottilia;Ingvar,Ingvor;Ulf,Ylva;Liv;Artur,Douglas;Tiburtius;Olivia,Oliver;Patrik,Patricia;Elias,Elis;Valdemar,Volmar;Olaus,Ola;Amalia,Amelie;Anneli,Annika;Allan,Glenn;Georg,Göran;Vega;Markus;Teresia,Terese;Engelbrekt;Ture,Tyra;Tyko;Mariana',
    'Valborg;Filip,Filippa;John,Jane;Monika,Mona;Gotthard,Erhard;Marit,Rita;Carina,Carita;Åke;Reidar,Reidun;Esbjörn,Styrbjörn;Märta,Märit;Charlotta,Lotta;Linnea,Linn;Halvard,Halvar;Sofia,Sonja;Ronald,Ronny;Rebecka,Ruben;Erik;Maj,Majken;Karolina,Carola;Konstantin,Conny;Hemming,Henning;Desideria,Desirée;Ivan,Vanja;Urban;Vilhelmina,Vilma;Beda,Blenda;Ingeborg,Borghild;Yvonne,Jeanette;Vera,Veronika;Petronella,Pernilla',
    'Gun,Gunnel;Rutger,Roger;Ingemar,Gudmar;Solbritt,Solveig;Bo;Gustav,Gösta;Robert,Robin;Eivor,Majvor;Börje,Birger;Svante,Boris;Bertil,Berthold;Eskil;Aina,Aino;Håkan,Hakon;Margit,Margot;Axel,Axelina;Torborg,Torvald;Björn,Bjarne;Germund,Görel;Linda;Alf,Alvar;Paulina,Paula;Adolf,Alice;;David,Salomon;Rakel,Lea;Selma,Fingal;Leo;Peter,Petra;Elof,Leif',
    'Aron,Mirjam;Rosa,Rosita;Aurora;Ulrika,Ulla;Laila,Ritva;Esaias,Jessika;Klas;Kjell;Jörgen,Örjan;André,Andrea;Eleonora,Ellinor;Herman,Hermine;Joel,Judit;Folke;Ragnhild,Ragnvald;Reinhold,Reine;Bruno;Fredrik,Fritz;Sara;Margareta,Greta;Johanna;Magdalena,Madeleine;Emma,Emmy;Kristina,Kerstin;Jakob;Jesper,Jasmine;Marta;Botvid,Seved;Olof,Olle;Algot;Helena,Elin',
    'Per;Karin,Kajsa;Tage;Arne,Arnold;Ulrik,Alrik;Alfons,Inez;Dennis,Denise;Silvia,Sylvia;Roland;Lars;Susanna;Klara;Kaj;Uno;Stella,Estelle;Brynolf;Verner,Valter;Ellen,Lena;Magnus,Måns;Bernhard,Bernt;Jon,Jonna;Henrietta,Henrika;Signe,Signhild;Bartolomeus;Lovisa,Louise;Östen;Rolf,Raoul;Fatima,Leila;Hans,Hampus;Albert,Albertina;Arvid,Vidar',
    'Samuel,Sam;Justus,Justina;Alfhild,Alva;Gisela;Adela,Heidi;Lilian,Lilly;Kevin,Roy;Alma,Hulda;Anita,Annette;Tord,Turid;Dagny,Helny;Åsa,Åslög;Sture;Ida,Ronja;Sigrid,Siri;Dag,Daga;Hildegard,Magnhild;Orvar;Fredrika;Elise,Lisa;Matteus;Maurits,Moritz;Tekla,Tea;Gerhard,Gert;Tryggve;Enar,Einar;Dagmar,Rigmor;Lennart,Leonard;Mikael,Mikaela;Helge',
    'Ragnar,Ragna;Ludvig,Love;Evald,Osvald;Frans,Frank;Bror;Jenny,Jennifer;Birgitta,Britta;Nils;Ingrid,Inger;Harry,Harriet;Erling,Jarl;Valfrid,Manfred;Berit,Birgit;Stellan;Hedvig,Hillevi;Finn;Antonia,Toini;Lukas;Tore,Tor;Sibylla;Ursula,Yrsa;Marika,Marita;Severin,Sören;Evert,Eilert;Inga,Ingalill;Amanda,Rasmus;Sabina;Simon,Simone;Viola;Elsa,Isabella;Edit,Edgar',
    ';Tobias,Tim;Hubert,Hugo;Sverker;Eugen,Eugenia;Gustav Adolf;Ingegerd,Ingela;Vendela;Teodor,Teodora;Martin,Martina;Mårten;Konrad,Kurt;Kristian,Krister;Emil,Emilia;Leopold;Vibeke,Viveka;Naemi,Naima;Lillemor,Moa;Elisabet,Lisbet;Pontus,Marina;Helga,Olga;Cecilia,Sissela;Klemens;Gudrun,Rune;Katarina,Katja;Linus;Astrid,Asta;Malte;Sune;Andreas,Anders',
    'Oskar,Ossian;Beata,Beatrice;Lydia,Cornelia;Barbara,Barbro;Sven;Nikolaus,Niklas;Angela,Angelika;Virginia;Anna;Malin,Malena;Daniel,Daniela;Alexander,Alexis;Lucia;Sten,Sixten;Gottfrid;Assar;Stig;Abraham;Isak;Israel,Moses;Tomas;Natanael,Jonatan;Adam;Eva;;Stefan,Staffan;Johannes,Johan;Benjamin;Natalia,Natalie;Abel,Set;Sylvester',
)

_ND_BY_NAME = {}     # "erika" -> [(month, day), ...]

def _build_namedays():
    """Unpack _ND_MONTHS into a name -> dates lookup.

    A row of the wrong length would silently shift every name after it by a
    day, so each one is measured against the real month first; a bad table is
    dropped whole rather than shown wrong.
    """
    for m, row in enumerate(_ND_MONTHS, start=1):
        cells = row.split(";")
        if len(cells) != calendar.monthrange(2024, m)[1]:   # 2024 = leap year
            logger.error(f"Name-day table: month {m} has {len(cells)} days, "
                         f"expected {calendar.monthrange(2024, m)[1]} - table dropped")
            _ND_BY_NAME.clear()
            return
        for d, cell in enumerate(cells, start=1):
            for n in cell.split(","):
                if n:
                    _ND_BY_NAME.setdefault(n.lower(), []).append((m, d))

_build_namedays()

# ── Milestones ────────────────────────────────────────────────────────────────
# Both lists copied from BirthdayTracker for the same reason as the almanac.
_BT_DAY_MILESTONES = (
    100, 200, 300, 365, 400, 500, 600, 700, 730, 800, 900,
    1_000, 1_111, 1_234, 1_500, 2_000, 2_222, 2_345, 2_500,
    3_000, 3_333, 3_456, 4_000, 4_321, 4_444, 4_567,
    5_000, 5_555, 5_678, 6_000, 6_666, 6_789,
    7_000, 7_777, 7_890, 8_000, 8_888, 9_000, 9_999,
    10_000, 10_101, 11_111, 12_000, 12_345,
    13_000, 14_000, 15_000, 16_000, 17_000, 18_000, 19_000,
    20_000, 21_000, 22_000, 22_222, 23_000, 24_000, 25_000,
    26_000, 27_000, 28_000, 29_000, 30_000,
)
_BT_AGE_MILESTONES = (
    1, 2, 3, 5, 10, 13, 16, 18, 20, 21, 25,
    30, 40, 50, 60, 65, 70, 75, 80, 85, 90, 95, 100, 110,
)

# Which mark wins the two lines a day cell has room for. Keyed on the leading
# symbol of the text, which is what identifies the kind of mark.
_MARK_RANK = {"🎂": 0, "★": 1, "🏆": 2, "⭐": 3, "⏳": 4, "💜": 5}


def _bt_parse_date(s):
    """BirthdayTracker accepts both 'YYYY-MM-DD' and 'YYYYMMDD'; so do we."""
    s = str(s or "").strip()
    for fmt in ("%Y-%m-%d", "%Y%m%d"):
        try:
            return datetime.strptime(s, fmt).date()
        except ValueError:
            pass
    return None


def _bt_name(person):
    """The name BirthdayTracker itself shows: preferred name wins."""
    for key in ("preferred_name", "first_name", "last_name"):
        v = str(person.get(key, "")).strip()
        if v:
            return v
    return "?"


def _bt_persons():
    """persons.json, re-read only when the file has actually changed.

    BirthdayTracker may well be open at the same time, so the cache is keyed on
    (mtime, size) rather than being read once at start-up. A missing or broken
    file is not an error here - it just means there is nothing to draw.
    """
    try:
        st = BT_PERSONS_PATH.stat()
        stamp = (st.st_mtime_ns, st.st_size)
    except OSError:
        _BT_CACHE["stamp"], _BT_CACHE["persons"] = None, []
        return []

    if stamp != _BT_CACHE["stamp"]:
        try:
            data = json.loads(BT_PERSONS_PATH.read_text(encoding="utf-8"))
            persons = data.get("persons", []) if isinstance(data, dict) else list(data)
        except Exception:
            logger.exception("Could not read BirthdayTracker persons.json")
            persons = []
        _BT_CACHE["stamp"]   = stamp
        _BT_CACHE["persons"] = persons
        logger.info(f"BirthdayTracker: {len(persons)} person(s) read from "
                    f"{BT_PERSONS_PATH}")
    return _BT_CACHE["persons"]


def _anniversary_in(original, year, month):
    """The date in (year, month) on which `original` recurs, or None.

    29 February falls back to the 28th in a non-leap year - the same rule
    BirthdayTracker's next_occurrence() uses, so the two never disagree.
    """
    if original is None or original.month != month or year < original.year:
        return None
    try:
        return original.replace(year=year)
    except ValueError:
        return original.replace(year=year, day=28)


def _bt_all_names(person):
    """Every name to try in the almanac: preferred, first, then each middle
    name, comma-split, de-duplicated. Same order as BirthdayTracker's
    all_person_names(), so both programs find the same name days."""
    names = []
    for key in ("preferred_name", "first_name"):
        v = str(person.get(key, "")).strip()
        if v and v not in names:
            names.append(v)
    for part in str(person.get("middle_names", "")).split(","):
        v = part.strip()
        if v and v not in names:
            names.append(v)
    return names


def _add_months(d, months):
    """d + months, clamped to the last day of the target month - a copy of
    BirthdayTracker's add_months(), which is what mini-birthdays are built on."""
    m    = d.month - 1 + months
    year = d.year + m // 12
    mon  = m % 12 + 1
    return d.replace(year=year, month=mon,
                     day=min(d.day, calendar.monthrange(year, mon)[1]))


def _extra_marks(p, name, born, year, month, add):
    """The ✨ Extras layer for one person: milestones, name days, mini-birthdays.

    None of this is stored anywhere - it is worked out from the same
    persons.json fields BirthdayTracker uses, with BirthdayTracker's own
    arithmetic, so the two programs can never name different dates.
    """
    if born:
        # A round-number age, on the birthday itself
        bday = _anniversary_in(born, year, month)
        if bday and (year - born.year) in _BT_AGE_MILESTONES:
            add(bday, f"🏆 {name} {year - born.year} yr")

        # Day counts: born + N days, exactly as BirthdayTracker counts them.
        # Past ones are drawn too - this is a calendar, so browsing back to
        # the month someone turned 10 000 days old should show it.
        for count in _BT_DAY_MILESTONES:
            md = born + timedelta(days=count)
            if md.year == year and md.month == month:
                add(md, f"⭐ {name} {count:,} d".replace(",", " "))

        # Mini-birthdays: every 1 / 3 / 6 months from the date of birth. A
        # multiple of 12 months IS the birthday, already drawn above, so it is
        # not repeated here.
        interval = str(p.get("mini_birthday") or "").strip()
        if interval in ("1", "3", "6"):
            interval   = int(interval)
            months_old = (year - born.year) * 12 + (month - born.month)
            if months_old > 0 and months_old % interval == 0 and months_old % 12:
                add(_add_months(born, months_old), f"⏳ {name} {months_old} mo")

    # Name days - every name the person answers to
    for nm in _bt_all_names(p):
        for nd_month, nd_day in _ND_BY_NAME.get(nm.lower(), []):
            if nd_month != month:
                continue
            try:
                add(datetime(year, month, nd_day).date(), f"💜 {name}")
            except ValueError:      # 29 February in a non-leap year
                pass


def bt_person_key(p):
    """The stable key of a BirthdayTracker person (its id; an old file without ids falls back to the name)."""
    return str(p.get("id") or "").strip() or ("name:" + _bt_name(p))


def bt_marks_for_month(year, month, base=True, extras=False, who=None):
    """{date: [text, ...]} for the given month, straight from persons.json.

    The two layers are independent, one per toolbar checkbox, so ticking either
    one on its own does what it says rather than quietly needing the other.
    who = an empty dict that is filled with {(date, text): person key}: whose line it is (for sharing one person at a time).
    """
    marks = {}
    if not (base or extras):
        return marks
    cur = [""]

    def add(d, text):
        row = marks.setdefault(d, [])
        if text not in row:     # two of a person's names can share one day
            row.append(text)
        if who is not None:
            who.setdefault((d, text), cur[0])

    for p in _bt_persons():
        cur[0] = bt_person_key(p)
        name = _bt_name(p)
        born = _bt_parse_date(p.get("birth_date"))

        if base:
            bday = _anniversary_in(born, year, month)
            if bday:
                add(bday, f"🎂 {name} {year - born.year}")

            for ev in (p.get("events") or []):
                when  = _bt_parse_date(ev.get("date"))
                title = str(ev.get("name", "")).strip()
                ev_day = _anniversary_in(when, year, month) if title else None
                if ev_day:
                    add(ev_day, f"★ {name}: {title} {year - when.year}")

        if extras:
            _extra_marks(p, name, born, year, month, add)

    # Birthdays first, then anniversaries, then the extras: a day cell has room
    # for two lines, and the one that gets dropped should be a name day, never
    # the birthday. sort() is stable, so persons.json order survives within a
    # rank.
    for row in marks.values():
        row.sort(key=lambda t: _MARK_RANK.get(t.split(" ", 1)[0], 9))

    return marks
# *************** END DEL 01 **************************************************


# ── Tiny tooltip ───────────────────────────────────────────────────────────────
def attach_tooltip(widget, text, delay=500):
    """A steady hint under a widget. Nothing here blinks, fades or animates."""
    state = {"after": None, "win": None}

    def hide(_e=None):
        if state["after"] is not None:
            try:
                widget.after_cancel(state["after"])
            except Exception:
                pass
            state["after"] = None
        if state["win"] is not None:
            try:
                state["win"].destroy()
            except Exception:
                pass
            state["win"] = None

    def show():
        state["after"] = None
        if state["win"] is not None or not widget.winfo_exists():
            return
        win = tk.Toplevel(widget)
        win.wm_overrideredirect(True)
        win.wm_geometry(f"+{widget.winfo_rootx() + 8}"
                        f"+{widget.winfo_rooty() + widget.winfo_height() + 4}")
        tk.Label(win, text=text, justify="left",
                 background="#ffffe0", foreground="black",
                 relief="solid", borderwidth=1,
                 font=("Segoe UI", 8), padx=6, pady=3).pack()
        state["win"] = win

    def enter(_e=None):
        hide()
        state["after"] = widget.after(delay, show)

    # add="+" throughout: bind() REPLACES, and a plain bind here would quietly
    # remove whatever the widget already listens for.
    widget.bind("<Enter>",    enter, add="+")
    widget.bind("<Leave>",    hide,  add="+")
    widget.bind("<Button-1>", hide,  add="+")


# ── Window icon ────────────────────────────────────────────────────────────────
def _set_window_icon(root) -> None:
    """Set taskbar + title-bar icon. Must be called via root.after(0, ...)."""
    if platform.system() != "Windows":
        return
    ico_path = str(APP_DIR / "Icons" / "Kalender.ico")
    import os
    if not os.path.isfile(ico_path):
        return

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

    # Channel 2: WM_SETICON via Win32
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        hwnd = user32.FindWindowW(None, root.title())   # FindWindowW, not winfo_id()
        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 40 - PHONE SYNC CORE (no tkinter here; checked by test_kalender_sync.py) *****************
# The Calendar keeps its two dicts exactly as before (self.events: {"YYYY-MM-DD": ["HH:MM text", ...]}, self.notes: {"YYYY-MM-DD": "text"}),
# and they stay the TRUTH.  CalCore is a MIRROR of them with what a sync needs: a stable id, a change time "u" (ms), the reminders, and a
# tombstone for a deleted record.  reconcile() finds what changed by comparing the dicts with the mirror (so an edit made by hand in the
# json file is noticed as well); apply_remote() writes what came from the phone back into the dicts.  Last change wins, per record.
# The server side is relay\calendar_relay.py (CalendarApp), the phone side is the app "Issu's Calendar"; the record layout is described there:
#     {"k": "e"|"n"|"b", "d": "YYYY-MM-DD", "t": "HH:MM", "x": "text", "r": [minutes before], "u": ms, "z": 1 = deleted}
# k "e" = event, k "n" = the note of a day, k "b" = birthdays etc. of a day (sent from here to the phone, never taken back).
# Version 1.1 adds two OPTIONAL fields on events (an old record without them is a plain event with loud reminders):
#     "qt": [minutes]   the reminders (a subset of "r") that are only a quiet notification on the phone, not the loud alarm
#     "rp": {"f": "d"|"w"|"m"|"y", "i": every N (default 1), "e": "YYYY-MM-DD" last day, "x": ["YYYY-MM-DD", ...] deleted occurrences}
#           the event REPEATS; "d" is its first occurrence and is never one of "x".  A repeating event is ONE record (and ONE string in the
#           events dict, on its first day): the other days are drawn from the rule (CalCore.occurrences_on), nothing is stored per day.
# The relay only keeps these fields from its version 2 on (its answer has "v": 2).  Until it has said so, a repeating event is NOT sent
# (an old relay would throw the repeat away and the phone would later overwrite the series with a plain event).
# Version 1.2 / relay version 3: SEVERAL PEOPLE on one calendar, half separate.  Every person has an own key (made by the owner, see
# show_people_dialog); the relay says who a key is ("me") and who the others are ("people": {id: name}).  New optional fields:
#     "o"  who made the record (set by the relay)       "v"  who SEES the event: "a" = everybody, or [person ids]; none = only its maker
#     "w"  [names] who the event is ABOUT (free text)   "pl" place   "cm" comment (both are made by the photo flow of the phone, version 1.3)
#     kind "m" record  id "m-<me>-<event id>"  {"ev": id, "hid": 1, "r": [..], "qt": [..]}  = MY OWN settings for somebody else's event:
#           left out of my calendar (hid) and/or my own reminders.  Private to me; it travels between my own PC and phone only.
# Somebody else's event is shown in the day list and the grid (blue) but can only be left out or given own reminders, never changed.
# Nothing of version 3 is sent before the relay has said "v": 3 (an older relay would drop the fields and the event would stay private for ever).
import re
import hashlib
import time as _time
import secrets
import base64
import threading
import queue
import urllib.request
import urllib.error

SYNC_APP = "kalender"
OWNER_ID = "owner"                                     # the person of the owner key (the relay's name for it)
DEFAULT_REMIND = [0]                                 # an event rings at its time unless told otherwise (what the PC always did)
REMIND_CHOICES = [(0, "At the time"), (10, "10 min before"), (30, "30 min before"),
                  (60, "1 hour before"), (1440, "1 day before")]
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
_EV_RE = re.compile(r"^(\d{1,2}):(\d{2})[ \t]+(.*)$", re.S)


def ev_parse(s):
    """'HH:MM text' -> ('HH:MM', 'text'), or None when the string does not start with a valid time (such a string is kept, never synced)."""
    m = _EV_RE.match(s or "")
    if not m:
        return None
    h, mi = int(m.group(1)), int(m.group(2))
    if h > 23 or mi > 59:
        return None
    return "%02d:%02d" % (h, mi), m.group(3)


def ev_string(t, x):
    return "%s %s" % (t, x)


class SyncError(Exception):
    """A problem that can be shown to the user as it is."""


# ----- the repeat rule (the same rules as Ev.java on the phone)
# Weekly = the weekday of the first day, monthly = its day of the month (a short month uses its last day), yearly = its month + day
# (29 February becomes 28 February in other years).  Every N days / weeks / months / years.
from datetime import date as _date
REPEAT_FREQ = ("d", "w", "m", "y")
REPEAT_NAMES = {"d": "day", "w": "week", "m": "month", "y": "year"}
MAX_EXCLUDED = 300


def _pd(s):
    """'YYYY-MM-DD' -> date (ValueError when it is not one)."""
    return datetime.strptime(str(s), "%Y-%m-%d").date()


def _add_months_clamped(d, n):
    y, m = divmod(d.year * 12 + (d.month - 1) + n, 12)
    m += 1
    return _date(y, m, min(d.day, calendar.monthrange(y, m)[1]))


def rp_nth(start, rp, n):
    """The n-th occurrence (0 = the first), ignoring the end day and the deleted ones.  OverflowError / ValueError past year 9999."""
    i = int(rp.get("i", 1))
    f = rp["f"]
    if f == "d":
        return start + timedelta(days=n * i)
    if f == "w":
        return start + timedelta(weeks=n * i)
    if f == "m":
        return _add_months_clamped(start, n * i)
    return _add_months_clamped(start, 12 * n * i)


def rp_pattern(start, rp, day):
    """Is the day on the pattern (first day, interval, end day)?  The deleted days are not looked at here."""
    if day < start:
        return False
    if rp.get("e") and day > _pd(rp["e"]):
        return False
    i = int(rp.get("i", 1))
    f = rp["f"]
    if f == "d":
        return (day - start).days % i == 0
    if f == "w":
        return (day - start).days % (7 * i) == 0
    if f == "m":
        months = (day.year - start.year) * 12 + day.month - start.month
        return months % i == 0 and rp_nth(start, rp, months // i) == day
    years = day.year - start.year
    return years % i == 0 and rp_nth(start, rp, years // i) == day


def rp_occurs(d_str, rp, day):
    """Does the repeating event whose first day is d_str happen on the day (a date)?"""
    try:
        return rp_pattern(_pd(d_str), rp, day) and day.isoformat() not in (rp.get("x") or [])
    except (ValueError, OverflowError):
        return False


def rp_canon(rp):
    """The rule with only what differs from the defaults (no "i" = 1, no empty "e" / "x"); None when it is not a repeat."""
    if not isinstance(rp, dict) or rp.get("f") not in REPEAT_FREQ:
        return None
    out = {"f": rp["f"]}
    try:
        i = max(1, min(99, int(rp.get("i", 1))))
    except (TypeError, ValueError):
        i = 1
    if i > 1:
        out["i"] = i
    e = rp.get("e")
    if isinstance(e, str) and _DATE_RE.match(e):
        out["e"] = e
    xs = rp.get("x")
    if isinstance(xs, list):
        ex = sorted({s for s in xs if isinstance(s, str) and _DATE_RE.match(s)})[-MAX_EXCLUDED:]
        if ex:
            out["x"] = ex
    return out


def _rp_next_anchored(start, rp, ex):
    """The next occurrence that is not deleted and may become the first one (a monthly / yearly series keeps its day of the month)."""
    last = _pd(rp["e"]) if rp.get("e") else None
    for n in range(1, 20000):
        try:
            c = rp_nth(start, rp, n)
        except (ValueError, OverflowError):
            return None
        if last and c > last:
            return None
        if c.isoformat() in ex:
            continue
        if rp["f"] in ("m", "y") and c.day != start.day:
            continue
        return c
    return None


def rp_normalize(rec):
    """Makes the repeat of a record legal (changes rec['d'] / rec['rp']): deleted days that are no occurrence are dropped and the first
    day is never a deleted one (the series then starts on its next day).  False = nothing is left of the series (the record is not usable)."""
    rp = rp_canon(rec.get("rp"))
    if rp is None:
        rec.pop("rp", None)
        return True
    try:
        start = _pd(rec["d"])
        if rp.get("e") and _pd(rp["e"]) < start:
            return False
        ex = sorted(s for s in rp.get("x", []) if rp_pattern(start, rp, _pd(s)))
        if rec["d"] in ex:
            nxt = _rp_next_anchored(start, rp, set(ex))
            if nxt is None:
                return False
            rec["d"] = nxt.isoformat()
            ex = [s for s in ex if s >= rec["d"]]
    except (ValueError, OverflowError, KeyError):
        return False
    if ex:
        rp["x"] = ex
    else:
        rp.pop("x", None)
    rec["rp"] = rp
    return True


def rp_label(rp):
    """'Every week', 'Every 2 weeks until 2027-01-01' - for the day window."""
    n = int(rp.get("i", 1))
    name = REPEAT_NAMES[rp["f"]]
    s = "Every " + name if n == 1 else "Every %d %ss" % (n, name)
    return s + (" until " + rp["e"] if rp.get("e") else "")


def v_canon(v):
    """Who sees an event, in its one allowed shape: None (only its maker), "a" (EVERYBODY on the calendar, whenever they were added),
    "a!leo,mio" (everybody EXCEPT those people) or a sorted list of person ids."""
    if v == "a":
        return "a"
    if isinstance(v, str) and v.startswith("a!"):
        ids = sorted({s for s in v[2:].split(",") if re.fullmatch(r"[a-z0-9]{1,12}", s)})
        return ("a!" + ",".join(ids)) if ids else "a"
    if isinstance(v, (list, tuple, set)):
        ids = sorted({str(s) for s in v if str(s)})
        return ids or None
    return None


def w_canon(w):
    """The names an event is ABOUT: a list of at most 4 different, trimmed names (a plain string is one name)."""
    if isinstance(w, str):
        w = [w]
    out = []
    for s in (w or []):
        s = str(s).strip()[:40]
        if s and s not in out:
            out.append(s)
    return out[:4]


def v_is_all(v):
    """Is the audience 'everybody' (also 'everybody except ...')?"""
    return isinstance(v, str) and v[:1] == "a"


def v_except(v):
    """The person ids that 'everybody except ...' leaves out ([] for plain everybody)."""
    return [s for s in v[2:].split(",") if s] if isinstance(v, str) and v.startswith("a!") else []


def v_label(v, people, me=OWNER_ID):
    """'Only me' / 'Everybody' / 'Everybody except Leo' / 'Olga, Mio' - the audience of an event as a short text."""
    if v_is_all(v):
        ex = [people.get(p, p) for p in v_except(v) if p != me]
        return "Everybody" + (" except " + ", ".join(ex) if ex else "")
    if isinstance(v, list) and v:
        return ", ".join(people.get(p, p) for p in v if p != me) or "Only me"
    return "Only me"


# The fields of version 3 that an older relay would throw away (see the header of DEL 40)
V3_FIELDS = ("v", "w", "pl", "cm")


class CalCore:
    def __init__(self, path, now_ms=None):
        self.path = path
        self._now = now_ms or (lambda: int(_time.time() * 1000))
        self.items = {}            # id -> record (see above)
        self.sent = {}             # id -> the "u" that the server has been given (a record whose u differs is waiting to be sent)
        self.seq = 0               # the server's counter at the last answer
        self.last_ok = 0           # ms of the last good sync
        self.last_error = ""
        self.last_counts = (0, 0)  # sent, taken
        self.hints = {}            # (date, time, text) -> {"r": reminders, "qt": quiet ones, "rp": repeat rule or None, "v": who sees it, "w": about, "pl", "cm"} chosen in the dialog, used once by the next reconcile()
        self.relay_v = 0           # what the relay said it can keep ("v" in its answer): 2 = repeats + quiet reminders, 3 = people; 0 = not heard yet / an old relay
        self.me = OWNER_ID         # which person this PC is (the relay says so in every answer)
        self.people = {}           # person id -> name, as the relay listed them last time
        self.foreign = {}          # date -> strings that are not "HH:MM text" (kept in the file, never synced)
        self._just_pushed = set()  # ids given to the server in the exchange that is being finished (see apply_remote)
        self.load()

    # ----- the mirror file
    def load(self):
        try:
            d = json.loads(self.path.read_text(encoding="utf-8"))
        except Exception:
            return
        self.items = d.get("items") or {}
        self.sent = {k: int(v) for k, v in (d.get("sent") or {}).items()}
        self.seq = int(d.get("seq") or 0)
        self.last_ok = int(d.get("last_ok") or 0)
        self.last_counts = tuple(d.get("last_counts") or (0, 0))
        self.relay_v = int(d.get("relay_v") or 0)
        self.me = str(d.get("me") or OWNER_ID)
        self.people = {str(k): str(v) for k, v in (d.get("people") or {}).items()}

    def save(self):
        tmp = self.path.with_name(self.path.name + ".tmp")
        data = {"seq": self.seq, "last_ok": self.last_ok, "last_counts": list(self.last_counts), "relay_v": self.relay_v, "me": self.me,
                "people": self.people, "items": self.items, "sent": self.sent}
        tmp.write_text(json.dumps(data, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
        os.replace(str(tmp), str(self.path))

    @staticmethod
    def new_id():
        return "e-" + secrets.token_hex(6)

    # ----- reminders
    def set_hint(self, date, time_s, text, reminders, quiet=(), rp=None, v=None, w=(), pl="", cm="", keep=None):
        """What the dialog chose for the event (date, time, text): its reminders, the quiet ones among them, its repeat rule (None = no repeat),
        who sees it (v), who it is about (w), place and comment.  keep = the id of the event this one is a CHANGED version of: it keeps its id
        (so the others' own settings for it stay), instead of becoming a new event while the old one is deleted."""
        p = ev_parse(ev_string(time_s, text))
        if p:
            r = sorted({int(m) for m in reminders})
            self.hints[(date, p[0], p[1])] = {"r": r, "qt": sorted({int(m) for m in quiet if int(m) in r}), "rp": rp_canon(rp),
                                              "v": v_canon(v), "w": w_canon(w), "pl": str(pl or "").strip()[:200], "cm": str(cm or "").strip()[:1000],
                                              "keep": keep}

    # ----- people: whose is a record, and my own settings for the events of others
    def is_mine(self, rec):
        """A record without a maker is mine (made here, or before there were people); the relay stamps the maker on every record it keeps."""
        return rec.get("o") in (None, "", self.me)

    def maker_name(self, rec):
        o = rec.get("o") or self.me
        return self.people.get(o, o)

    def override_id(self, iid):
        return "m-%s-%s" % (self.me, iid)

    def override(self, iid):
        """My own settings record for the event iid (live), or None."""
        o = self.items.get(self.override_id(iid))
        return o if o and not o.get("z") else None

    def is_hidden(self, iid):
        o = self.override(iid)
        return bool(o and o.get("hid"))

    def effective_reminders(self, iid, rec):
        """(reminders, quiet ones) that RING for me: my own settings when I made some for this event, else the event's."""
        o = self.override(iid) if not self.is_mine(rec) else None
        if o is not None and "r" in o:
            return list(o["r"]), list(o.get("qt", []))
        return list(rec.get("r", DEFAULT_REMIND)), list(rec.get("qt", []))

    def set_override(self, iid, events, notes, hid=None, reminders=None, quiet=(), reset_reminders=False):
        """Changes my own settings for somebody else's event: hid True/False = leave it out of / show it in my calendar again; reminders = my
        own list (with the quiet ones); reset_reminders = back to the maker's.  Writes the dicts (a hidden event leaves them) and the mirror."""
        rec = self.items.get(iid)
        if not rec or rec.get("z") or self.is_mine(rec):
            return False
        oid = self.override_id(iid)
        cur = self.override(iid)
        new = {"k": "m", "d": rec["d"], "x": "", "ev": iid, "u": max(self._now(), int((cur or self.items.get(oid) or {}).get("u", 0)) + 1)}
        if cur and cur.get("hid"):
            new["hid"] = 1
        if cur and "r" in cur:
            new["r"] = list(cur["r"])
            if cur.get("qt"):
                new["qt"] = list(cur["qt"])
        if hid is not None:
            if hid:
                new["hid"] = 1
            else:
                new.pop("hid", None)
        if reset_reminders:
            new.pop("r", None)
            new.pop("qt", None)
        if reminders is not None:
            r = sorted({int(m) for m in reminders})
            new["r"] = r
            q = sorted({int(m) for m in quiet if int(m) in r})
            if q:
                new["qt"] = q
            else:
                new.pop("qt", None)
        was_hidden = bool(cur and cur.get("hid"))
        self.items[oid] = new
        if hid is True and not was_hidden:
            self._ui_remove(rec, events, notes)
        elif hid is False and was_hidden:
            self._ui_add(rec, events, notes)
        return True

    def hidden_events(self):
        """[(id, record)] of the events of others that I left out of my calendar, in date order."""
        out = [(iid, r) for iid, r in self.items.items()
               if r.get("k") == "e" and not r.get("z") and not self.is_mine(r) and self.is_hidden(iid)]
        out.sort(key=lambda a: (a[1]["d"], a[1]["t"]))
        return out

    def foreign_keys(self):
        """{(date, time, text)} of the live events of others that are shown (not left out): their strings in the events dict are not mine."""
        return {(r["d"], r["t"], r["x"]) for iid, r in self.items.items()
                if r.get("k") == "e" and not r.get("z") and not self.is_mine(r) and not self.is_hidden(iid)}

    def note_id(self, day_str):
        """The owner keeps the old id; everybody else gets an own one (the relay refuses a note whose id does not carry the maker)."""
        return "n-" + day_str if self.me == OWNER_ID else "n-%s-%s" % (self.me, day_str)

    def note_people(self, answer):
        """Takes 'me' and 'people' out of a relay answer (version 3)."""
        me = answer.get("me")
        if isinstance(me, str) and me:
            self.me = me
            if me != OWNER_ID:                         # notes made before this PC knew who it is carry the owner's id: the relay refuses those
                for iid in [i for i, r in self.items.items() if r.get("k") == "n" and not i.startswith("n-%s-" % me)]:
                    del self.items[iid]
                    self.sent.pop(iid, None)
        ppl = answer.get("people")
        if isinstance(ppl, dict):
            self.people = {str(k): str(v) for k, v in ppl.items()}

    def remind_index(self):
        out = {}
        for r in self.items.values():
            if r.get("k") == "e" and not r.get("z") and self.is_mine(r):
                out.setdefault((r["d"], r["t"], r["x"]), r.get("r", list(DEFAULT_REMIND)))
        return out

    def reminders_for(self, date, s):
        p = ev_parse(s)
        if not p:
            return list(DEFAULT_REMIND)
        key = (date, p[0], p[1])
        if key in self.hints:
            return list(self.hints[key]["r"])
        return list(self.remind_index().get(key, DEFAULT_REMIND))

    def record_for(self, date, s):
        """(id, record) of the live event that the string s on that date stands for, or (None, None)."""
        p = ev_parse(s)
        found = (None, None)
        if p:
            for iid, r in self.items.items():
                if r.get("k") == "e" and not r.get("z") and (r["d"], r["t"], r["x"]) == (date, p[0], p[1]):
                    if self.is_mine(r):
                        return iid, r                       # mine first: an identical event of somebody else is not the one meant
                    if found[0] is None and not self.is_hidden(iid):
                        found = (iid, r)
        return found

    def repeat_starts(self):
        """{(date, time, text)} of the repeating events: their strings in the events dict are the first day of a series."""
        return {(r["d"], r["t"], r["x"]) for r in self.items.values() if r.get("k") == "e" and not r.get("z") and r.get("rp")}

    def occurrences_on(self, day_str):
        """[(id, record)] of the repeating events that happen on the day but are NOT drawn from the events dict (their first day is another one)."""
        try:
            day = _pd(day_str)
        except ValueError:
            return []
        out = [(iid, r) for iid, r in self.items.items()
               if r.get("k") == "e" and not r.get("z") and r.get("rp") and r["d"] != day_str and rp_occurs(r["d"], r["rp"], day)
               and (self.is_mine(r) or not self.is_hidden(iid))]
        out.sort(key=lambda a: (a[1]["t"], a[1]["x"]))
        return out

    def _bump(self, iid):
        r = self.items[iid]
        r["u"] = max(self._now(), int(r.get("u", 0)) + 1)

    def series_exclude(self, iid, day_str):
        """Deletes ONE occurrence of a repeating event (not its first one: that changes the events dict, see CalendarFrame)."""
        r = self.items.get(iid)
        if not r or r.get("z") or not r.get("rp") or day_str == r["d"] or not rp_occurs(r["d"], r["rp"], _pd(day_str)):
            return False
        r["rp"]["x"] = sorted(set(r["rp"].get("x", [])) | {day_str})
        rp_normalize(r)
        self._bump(iid)
        return True

    def series_end_before(self, iid, day_str):
        """'This and the following': the series ends the day before (not for its first day: that is deleting all of it)."""
        r = self.items.get(iid)
        if not r or r.get("z") or not r.get("rp") or _pd(day_str) <= _pd(r["d"]):
            return False
        r["rp"]["e"] = (_pd(day_str) - timedelta(days=1)).isoformat()
        rp_normalize(r)
        self._bump(iid)
        return True

    @staticmethod
    def series_without_first(rec):
        """(new first day, new rule) of a series whose first occurrence is deleted, or None when nothing is left of it.  Does not change rec."""
        c = {"d": rec["d"], "rp": json.loads(json.dumps(rec["rp"]))}
        c["rp"]["x"] = sorted(set(c["rp"].get("x", [])) | {rec["d"]})
        if not rp_normalize(c):
            return None
        return c["d"], c["rp"]

    @staticmethod
    def needs_v3(rec):
        """Does the record carry something only relay version 3 keeps (who sees it, who it is about, place, comment, own settings)?"""
        return not rec.get("z") and (rec.get("k") == "m" or any(rec.get(f) for f in V3_FIELDS))

    def set_audience(self, iid, v):
        """Who sees MY event iid (None = only me, "a" = everybody, a list of person ids).  True when that changed it."""
        rec = self.items.get(iid)
        v = v_canon(v)
        if not rec or rec.get("z") or rec.get("k") != "e" or not self.is_mine(rec) or v == rec.get("v"):
            return False
        if v:
            rec["v"] = v
        else:
            rec.pop("v", None)
        self._bump(iid)
        return True

    def about_names(self):
        """Every name an event is about, plus the names of the people: what the 'About' drop-down offers (people first)."""
        names = [n for p, n in sorted(self.people.items(), key=lambda a: a[1].lower())]
        for r in self.items.values():
            for n in (r.get("w") or []):
                if n not in names:
                    names.append(n)
        return names

    def held_back(self):
        """How many records wait because the relay has not said that it keeps repeats (2) / people (3)."""
        n = 0
        for iid, r in self.items.items():
            if self.sent.get(iid) != r.get("u") and not r.get("z") and (r.get("rp") or self.needs_v3(r)):
                n += 1
        return n

    def _apply_hint(self, rec, hint, now):
        """Takes the dialog's reminders / quiet ones / repeat / audience into a record; True when that changed it."""
        chg = False
        for f, val in (("v", hint.get("v")), ("w", hint.get("w") or None), ("pl", hint.get("pl") or None), ("cm", hint.get("cm") or None)):
            if val != rec.get(f):
                if val:
                    rec[f] = json.loads(json.dumps(val))
                else:
                    rec.pop(f, None)
                chg = True
        if hint["r"] != rec.get("r"):
            rec["r"] = list(hint["r"])
            chg = True
        if hint["qt"] != rec.get("qt", []):
            if hint["qt"]:
                rec["qt"] = list(hint["qt"])
            else:
                rec.pop("qt", None)
            chg = True
        if hint["rp"] != rec.get("rp"):
            if hint["rp"]:
                rec["rp"] = json.loads(json.dumps(hint["rp"]))
            else:
                rec.pop("rp", None)
            chg = True
        if chg:
            rec["u"] = max(now, int(rec.get("u", 0)) + 1)
        return chg

    # ----- local changes -> the mirror
    def _tombstone(self, iid, now):
        r = self.items[iid]
        self.items[iid] = {"k": r["k"], "d": r["d"], "x": "", "u": max(now, int(r.get("u", 0)) + 1), "z": 1}

    def reconcile(self, events, notes):
        """Compares the two dicts with the mirror; True when the mirror changed.  Never touches the dicts."""
        now = self._now()
        changed = False
        pool, fpool = {}, {}                      # my events / the events of others, by (date, time, text)
        for iid, r in self.items.items():
            if r.get("k") == "e" and not r.get("z"):
                (pool if self.is_mine(r) else fpool).setdefault((r["d"], r["t"], r["x"]), []).append(iid)
        for ids in list(pool.values()) + list(fpool.values()):
            ids.sort(key=lambda i: (self.items[i]["u"], i))
        foreign = {}
        for d, lst in events.items():
            if not _DATE_RE.match(str(d)):
                continue
            for s in lst:
                p = ev_parse(s)
                if p is None:
                    foreign.setdefault(d, []).append(s)
                    continue
                key = (d, p[0], p[1])
                ids = pool.get(key)
                hint = self.hints.get(key)
                if ids:
                    iid = ids.pop(0)
                    if hint is not None and self._apply_hint(self.items[iid], hint, now):
                        changed = True
                elif fpool.get(key):
                    fpool[key].pop(0)                 # somebody else's event shown in the list: never changed or deleted from here
                else:
                    rec = {"k": "e", "d": d, "t": p[0], "x": p[1], "u": now,
                           "r": list(hint["r"]) if hint is not None else list(DEFAULT_REMIND)}
                    if hint is not None and hint["qt"]:
                        rec["qt"] = list(hint["qt"])
                    if hint is not None and hint["rp"]:
                        rec["rp"] = json.loads(json.dumps(hint["rp"]))
                        rp_normalize(rec)
                    if hint is not None:
                        for f in V3_FIELDS:
                            if hint.get(f):
                                rec[f] = json.loads(json.dumps(hint[f]))
                    keep = hint.get("keep") if hint is not None else None
                    old = self.items.get(keep) if keep else None
                    if old is not None and old.get("k") == "e" and not old.get("z") and self.is_mine(old):
                        for lst2 in pool.values():    # a CHANGED event: the old record becomes this one (same id), it is not deleted
                            if keep in lst2:
                                lst2.remove(keep)
                        rec["u"] = max(now, int(old.get("u", 0)) + 1)
                        self.items[keep] = rec
                    else:
                        self.items[self.new_id()] = rec
                    changed = True
        for ids in pool.values():
            for iid in ids:                       # in the mirror but no longer in the dict = deleted here
                self._tombstone(iid, now)
                changed = True
        self.hints.clear()
        # the notes: one record per day, id "n-<date>" (the owner) / "n-<me>-<date>" (everybody else)
        live_notes = {d: t.strip() for d, t in notes.items() if _DATE_RE.match(str(d)) and str(t).strip()}
        for d, text in live_notes.items():
            iid = self.note_id(d)
            cur = self.items.get(iid)
            if cur and not cur.get("z") and cur.get("x") == text:
                continue
            self.items[iid] = {"k": "n", "d": d, "x": text, "u": max(now, int(cur["u"]) + 1) if cur else now}
            changed = True
        for iid, r in list(self.items.items()):
            if r.get("k") == "n" and not r.get("z") and r["d"] not in live_notes:
                self._tombstone(iid, now)
                changed = True
        self.foreign = foreign
        return changed

    @staticmethod
    def marks_id(d, v):
        """The record id of the birthdays of day d that one audience sees: 'b-<d>' = only me, 'b-<d>-a' = everybody, 'b-<d>-p<hash>' = chosen people."""
        v = v_canon(v)
        if not v:
            return "b-" + d
        if v == "a":
            return "b-%s-a" % d
        return "b-%s-p%s" % (d, hashlib.sha1((v if isinstance(v, str) else ",".join(v)).encode("utf-8")).hexdigest()[:8])

    def update_marks(self, marks, first, last, v=None):
        """Birthdays etc. for the days first..last ('YYYY-MM-DD' strings): marks = {date: [line]} where a line is a text (it gets the audience v)
        or a pair (text, audience of THAT line).  An audience: None = only me, "a" = everybody, a list of person ids.  One record per day and
        audience, so every birthday has its own audience.  True when something changed."""
        if self.me != OWNER_ID:                  # the relay keeps birthdays for the owner only
            return False
        now = self._now()
        changed = False
        dv = v_canon(v)
        want = {}                                # record id -> (date, [lines], audience)
        for d, lines in marks.items():
            if not (first <= d <= last):
                continue
            for line in lines or []:
                text, lv = (line[0], v_canon(line[1])) if isinstance(line, (tuple, list)) else (line, dv)
                if not str(text).strip():
                    continue
                iid = self.marks_id(d, lv)
                want.setdefault(iid, (d, [], lv))[1].append(str(text))
        for iid, (d, ls, lv) in want.items():
            text = "\n".join(ls)
            cur = self.items.get(iid)
            if cur and not cur.get("z") and cur.get("x") == text and v_canon(cur.get("v")) == lv:
                continue
            rec = {"k": "b", "d": d, "x": text, "u": max(now, int(cur["u"]) + 1) if cur else now}
            if lv:
                rec["v"] = lv
            self.items[iid] = rec
            changed = True
        for iid, r in list(self.items.items()):
            if r.get("k") == "b" and not r.get("z") and first <= r["d"] <= last and iid not in want:
                self._tombstone(iid, now)
                changed = True
        return changed

    # ----- the sync itself
    def push_body(self, series=True, people=True):
        """What is waiting for the relay.  series=False holds back the repeating events (the relay has not said that it keeps repeats);
        people=False holds back everything of version 3 (who sees it, about, place, comment, own settings).  Somebody else's events never go."""
        return {iid: {k: v for k, v in r.items() if k in ("k", "d", "t", "x", "r", "qt", "rp", "u", "z", "v", "w", "pl", "cm", "ev", "hid")}
                for iid, r in self.items.items()
                if self.sent.get(iid) != r.get("u") and (r.get("k") == "m" or self.is_mine(r))
                and (series or not (r.get("rp") and not r.get("z"))) and (people or not self.needs_v3(r))}

    def note_relay_version(self, v):
        try:
            self.relay_v = int(v)
        except (TypeError, ValueError):
            self.relay_v = 1                          # an answer without "v" comes from the first version of the relay

    def mark_pushed(self, body):
        for iid, r in body.items():
            cur = self.items.get(iid)
            if cur and cur.get("u") == r.get("u"):
                self.sent[iid] = r["u"]
                self._just_pushed.add(iid)

    def apply_remote(self, remote, seq, events, notes):
        """Takes what the server answered into the mirror AND the two dicts.  Returns how many records were taken."""
        taken = 0
        for iid, rec in (remote or {}).items():
            if not isinstance(rec, dict) or rec.get("k") not in ("e", "n", "b", "m"):
                continue
            try:
                u = int(rec.get("u", 0))
            except (TypeError, ValueError):
                continue
            cur = self.items.get(iid)
            if cur is not None and u <= int(cur.get("u", 0)):
                if u == int(cur.get("u", 0)):
                    self.sent[iid] = u
                continue
            if cur is not None and not cur.get("z"):
                self._ui_remove(cur, events, notes)
            new = {"k": rec["k"], "d": str(rec.get("d", "")), "x": str(rec.get("x", "")), "u": u}
            if rec["k"] == "e":
                new["t"] = str(rec.get("t", ""))
                rr = rec.get("r")                       # [] = "no reminder" is a real choice; only a record without the field gets the default
                new["r"] = sorted({int(m) for m in rr if isinstance(m, (int, float))}) if isinstance(rr, list) else list(DEFAULT_REMIND)
                qq = rec.get("qt")
                soft = sorted({int(m) for m in qq if isinstance(m, (int, float)) and int(m) in new["r"]}) if isinstance(qq, list) else []
                if soft:
                    new["qt"] = soft
                rp = rp_canon(rec.get("rp"))
                if rp and not rec.get("z"):
                    new["rp"] = rp
                v = v_canon(rec.get("v"))
                if v and not rec.get("z"):
                    new["v"] = v
                w = w_canon(rec.get("w"))
                if w and not rec.get("z"):
                    new["w"] = w
                for f in ("pl", "cm"):
                    if rec.get(f) and not rec.get("z"):
                        new[f] = str(rec[f])
            if rec["k"] in ("e", "n") and isinstance(rec.get("o"), str) and rec["o"]:
                new["o"] = rec["o"]
            if rec["k"] == "m":
                new["ev"] = str(rec.get("ev", ""))
                if rec.get("hid") and not rec.get("z"):
                    new["hid"] = 1
                rr = rec.get("r")
                if isinstance(rr, list) and not rec.get("z"):
                    new["r"] = sorted({int(m) for m in rr if isinstance(m, (int, float))})
                    qq = rec.get("qt")
                    soft = sorted({int(m) for m in qq if isinstance(m, (int, float)) and int(m) in new["r"]}) if isinstance(qq, list) else []
                    if soft:
                        new["qt"] = soft
            if rec.get("z"):
                new["z"] = 1
                new["x"] = ""
            elif not _DATE_RE.match(new["d"]) or (rec["k"] == "e" and ev_parse(ev_string(new["t"], new["x"])) is None):
                continue
            elif new.get("rp") and not rp_normalize(new):
                continue
            # An identical event that this side made and never sent is THE SAME event (first pairing, or the mirror file was lost):
            # take the server's id for it instead of showing it twice.
            adopt = None
            if cur is None and new["k"] == "e" and not new.get("z") and self.is_mine(new):
                for oid, o in self.items.items():
                    if (o.get("k") == "e" and not o.get("z") and (oid not in self.sent or oid in self._just_pushed)
                            and (o["d"], o["t"], o["x"]) == (new["d"], new["t"], new["x"])):
                        adopt = oid
                        break
            if adopt:
                if adopt in self._just_pushed:
                    # the twin went to the server in this very exchange: the server has it now, so it must be deleted THERE too
                    # (a tombstone that goes with the next sync); the one event shown here stays
                    old = self.items[adopt]
                    self.items[adopt] = {"k": "e", "d": old["d"], "x": "", "u": max(self._now(), int(old.get("u", 0)) + 1), "z": 1}
                    self.sent.pop(adopt, None)
                else:
                    del self.items[adopt]
            self.items[iid] = new
            self.sent[iid] = u
            if new["k"] == "m":
                self._take_override(iid, cur, new, events, notes)
            elif not new.get("z") and not adopt and (self.is_mine(new) or not self.is_hidden(iid)):
                self._ui_add(new, events, notes)
            taken += 1
        self.seq = max(self.seq, int(seq or 0))
        self._just_pushed = set()
        return taken

    def _take_override(self, oid, old, new, events, notes):
        """My own settings changed on ANOTHER device of mine: an event that is now left out leaves the dicts, one that is shown again returns."""
        ev = self.items.get(new.get("ev", ""))
        if not ev or ev.get("z") or self.is_mine(ev):
            return
        was = bool(old and not old.get("z") and old.get("hid"))
        now_hidden = bool(not new.get("z") and new.get("hid"))
        if now_hidden and not was:
            self._ui_remove(ev, events, notes)
        elif was and not now_hidden:
            self._ui_add(ev, events, notes)

    @staticmethod
    def _ui_remove(rec, events, notes):
        if rec["k"] == "e":
            lst = events.get(rec["d"], [])
            for s in lst:
                if ev_parse(s) == (rec["t"], rec["x"]):
                    lst.remove(s)
                    break
            if not lst and rec["d"] in events:
                del events[rec["d"]]
        elif rec["k"] == "n":
            notes.pop(rec["d"], None)

    @staticmethod
    def _ui_add(rec, events, notes):
        if rec["k"] == "e":
            events.setdefault(rec["d"], []).append(ev_string(rec["t"], rec["x"]))
        elif rec["k"] == "n":
            notes[rec["d"]] = rec["x"]

    def forget_old(self, days=120):
        """Drops tombstones that are old and already known to the server."""
        limit = self._now() - days * 86400 * 1000
        for iid in [i for i, r in self.items.items() if r.get("z") and r.get("u", 0) < limit and self.sent.get(i) == r.get("u")]:
            del self.items[iid]
            self.sent.pop(iid, None)

    def waiting(self):
        return sum(1 for iid, r in self.items.items() if self.sent.get(iid) != r.get("u") and r.get("k") != "b")

    def alarm_times(self, now_dt):
        """[(datetime of the ring, event datetime, text)] for every live event whose reminder moment is still ahead."""
        out = []
        first = now_dt.date() - timedelta(days=1)
        for iid, r in self.items.items():
            if r.get("k") != "e" or r.get("z"):
                continue
            if not self.is_mine(r) and self.is_hidden(iid):
                continue                                    # left out of my calendar: no alarm either
            rem_list = self.effective_reminders(iid, r)[0]
            days = [r["d"]]
            if r.get("rp"):                                 # a repeating event: every occurrence from yesterday to 90 days ahead
                days = [(first + timedelta(days=n)).isoformat() for n in range(92)
                        if rp_occurs(r["d"], r["rp"], first + timedelta(days=n))]
            for dd in days:
                try:
                    ev_dt = datetime.strptime("%s %s" % (dd, r["t"]), "%Y-%m-%d %H:%M")
                except ValueError:
                    continue
                for m in rem_list:
                    at = ev_dt - timedelta(minutes=int(m))
                    if at >= now_dt:
                        out.append((at, ev_dt, r["x"]))
        out.sort(key=lambda a: a[0])
        return out


def relay_post(url, key, body, timeout=20, path="/sync"):
    """One POST /sync (path="/people": the owner's people operations); returns the answer dict.  Raises SyncError with a message that can be shown as it is."""
    req = urllib.request.Request(url.rstrip("/") + path, data=json.dumps(body, ensure_ascii=False).encode("utf-8"), method="POST",
                                 headers={"X-Calendar-Key": key, "Content-Type": "application/json", "User-Agent": "Kalender/1"})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.loads(r.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        if e.code == 401:
            raise SyncError("The server did not accept the key.")
        if e.code == 403:
            raise SyncError("Only the owner can manage people.")
        if e.code == 404 and path == "/people":
            raise SyncError("The server does not know people yet: run WebdockTool > Jobs > 'Calendar relay' first.")
        if e.code == 429:
            raise SyncError("The server says: too many requests. Try again in a while.")
        raise SyncError("The server answered %d." % e.code)
    except urllib.error.URLError:
        raise SyncError("No connection to the server (no network?).")
    except (OSError, ValueError):
        raise SyncError("The server did not answer properly.")


def pairing_make(url, key, app=SYNC_APP):
    raw = json.dumps({"a": app, "u": url, "k": key}, separators=(",", ":")).encode("utf-8")
    return "ISSUSYNC1:" + base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")


def pairing_parse(text):
    """(app, url, key) out of any text that contains a code, or None.  Whitespace inside the code and text after it are ignored."""
    t = re.sub(r"\s+", "", text or "")
    i = t.find("ISSUSYNC1:")
    if i < 0:
        return None
    m = re.match(r"[A-Za-z0-9_\-]+", t[i + 10:])
    if not m:
        return None
    body = m.group(0)
    for n in range(len(body), max(len(body) - 400, 15), -1):       # text after the code sticks to it: shorten until it decodes
        piece = body[:n]
        try:
            o = json.loads(base64.urlsafe_b64decode(piece + "=" * (-len(piece) % 4)).decode("utf-8"))
        except (ValueError, UnicodeDecodeError):
            continue
        if isinstance(o, dict) and str(o.get("u", "")).startswith(("http://", "https://")) and len(str(o.get("k", ""))) >= 8:
            return str(o.get("a", "")), str(o["u"]), str(o["k"])
    return None


# ── Day-header rows for each locale ───────────────────────────────────────────
# Monday-first (Sweden / UK): columns 1-7 = Mon … Sun
_HEADERS_MON_FIRST = ["Week", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
# Sunday-first (Russia): columns 1-7 = Sun … Sat
_HEADERS_SUN_FIRST = ["Week", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

# ── CalendarFrame ──────────────────────────────────────────────────────────────
class CalendarFrame(tk.Frame):
    def __init__(self, master, hub=None, hub_locale="Sweden"):
        super().__init__(master)
        self.hub        = hub
        self.hub_locale = hub_locale
        self.pack(fill="both", expand=True)

        self.calendar_type = tk.StringVar(value="Sweden")
        self.events   = {}
        self.notes    = {}
        self.holidays = holidays.Sweden()

        # The two BirthdayTracker layers (DEL 01). Both choices survive a
        # restart; Extras starts OFF because it is much busier.
        _cfg = load_cfg()
        self.show_bt     = tk.BooleanVar(value=bool(_cfg.get("show_birthdays", True)))
        self.show_extras = tk.BooleanVar(value=bool(_cfg.get("show_extras", True)))
        self._bt_marks   = {}

        # Cell geometry is measured from the canvas, never from the text, so
        # switching a layer on or off cannot move the layout. _last_layout is
        # what the last redraw was measured against; a resize only rebuilds
        # when it would actually change the cells.
        self._last_layout   = (0, 0)
        self._resize_after  = None
        self._cell_metrics  = (100, 80, 2, 18)   # w, h, lines, chars per line
        self._cell_hidden   = {}                 # day -> lines that did not fit
        self._day_popup     = None               # only ever one open at a time

        # Styles
        self.style = ttk.Style()
        self.style.configure("Header.TLabel",  font=("Arial", 10, "bold"))
        self.style.configure("Today.TFrame",   background="lightblue")
        self.style.configure("Holiday.TFrame", background="mistyrose")
        self.style.configure("Normal.TFrame",  background="white")
        self.style.configure("Event.TLabel",   foreground="red", font=("Arial", 8))

        self.today         = datetime.today()
        self.current_date  = self.today.replace(day=1)
        self.selected_date = self.today.date()

        # Timer ID for alarm rescheduling (avoids accumulating multiple timers)
        self._alarm_after_id = None

        # Phone sync (DEL 40/41): the mirror of events + notes, and the state of the background sync
        self.core            = CalCore(SYNC_PATH)
        self._sync_busy      = False
        self._sync_after_id  = None
        self._sync_tick_id   = None
        self._marks_stamp    = None
        self._rung           = set()

        self.build_header()
        self.build_calendar_grid()
        self.build_notes_section()
        self.build_footer()

        self.load_data()
        self._reconcile_now()                         # the mirror learns what the files say (also a hand-edited file)
        self.show_notes_for_day(self.selected_date)  # show today's note at once
        self.refresh_calendar()
        self._run_alarm_check()                       # fill "Next reminder" immediately
        self._schedule_alarm()
        self._update_sync_label()
        self.request_sync(2500)                       # first sync a moment after the window is up
        self._sync_tick()                             # and then every few minutes

    # ── UI construction ────────────────────────────────────────────────────────
    def build_header(self):
        self.header_frame = ttk.Frame(self)
        self.header_frame.pack(pady=5, fill="x")

        ttk.Label(self.header_frame, text="Calendar format:").pack(side="left", padx=(10, 2))
        for val, lbl in (("Sweden", "Sweden"), ("UK", "UK"), ("Russia", "Russia")):
            ttk.Radiobutton(
                self.header_frame, text=lbl,
                variable=self.calendar_type, value=val,
                command=self.on_calendar_type_changed,
            ).pack(side="left")

        nav = ttk.Frame(self.header_frame)
        nav.pack(side="left", padx=10)
        ttk.Button(nav, text="←", width=3, command=self.prev_month).pack(side="left")
        ttk.Button(nav, text="→", width=3, command=self.next_month).pack(side="left")

        self.month_label = ttk.Label(
            self.header_frame, font=("Arial", 12, "bold"),
            text=self.current_date.strftime("%B %Y"),
        )
        self.month_label.pack(side="left", padx=20)

        ttk.Button(self.header_frame, text="Today",        command=self.go_to_today).pack(side="right", padx=10)
        ttk.Button(self.header_frame, text="➕ Add event",  command=self.add_event).pack(side="right", padx=4)
        ttk.Button(self.header_frame, text="?  Help",       command=self._show_help).pack(side="right", padx=4)
        ttk.Button(self.header_frame, text="ℹ  About",      command=self._show_about).pack(side="right", padx=4)

        # ── Second, slim row: the two BirthdayTracker layers ──────────────────
        # Their own row on purpose. The toolbar above already needs ~960 px of
        # a 1000 px window, and pack() does not wrap - it silently clips
        # whatever will not fit, which would have eaten the About button.
        self.header_frame2 = ttk.Frame(self)
        self.header_frame2.pack(fill="x", padx=10, pady=(0, 4))

        # The phone sync (DEL 41) goes first on the RIGHT, so it is never the one that gets clipped
        self.sync_btn = ttk.Button(self.header_frame2, text="📱 Phone sync…", command=self.show_sync_dialog)
        self.sync_btn.pack(side="right")
        self.people_btn = ttk.Button(self.header_frame2, text="👥 People…", command=self.show_people_dialog)
        self.people_btn.pack(side="right", padx=(0, 6))
        self.sync_label = tk.Label(self.header_frame2, text="", foreground="gray", font=("Segoe UI", 8),
                                   anchor="e", width=34)
        self.sync_label.pack(side="right", padx=(0, 8))

        cb_bt = ttk.Checkbutton(
            self.header_frame2, text="🎂 Birthdays",
            variable=self.show_bt,
            command=self.on_show_bt_changed,
        )
        cb_bt.pack(side="left")
        attach_tooltip(cb_bt,
                       "Birthdays and personal anniversaries,\n"
                       "read from BirthdayTracker's own list.")

        cb_extra = ttk.Checkbutton(
            self.header_frame2, text="✨ Extras",
            variable=self.show_extras,
            command=self.on_show_bt_changed,
        )
        cb_extra.pack(side="left", padx=(12, 0))
        attach_tooltip(cb_extra,
                       "Also show, for the same people:\n"
                       "  ⭐  day-count milestones (1 000, 10 000 days …)\n"
                       "  🏆  round-number ages (18, 50, 65 …)\n"
                       "  💜  Swedish name days\n"
                       "  ⏳  mini-birthdays (every 1 / 3 / 6 months)\n"
                       "Switching this changes what a day shows,\n"
                       "never the size of the calendar.")

        ttk.Label(self.header_frame2,
                  text="— from BirthdayTracker",
                  foreground="gray").pack(side="left", padx=(10, 0))

    def build_calendar_grid(self):
        container = ttk.Frame(self)
        container.pack(fill="both", expand=True, pady=(0, 10))

        self.canvas     = tk.Canvas(container)
        self.scrollbar  = ttk.Scrollbar(container, orient="vertical", command=self.canvas.yview)
        self.grid_frame = ttk.Frame(self.canvas)

        self.canvas.configure(yscrollcommand=self.scrollbar.set, highlightthickness=0)
        # Keep the item id: the frame inside a canvas is normally only as big
        # as its contents, which is exactly what made the calendar change size
        # whenever a layer was switched on. It is stretched to the canvas
        # instead, so the grid always fills the space it is given.
        self._grid_window = self.canvas.create_window(
            (0, 0), window=self.grid_frame, anchor="nw")
        self.canvas.bind("<Configure>", self._on_canvas_resize)

        # Scrollbar packed BEFORE the expanding canvas, or it renders 1 px wide
        self.scrollbar.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)

        self.grid_frame.bind("<Enter>", lambda e: self.canvas.bind_all("<MouseWheel>", self._on_mousewheel))
        self.grid_frame.bind("<Leave>", lambda e: self.canvas.unbind_all("<MouseWheel>"))

    def _on_canvas_resize(self, event):
        """Stretch the grid to the canvas, and rebuild only if the cells change.

        Rebuilding on every pixel of a window drag would be wasteful, so the
        redraw is debounced and skipped altogether while the cell size stays
        the same.
        """
        self.canvas.itemconfigure(self._grid_window,
                                  width=event.width, height=event.height)
        self.canvas.configure(scrollregion=(0, 0, event.width, event.height))

        if (abs(event.width  - self._last_layout[0]) < 8 and
                abs(event.height - self._last_layout[1]) < 8):
            return
        if self._resize_after is not None:
            try:
                self.after_cancel(self._resize_after)
            except Exception:
                pass
        self._resize_after = self.after(200, self._resize_redraw)

    def _resize_redraw(self):
        self._resize_after = None
        self.refresh_calendar()

    def _on_mousewheel(self, event):
        self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

    def build_notes_section(self):
        nf = ttk.LabelFrame(self, text="📝 Notes for selected day")
        nf.pack(fill="x", padx=10, pady=5)

        # Whatever BirthdayTracker holds for the selected day, in full - the
        # month cells only have room for two shortened lines. Packed BEFORE the
        # text box, or the expanding widget would squeeze it to nothing.
        # width=1 on purpose: the label is stretched by fill="x", so it asks
        # for nothing and long text is clipped instead of widening the whole
        # window. Nothing here may depend on how much text there happens to be.
        self.bt_day_label = tk.Label(
            nf, text="", anchor="w", justify="left", width=1,
            foreground="#1b6b2a", font=("Segoe UI", 8))
        self.bt_day_label.pack(fill="x", padx=6, pady=(2, 0))

        self.notes_text = tk.Text(
            nf, height=5, wrap="word",
            insertofftime=0, insertontime=9_999_999,
        )
        no_blink(self.notes_text)
        ns = ttk.Scrollbar(nf, command=self.notes_text.yview)
        self.notes_text.configure(yscrollcommand=ns.set)
        self.notes_text.pack(side="left", fill="both", expand=True)
        ns.pack(side="right", fill="y")

        bf = ttk.Frame(nf)
        bf.pack(fill="x", pady=(5, 0))
        ttk.Button(bf, text="💾 Save",  command=self.save_note).pack(side="right", padx=5)
        ttk.Button(bf, text="✖ Clear", command=self.clear_note).pack(side="right")

    def build_footer(self):
        footer = ttk.Frame(self)
        footer.pack(fill="x", padx=10, pady=(0, 5))

        self.upcoming_label = ttk.Label(footer, text="🔔 Next reminder: None", font=("Arial", 9))
        self.upcoming_label.pack(side="left", anchor="w")

        ef = ttk.Frame(footer)
        ef.pack(side="right", anchor="e")
        ttk.Label(ef, text="E-mail:").pack(side="left")

        self.email_entry = tk.Entry(ef, width=30, insertofftime=0, insertontime=9_999_999)
        no_blink(self.email_entry)
        self.email_entry.pack(side="left", padx=5)
        ttk.Button(ef, text="Save", command=self.save_email, width=6).pack(side="left")

    # ── Calendar rendering ─────────────────────────────────────────────────────
    def on_calendar_type_changed(self):
        ct = self.calendar_type.get()
        if ct == "Sweden":
            self.holidays = holidays.Sweden()
        elif ct == "UK":
            self.holidays = holidays.UnitedKingdom()
        elif ct == "Russia":
            self.holidays = holidays.Russia()
        self.refresh_calendar()

    def on_show_bt_changed(self):
        """Remember both BirthdayTracker layers in kalender-settings.json.

        Re-read the file rather than keeping a copy: the standalone window
        writes its geometry into the same file when it closes, and a stale
        in-memory copy would put these settings straight back to what they were.
        """
        cfg = load_cfg()
        cfg["show_birthdays"] = bool(self.show_bt.get())
        cfg["show_extras"]    = bool(self.show_extras.get())
        save_cfg(cfg)
        self.refresh_calendar()
        self._show_bt_for_day(self.selected_date)

    def refresh_calendar(self):
        for w in self.grid_frame.winfo_children():
            w.destroy()

        year, month = self.current_date.year, self.current_date.month
        self.month_label.config(text=self.current_date.strftime("%B %Y").capitalize())

        # Read once per redraw, not once per cell - and _bt_persons() only
        # touches the disk again when persons.json has actually changed.
        self._bt_who = {}
        self._bt_marks = bt_marks_for_month(year, month,
                                            base=self.show_bt.get(),
                                            extras=self.show_extras.get(), who=self._bt_who)

        # Russia uses Sunday-first weeks; all others use Monday-first
        sunday_first = (self.calendar_type.get() == "Russia")
        first_weekday = 6 if sunday_first else 0
        headers = _HEADERS_SUN_FIRST if sunday_first else _HEADERS_MON_FIRST

        cal  = calendar.Calendar(firstweekday=first_weekday)
        days = cal.monthdatescalendar(year, month)

        # ── Measure the space first, then cut the cells to fit it ────────────
        # The old code let the cells size themselves around their text, so the
        # whole calendar grew and shrank as layers were switched on and off.
        # Now the space decides, and the text is fitted into it.
        self.canvas.update_idletasks()
        avail_w = self.canvas.winfo_width()
        avail_h = self.canvas.winfo_height()
        if avail_w <= 1:            # first draw - the canvas has no size yet
            avail_w = 940
        if avail_h <= 1:
            avail_h = 420
        self._last_layout = (avail_w, avail_h)

        rows      = len(days)
        head_h    = 22
        week_w    = 34
        cell_w    = max(70, (avail_w - week_w - 18) // 7)
        cell_h    = max(46, (avail_h - head_h - 2 * (rows + 1)) // rows)
        # One line of Arial 7 is about 12 px high and about 4.6 px per
        # character; the day number takes the first ~18 px of the cell.
        max_lines = max(1, (cell_h - 18) // 12)
        max_chars = max(6, int((cell_w - 10) / 4.6))
        self._cell_metrics = (cell_w, cell_h, max_lines, max_chars)
        self._cell_hidden  = {}

        for col, hdr in enumerate(headers):
            ttk.Label(self.grid_frame, text=hdr, style="Header.TLabel").grid(
                row=0, column=col, padx=1, pady=2, sticky="ew")

        for row_idx, week in enumerate(days, start=1):
            week_num = week[0].isocalendar()[1]
            ttk.Label(self.grid_frame, text=str(week_num), style="Header.TLabel").grid(
                row=row_idx, column=0, padx=2, pady=2)
            for col_idx, day in enumerate(week, start=1):
                self.create_day_cell(day, row_idx, col_idx)

        # The week-number column keeps its narrow width; the seven day columns
        # share everything else, in both directions.
        self.grid_frame.columnconfigure(0, weight=0, minsize=week_w, uniform="")
        for c in range(1, 8):
            self.grid_frame.columnconfigure(c, weight=1, uniform="cols")
        self.grid_frame.rowconfigure(0, weight=0, uniform="")
        for r in range(1, rows + 1):
            self.grid_frame.rowconfigure(r, weight=1, uniform="rows")

        self.canvas.itemconfigure(self._grid_window, width=avail_w, height=avail_h)
        self.canvas.configure(scrollregion=(0, 0, avail_w, avail_h))

    def create_day_cell(self, day, row, col):
        is_today    = (day == self.today.date())
        is_holiday  = day in self.holidays
        is_selected = (day == self.selected_date)

        if is_selected:
            bg = "#cce5ff"
        elif is_today:
            bg = "lightblue"
        elif is_holiday:
            bg = "mistyrose"
        else:
            bg = "white"

        cell_w, cell_h, max_lines, max_chars = self._cell_metrics

        cell = tk.Frame(self.grid_frame, background=bg, bd=1, relief="solid")
        cell.grid(row=row, column=col, padx=1, pady=1, sticky="nsew")
        cell.grid_propagate(False)
        cell.configure(width=cell_w, height=cell_h)

        fg = "navy" if is_today else "black"
        tk.Label(cell, text=str(day.day), background=bg, foreground=fg,
                 font=("Arial", 9, "bold" if is_today else "normal")).pack(anchor="nw", padx=2, pady=1)

        # Everything competing for the cell's lines, in priority order:
        # holiday, my own events (red), then the BirthdayTracker layers (green,
        # so they never read as one of my own).
        lines = []
        if is_holiday:
            lines.append((self.holidays[day], "#880000", ("Arial", 7, "italic")))
        day_key = day.strftime("%Y-%m-%d")
        starts = self.core.repeat_starts()
        others = self.core.foreign_keys()                        # the events of other people are blue, mine are red
        for ev in self.events.get(day_key, []):
            p_ev = ev_parse(ev)
            colour = "#1a4fa0" if p_ev and (day_key, p_ev[0], p_ev[1]) in others else "red"
            lines.append(("↻ " + ev if p_ev and (day_key, p_ev[0], p_ev[1]) in starts else ev, colour, ("Arial", 7)))
        for _iid, rec in self.core.occurrences_on(day_key):      # the other days of a repeating event are drawn from its rule
            lines.append(("↻ " + ev_string(rec["t"], rec["x"]), "red" if self.core.is_mine(rec) else "#1a4fa0", ("Arial", 7)))
        for text in self._bt_marks.get(day, []):
            lines.append((text, "#1b6b2a", ("Arial", 7)))

        # Show what fits; if anything is left over, the last line says so and
        # the whole day is one click away in its own window.
        shown = lines if len(lines) <= max_lines else lines[:max(0, max_lines - 1)]
        for text, colour, font in shown:
            tk.Label(cell,
                     text=(text[:max_chars - 1] + "…" if len(text) > max_chars else text),
                     background=bg, foreground=colour, font=font,
                     anchor="w", width=1).pack(fill="x", padx=2)

        hidden = len(lines) - len(shown)
        self._cell_hidden[day] = hidden
        if hidden:
            tk.Label(cell, text=f"+{hidden} more …", background=bg,
                     foreground="#444444", font=("Arial", 7, "italic"),
                     anchor="w", width=1).pack(fill="x", padx=2)

        for w in (cell,) + tuple(cell.winfo_children()):
            try:
                w.bind("<Button-1>", lambda e, d=day: self.select_day(d))
            except Exception:
                pass

    def select_day(self, day):
        # A click draws the whole month again, which replaces the cell under the mouse - so tk never sees the second click of a double-click
        # as a double-click (the old "double-click to open the day" hardly ever worked).  The second click on the same day within half a
        # second opens the day window instead, and a click on the day that is already selected does not redraw anything (no blinking).
        now = _time.monotonic()
        last = getattr(self, "_last_click", None)
        self._last_click = (day, now)
        if last and last[0] == day and now - last[1] < 0.5:
            self._last_click = None
            self.show_day_popup(day)
            return
        if day == self.selected_date:
            if self._cell_hidden.get(day):
                self.show_day_popup(day)
            return
        self.selected_date = day
        self.show_notes_for_day(day)
        self.refresh_calendar()
        # Only when the cell could not show everything: then a click opens the
        # day in its own window, where there is all the room it needs. A day
        # that fits is simply selected, the way it always was.
        if self._cell_hidden.get(day):
            self.show_day_popup(day)

    # ── One day, in full ───────────────────────────────────────────────────────
    def show_day_popup(self, day):
        """Everything on one day, untruncated, in a window of its own.

        Not modal, and only ever one at a time: clicking through several busy
        days replaces the window instead of stacking up a pile of them.
        """
        old = getattr(self, "_day_popup", None)
        if old is not None:
            try:
                old.destroy()
            except Exception:
                pass
        self._day_popup = None

        root = self.winfo_toplevel()
        top  = tk.Toplevel(root)
        self._day_popup = top
        top.title(day.strftime("%Y-%m-%d"))
        top.transient(root)
        top.bind("<Escape>", lambda e: top.destroy())
        top.protocol("WM_DELETE_WINDOW", top.destroy)

        # ── Header: weekday, date, week number ───────────────────────────────
        hdr = tk.Frame(top, background="#f0f4f8")
        hdr.pack(fill="x")
        tk.Label(hdr, text=day.strftime("%A %d %B %Y"),
                 background="#f0f4f8", font=("Segoe UI", 12, "bold")).pack(
                     anchor="w", padx=14, pady=(12, 0))
        sub = f"Week {day.isocalendar()[1]}"
        if day in self.holidays:
            sub += f"   ·   {self.holidays[day]}"
        tk.Label(hdr, text=sub, background="#f0f4f8", foreground="#555555",
                 font=("Segoe UI", 9)).pack(anchor="w", padx=14, pady=(1, 12))
        tk.Frame(top, background="#cccccc", height=1).pack(fill="x")

        body = tk.Frame(top, background="white")
        body.pack(fill="both", expand=True)

        def section(title):
            tk.Label(body, text=title, background="white", foreground="#333333",
                     font=("Segoe UI", 9, "bold")).pack(anchor="w", padx=14, pady=(10, 2))

        def row(text, colour):
            tk.Label(body, text=text, background="white", foreground=colour,
                     font=("Segoe UI", 9), justify="left", anchor="w").pack(
                         anchor="w", fill="x", padx=24)

        # ── My own events ────────────────────────────────────────────────────
        day_key = day.strftime("%Y-%m-%d")
        own = self.events.get(day_key, [])
        virtual = self.core.occurrences_on(day_key)          # other days of a repeating event: drawn from its rule, not in the events dict
        if own or virtual:
            section("Events")
            names = dict(REMIND_CHOICES)
            for ev, vid in [(e, None) for e in list(own)] + [(ev_string(rec["t"], rec["x"]), iid) for iid, rec in virtual]:
                line = tk.Frame(body, background="white")
                line.pack(fill="x", padx=24)
                p_ev = ev_parse(ev)
                _i = None
                if vid:
                    rec = self.core.items[vid]
                else:
                    _i, rec = self.core.record_for(day_key, ev)
                rec_id = vid or (_i if rec else None)
                mine = rec is None or self.core.is_mine(rec)
                if mine:
                    rem = (rec.get("r", list(DEFAULT_REMIND)) if rec else self.core.reminders_for(day_key, ev)) if p_ev else []
                    soft = rec.get("qt", []) if rec else []
                else:
                    rem, soft = self.core.effective_reminders(rec_id, rec)
                rp = rec.get("rp") if rec else None
                tk.Label(line, text=("↻ " if rp else "") + ev, background="white", foreground="#b00000" if mine else "#1a4fa0",
                         font=("Segoe UI", 9), justify="left", anchor="w", wraplength=420).pack(side="left", fill="x", expand=True)
                extra = []
                if rec and not mine:
                    extra.append("👤 from " + self.core.maker_name(rec))
                elif rec and len(self.core.people) > 1:
                    extra.append(("🔒 " if not rec.get("v") else "👥 ") + v_label(rec.get("v"), self.core.people, self.core.me))
                if rec and rec.get("w"):
                    extra.append("about " + ", ".join(rec["w"]))
                if p_ev and (rem != DEFAULT_REMIND or soft):
                    extra.append(", ".join(("🔔 " if m in soft else "⏰ ") + names.get(m, f"{m} min") for m in rem) if rem else "🔕 no reminder")
                if rp:
                    extra.append("🔁 " + rp_label(rp))
                if extra:
                    tk.Label(line, text="   ".join(extra), background="white", foreground="#777777", font=("Segoe UI", 8)).pack(side="left", padx=6)

                def _edit(e=ev, v=vid):
                    top.destroy()
                    self.edit_event(day_key, e, v)

                def _delete(e=ev, v=vid):
                    top.destroy()
                    self.delete_event(day_key, e, v)

                def _leave_out(r_id=rec_id):
                    top.destroy()
                    self.leave_out_event(r_id)
                if mine:
                    ttk.Button(line, text="✎", width=3, command=_edit).pack(side="right", padx=(2, 0))
                    ttk.Button(line, text="🗑", width=3, command=_delete).pack(side="right")
                else:                                       # somebody else's event: only my own settings can change
                    ttk.Button(line, text="⚙", width=3, command=_edit).pack(side="right", padx=(2, 0))
                    ttk.Button(line, text="✖", width=3, command=_leave_out).pack(side="right")

        # ── BirthdayTracker ──────────────────────────────────────────────────
        marks = self._bt_marks.get(day, [])
        if marks:
            section("From BirthdayTracker")
            can_share = self.core.me == OWNER_ID and len(self.core.people) > 1
            share = self._marks_share()
            for text in marks:
                pkey = getattr(self, "_bt_who", {}).get((day, text))
                if not (can_share and pkey):
                    row(text, "#1b6b2a")
                    continue
                line = tk.Frame(body, background="white")
                line.pack(fill="x", padx=24)
                tk.Label(line, text=text, background="white", foreground="#1b6b2a", font=("Segoe UI", 9), justify="left", anchor="w").pack(side="left")
                tk.Label(line, text="👥 " + v_label(self._marks_audience(pkey, share), self.core.people, self.core.me), background="white",
                         foreground="#777777", font=("Segoe UI", 8)).pack(side="left", padx=8)
                ttk.Button(line, text="Share…", width=7,
                           command=lambda k=pkey: (top.destroy(), self.show_birthday_share_dialog(pick=k))).pack(side="right")

        # ── The note ─────────────────────────────────────────────────────────
        note = self.notes.get(day.strftime("%Y-%m-%d"), "")
        if note:
            section("Note")
            note_box = tk.Text(body, height=min(8, note.count("\n") + 2),
                               wrap="word", relief="flat", background="#fbfbfb",
                               font=("Segoe UI", 9),
                               insertofftime=0, insertontime=9_999_999)
            no_blink(note_box)
            note_box.insert("1.0", note)
            note_box.configure(state="disabled")
            note_box.pack(fill="x", padx=24, pady=(0, 4))

        if not (own or virtual or marks or note or day in self.holidays):
            section("Nothing on this day")

        # ── Footer ───────────────────────────────────────────────────────────
        tk.Frame(top, background="#cccccc", height=1).pack(fill="x", pady=(10, 0))
        bar = tk.Frame(top)
        bar.pack(fill="x", padx=12, pady=8)
        ttk.Button(bar, text="Close", command=top.destroy).pack(side="right")
        # Select the day first: add_event() adds to the SELECTED day, and the
        # window can be opened for a day that was never clicked.
        def _add_here():
            top.destroy()
            self.selected_date = day
            self.show_notes_for_day(day)
            self.add_event()

        ttk.Button(bar, text="➕ Add event", command=_add_here).pack(
            side="right", padx=(0, 6))
        tk.Label(bar, text="Esc closes", foreground="gray",
                 font=("Segoe UI", 8, "italic")).pack(side="left")

        # Beside the parent window, never on top of the calendar it describes
        top.update_idletasks()
        x = root.winfo_rootx() + max(0, (root.winfo_width() - top.winfo_width()) // 2)
        y = root.winfo_rooty() + max(0, (root.winfo_height() - top.winfo_height()) // 2)
        top.geometry(f"+{x}+{y}")
        top.minsize(340, 160)
        top.focus_set()

    # ── Events ─────────────────────────────────────────────────────────────────
    def add_event(self):
        self.edit_event(self.selected_date.strftime("%Y-%m-%d"), None)

    def _ask_scope(self, title, options):
        """A small modal window with one button per choice [(key, label), ...]; returns the key of the one pressed, or None (Cancel / Escape)."""
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title(title)
        top.transient(root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(False, False)
        result = [None]

        def pick(key):
            result[0] = key
            top.destroy()

        ttk.Label(top, text=title, font=("Segoe UI", 10, "bold")).pack(padx=14, pady=(12, 6), anchor="w")
        for key, label in options:
            ttk.Button(top, text=label, width=34, command=lambda k=key: pick(k)).pack(padx=14, pady=2)
        ttk.Button(top, text="Cancel", command=top.destroy).pack(padx=14, pady=(8, 12), anchor="e")
        top.wait_window()
        return result[0]

    def _events_remove(self, date_key, s):
        """Takes one string out of the events dict (and the day when it was the last one)."""
        lst = self.events.get(date_key, [])
        if s in lst:
            lst.remove(s)
            if not lst:
                del self.events[date_key]

    def _drop_first_occurrence(self, rec, iid=None):
        """Deletes the FIRST day of a repeating event: its string moves to the next day (and goes altogether when nothing is left of it)."""
        s = ev_string(rec["t"], rec["x"])
        nxt = CalCore.series_without_first(rec)
        self._events_remove(rec["d"], s)
        if nxt is None:
            return
        nd, nrp = nxt
        self.events.setdefault(nd, []).append(s)
        self.core.set_hint(nd, rec["t"], rec["x"], rec.get("r", DEFAULT_REMIND), rec.get("qt", []), nrp,
                           v=rec.get("v"), w=rec.get("w"), pl=rec.get("pl", ""), cm=rec.get("cm", ""), keep=iid)

    # ── People: who sees an event, who it is about, the events of others ────────────
    def _marks_share(self):
        """{BirthdayTracker person key: "all" | [person ids]} = who sees THAT person's birthday etc. on their phone.  A person who is not in it is
        seen by nobody but me (the default).  Chosen one person at a time in  Share birthdays…  (People window or the 👥 in the day window)."""
        d = load_cfg().get("marks_share", {})
        return d if isinstance(d, dict) else {}

    def _v_from_cfg(self, d):
        """An audience as it is kept in the settings file ("me" / "all" / "a!leo,mio" / [ids]) -> None / "a" / "a!.." / [ids], without people that are gone."""
        people, me = self.core.people, self.core.me
        if d == "all":
            return "a"
        if isinstance(d, str) and d.startswith("a!"):
            return v_canon("a!" + ",".join(p for p in d[2:].split(",") if p in people and p != me))
        if isinstance(d, list):
            return v_canon([p for p in d if p in people and p != me])
        return None

    @staticmethod
    def _v_to_cfg(v):
        if v == "a":
            return "all"
        if v_is_all(v):
            return v
        return list(v) if v else "me"

    def _marks_audience(self, pkey, share=None):
        """The audience of one BirthdayTracker person: None = only me, "a" = everybody, "a!.." = everybody except, or a list of person ids."""
        return self._v_from_cfg((self._marks_share() if share is None else share).get(pkey))

    def _default_v(self):
        """The audience a NEW event starts with (chosen in the People window): None = only me, "a" = everybody, "a!.." = everybody except, or a list of people."""
        return self._v_from_cfg(load_cfg().get("default_v", "me"))

    def _audience_widget(self, parent, current, on_change=None):
        """Radio buttons 'Only me / Everybody (with 'except' boxes) / These people' with one check box per other person.
        Returns (frame, getter); getter() = None / "a" / "a!ids" / [ids]."""
        frame = ttk.Frame(parent)
        others = {p: n for p, n in self.core.people.items() if p != self.core.me}
        mode = tk.StringVar(value="a" if v_is_all(current) else ("some" if isinstance(current, list) and current else "me"))
        picks = {p: tk.BooleanVar(value=isinstance(current, list) and p in current) for p in others}
        leave = {p: tk.BooleanVar(value=p in v_except(current)) for p in others}

        def changed(*_):
            if on_change:
                on_change()

        def pick_one():
            if any(v.get() for v in picks.values()):
                mode.set("some")
            changed()

        def leave_one():
            mode.set("a")
            changed()
        ttk.Radiobutton(frame, text="Only me", variable=mode, value="me", command=changed).pack(anchor="w")
        ttk.Radiobutton(frame, text="Everybody on the calendar (also people added later)", variable=mode, value="a", command=changed).pack(anchor="w")
        if others:
            row0 = ttk.Frame(frame)
            row0.pack(anchor="w", padx=(22, 0))
            ttk.Label(row0, text="except:", foreground="#777777").pack(side="left", padx=(0, 6))
            for p, n in sorted(others.items(), key=lambda a: a[1].lower()):
                ttk.Checkbutton(row0, text=n, variable=leave[p], command=leave_one).pack(side="left", padx=(0, 8))
            ttk.Radiobutton(frame, text="Me and only these people:", variable=mode, value="some", command=changed).pack(anchor="w")
            row = ttk.Frame(frame)
            row.pack(anchor="w", padx=(22, 0))
            for p, n in sorted(others.items(), key=lambda a: a[1].lower()):
                ttk.Checkbutton(row, text=n, variable=picks[p], command=pick_one).pack(side="left", padx=(0, 8))
        else:
            ttk.Label(frame, text="(nobody else yet: add people with the 👥 People button)", foreground="#777777").pack(anchor="w", padx=(22, 0))

        def getter():
            if mode.get() == "a":
                left = [p for p, v in leave.items() if v.get()]
                return v_canon("a!" + ",".join(left)) if left else "a"
            if mode.get() == "some":
                return v_canon([p for p, v in picks.items() if v.get()])
            return None
        return frame, getter
    def _after_override(self):
        """Common ending after my own settings for somebody's event changed: files, mirror, sync, screen, alarms."""
        self._write_files()
        self.core.save()
        self.request_sync()
        self.refresh_calendar()
        self._run_alarm_check()

    def leave_out_event(self, iid):
        """'Not interested': an event of somebody else disappears from MY calendar (and my phone); the maker and the others keep it."""
        rec = self.core.items.get(iid)
        if not rec or self.core.is_mine(rec):
            return
        if not messagebox.askyesno("Leave out", f"Leave this event out of your calendar?\n\n{rec['d']}  {ev_string(rec['t'], rec['x']).splitlines()[0][:70]}\n\n"
                                   f"It is only hidden for you ({self.core.maker_name(rec)} and the others still have it). "
                                   f"You can bring it back from the People window.", parent=self.winfo_toplevel()):
            return
        self.core.set_override(iid, self.events, self.notes, hid=True)
        self._after_override()

    def edit_foreign_event(self, date_key, old, iid, rec):
        """The window of an event somebody else made: it cannot be changed, but I can pick my OWN reminders for it or leave it out."""
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title(f"Event of {self.core.maker_name(rec)} – {date_key}")
        top.transient(root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(False, False)
        tk.Label(top, justify="left", anchor="w", wraplength=420, font=("Segoe UI", 10, "bold"),
                 text=f"{rec['d']} {rec['t']}\n{rec['x']}").pack(padx=12, pady=(12, 2), anchor="w")
        facts = [f"Made by {self.core.maker_name(rec)}"]
        if rec.get("w"):
            facts.append("About: " + ", ".join(rec["w"]))
        if rec.get("pl"):
            facts.append("Place: " + rec["pl"])
        if rec.get("cm"):
            facts.append("Note: " + rec["cm"])
        tk.Label(top, text="\n".join(facts), justify="left", anchor="w", wraplength=420, foreground="#555555",
                 font=("Segoe UI", 9)).pack(padx=12, anchor="w")
        ttk.Label(top, text="My own reminders for it (this PC and my phone; the others keep theirs):").pack(padx=12, pady=(10, 0), anchor="w")
        cur_r, cur_q = self.core.effective_reminders(iid, rec)
        rf = ttk.Frame(top)
        rf.pack(padx=12, anchor="w")
        rem_vars, soft_vars = {}, {}
        for mins, label in REMIND_CHOICES:
            row = ttk.Frame(rf)
            row.pack(anchor="w", fill="x")
            rem_vars[mins] = tk.BooleanVar(value=mins in cur_r)
            ttk.Checkbutton(row, text=label, variable=rem_vars[mins]).pack(side="left")
            soft_vars[mins] = tk.BooleanVar(value=mins in cur_q)
            ttk.Checkbutton(row, text="quiet", variable=soft_vars[mins]).pack(side="left", padx=(14, 0))
        status = tk.Label(top, text="", foreground="#1b6b2a", font=("Segoe UI", 9))
        status.pack(padx=12, pady=(4, 0), anchor="w")

        def save_mine():
            chosen = [m for m, v in rem_vars.items() if v.get()]
            self.core.set_override(iid, self.events, self.notes, reminders=chosen, quiet=[m for m in chosen if soft_vars[m].get()])
            self._after_override()
            top.destroy()

        def reset():
            self.core.set_override(iid, self.events, self.notes, reset_reminders=True)
            self._after_override()
            top.destroy()

        def leave():
            top.destroy()
            self.leave_out_event(iid)
        bf = ttk.Frame(top)
        bf.pack(fill="x", padx=12, pady=10)
        ttk.Button(bf, text="Save my reminders", command=save_mine).pack(side="left")
        ttk.Button(bf, text=f"Use {self.core.maker_name(rec)}'s", command=reset).pack(side="left", padx=4)
        ttk.Button(bf, text="Leave out of my calendar", command=leave).pack(side="left")
        ttk.Button(bf, text="Close", command=top.destroy).pack(side="right")

    def edit_event(self, date_key, old, iid=None):
        """The event window.  old = None: a new event on date_key.  old = the event's string: change that event (date, time, text, reminders,
        repeat, who sees it, who it is about).  iid = the id of a repeating event when old is one of its LATER days (those are not in the events
        dict, see CalCore.occurrences_on).  An event somebody else made opens its own small window (edit_foreign_event)."""
        if old is not None:
            sid0, rec0 = (iid, self.core.items.get(iid)) if iid else self.core.record_for(date_key, old)
            if rec0 is not None and not self.core.is_mine(rec0):
                return self.edit_foreign_event(date_key, old, sid0, rec0)
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title(f"Event – {date_key}" if old is None else f"Change event – {date_key}")
        top.transient(root)
        top.grab_set()
        top.focus_force()                               # FIX: focus so ESC works
        top.bind("<Escape>", lambda e: top.destroy())   # FIX: ESC closes
        top.resizable(False, False)

        p_old = ev_parse(old) if old else None
        sid, rec = (iid, self.core.items.get(iid)) if iid else (self.core.record_for(date_key, old) if old else (None, None))
        series = rec if (rec and rec.get("rp")) else None
        rem_old = list(rec.get("r", DEFAULT_REMIND)) if (iid and rec) else (self.core.reminders_for(date_key, old) if old else list(DEFAULT_REMIND))
        soft_old = set(rec.get("qt", [])) if rec else set()
        rp_old = series["rp"] if series else None
        occ_date = _pd(date_key)

        ttk.Label(top, text="Date (YYYY-MM-DD):").pack(pady=(10, 0), padx=10, anchor="w")
        date_entry = tk.Entry(top, width=12, insertofftime=0, insertontime=9_999_999)
        no_blink(date_entry)
        date_entry.insert(0, date_key)
        date_entry.pack(padx=10, anchor="w")

        ttk.Label(top, text="Time (HH:MM):").pack(pady=(8, 0), padx=10, anchor="w")
        time_entry = tk.Entry(top, width=10, insertofftime=0, insertontime=9_999_999)
        no_blink(time_entry)
        if p_old:
            time_entry.insert(0, p_old[0])
        time_entry.pack(padx=10, anchor="w")

        ttk.Label(top, text="Description:").pack(pady=(8, 0), padx=10, anchor="w")
        desc_text = tk.Text(top, height=4, width=40, insertofftime=0, insertontime=9_999_999)
        no_blink(desc_text)
        if old:
            desc_text.insert("1.0", p_old[1] if p_old else old)
        desc_text.pack(padx=10, pady=(0, 5))

        # Reminders: any number of them; the phone rings for each one as well (phone sync), or only shows a quiet notification
        ttk.Label(top, text="Remind me (the phone rings too - or, if 'quiet', only shows a notification):").pack(pady=(4, 0), padx=10, anchor="w")
        rf = ttk.Frame(top)
        rf.pack(padx=10, anchor="w")
        rem_vars, soft_vars = {}, {}
        for mins, label in REMIND_CHOICES:
            row = ttk.Frame(rf)
            row.pack(anchor="w", fill="x")
            v = tk.BooleanVar(value=mins in rem_old)
            rem_vars[mins] = v
            ttk.Checkbutton(row, text=label, variable=v).pack(side="left")
            q = tk.BooleanVar(value=mins in soft_old)
            soft_vars[mins] = q
            ttk.Checkbutton(row, text="quiet", variable=q).pack(side="left", padx=(14, 0))

        # Repeat: never / every day / week / month / year, every N, until a day
        freq_names = {"": "Never", "d": "Every day", "w": "Every week", "m": "Every month", "y": "Every year"}
        ttk.Label(top, text="Repeat:").pack(pady=(6, 0), padx=10, anchor="w")
        rpf = ttk.Frame(top)
        rpf.pack(padx=10, anchor="w")
        freq_var = tk.StringVar(value=freq_names[rp_old["f"] if rp_old else ""])
        ttk.Combobox(rpf, textvariable=freq_var, values=list(freq_names.values()), state="readonly", width=13).pack(side="left")
        ttk.Label(rpf, text="  once in every").pack(side="left")
        every_var = tk.StringVar(value=str(rp_old.get("i", 1)) if rp_old else "1")
        ttk.Spinbox(rpf, from_=1, to=99, width=4, textvariable=every_var).pack(side="left", padx=4)
        ttk.Label(rpf, text="(1 = every time, 2 = every other ...)").pack(side="left")
        rpf2 = ttk.Frame(top)
        rpf2.pack(padx=10, pady=(2, 0), anchor="w")
        ttk.Label(rpf2, text="Until (YYYY-MM-DD, empty = no end):").pack(side="left")
        until_entry = tk.Entry(rpf2, width=12, insertofftime=0, insertontime=9_999_999)
        no_blink(until_entry)
        until_entry.insert(0, rp_old.get("e", "") if rp_old else "")
        until_entry.pack(side="left", padx=4)
        if series:
            ttk.Label(top, text="This is one day of a repeating event: you are asked which events to change.", foreground="#555555").pack(padx=10, anchor="w")

        # Who can see it, and who it is about (people on the same calendar, half separate).  A new event starts with the default of the People window.
        ttk.Label(top, text="Who can see it:").pack(pady=(8, 0), padx=10, anchor="w")
        aud_frame, aud_get = self._audience_widget(top, rec.get("v") if rec else self._default_v())
        aud_frame.pack(padx=10, anchor="w")
        ttk.Label(top, text="About (pick a person or type a new name):").pack(pady=(6, 0), padx=10, anchor="w")
        about_var = tk.StringVar(value=", ".join(rec.get("w", [])) if rec else "")
        ttk.Combobox(top, textvariable=about_var, values=self.core.about_names(), width=38).pack(padx=10, anchor="w")
        pl0, cm0 = (rec.get("pl", ""), rec.get("cm", "")) if rec else ("", "")

        def save_event():
            tid         = time_entry.get().strip()
            description = desc_text.get("1.0", tk.END).strip()
            day         = date_entry.get().strip()
            if not tid or not description:
                messagebox.showwarning("Warning", "Both time and description are required!", parent=top)
                return
            try:
                datetime.strptime(tid, "%H:%M")
                new_date = datetime.strptime(day, "%Y-%m-%d").date()
            except ValueError:
                messagebox.showerror("Error", "Please enter the date as YYYY-MM-DD and the time as HH:MM", parent=top)
                return
            tid = datetime.strptime(tid, "%H:%M").strftime("%H:%M")   # 9:5 -> 09:05
            chosen = [m for m, v in rem_vars.items() if v.get()]
            quiet = [m for m in chosen if soft_vars[m].get()]
            rp_new = None
            fkey = {v: k for k, v in freq_names.items()}.get(freq_var.get(), "")
            if fkey:
                try:
                    n = int(every_var.get())
                except ValueError:
                    n = 0
                until = until_entry.get().strip()
                if not 1 <= n <= 99:
                    messagebox.showerror("Error", "'once in every' must be a number from 1 to 99.", parent=top)
                    return
                if until:
                    try:
                        ok = datetime.strptime(until, "%Y-%m-%d").date() >= new_date
                    except ValueError:
                        messagebox.showerror("Error", "Please enter the last day of the repeat as YYYY-MM-DD (or leave it empty).", parent=top)
                        return
                    if not ok:
                        messagebox.showerror("Error", "The last day of the repeat is before the first day.", parent=top)
                        return
                rp_new = {"f": fkey, "i": n, "e": until}
            new_s = f"{tid} {description}"
            new_v = aud_get()
            new_w = [s for s in about_var.get().split(",")]
            people_args = {"v": new_v, "w": new_w, "pl": pl0, "cm": cm0}
            if series is None:
                if old is not None:                         # change = take the old one away, then add the new one (it keeps the id of the old one)
                    self._events_remove(date_key, old)
                self.events.setdefault(day, []).append(new_s)
                self.core.set_hint(day, tid, description, chosen, quiet, rp_new, keep=sid, **people_args)
            else:
                scope = self._ask_scope("Change a repeating event", [("this", "This event only"), ("all", "All events")])
                if scope is None:
                    return
                if scope == "all":                          # the series itself changes; it moves by as many days as the date was changed
                    delta = (new_date - occ_date).days
                    self._events_remove(series["d"], ev_string(series["t"], series["x"]))
                    first = _pd(series["d"]) + timedelta(days=delta)
                    if rp_new is not None:
                        rp_new["x"] = [(_pd(s) + timedelta(days=delta)).isoformat() for s in rp_old.get("x", [])]
                        tmp = {"d": first.isoformat(), "rp": rp_new}
                        if rp_normalize(tmp):
                            first, rp_new = _pd(tmp["d"]), tmp["rp"]
                        else:
                            rp_new.pop("x", None)
                    self.events.setdefault(first.isoformat(), []).append(new_s)
                    self.core.set_hint(first.isoformat(), tid, description, chosen, quiet, rp_new, keep=sid, **people_args)
                else:                                       # this day only: it leaves the series and becomes an event of its own
                    self.events.setdefault(day, []).append(new_s)
                    self.core.set_hint(day, tid, description, chosen, quiet, None, **people_args)
                    if date_key == series["d"]:
                        self._drop_first_occurrence(series, sid)
                    else:
                        self.core.series_exclude(sid, date_key)
                        self.core.save()
            self.save_data()
            top.destroy()
            self.selected_date = new_date
            self.refresh_calendar()
            # Run alarm check immediately without creating a new recurring timer
            self._run_alarm_check()

        bf = ttk.Frame(top)
        bf.pack(fill="x", padx=10, pady=8)
        ttk.Button(bf, text="Save",   command=save_event).pack(side="right", padx=4)
        ttk.Button(bf, text="Cancel", command=top.destroy).pack(side="right")
        time_entry.focus()

    def delete_event(self, date_key, s, iid=None):
        p = ev_parse(s)
        shown = (p[1] if p else s).splitlines()[0][:60]
        sid, rec = (iid, self.core.items.get(iid)) if iid else self.core.record_for(date_key, s)
        if rec is not None and rec.get("rp"):                # one day of a repeating event: which ones?
            choice = self._ask_scope("Delete a repeating event", [("this", "This event only"), ("following", "This and the following events"),
                                                                  ("all", "All events")])
            if choice is None:
                return
            if choice == "all" or (choice == "following" and date_key == rec["d"]):
                self._events_remove(rec["d"], ev_string(rec["t"], rec["x"]))
            elif choice == "following":
                self.core.series_end_before(sid, date_key)
                self.core.save()
            elif date_key == rec["d"]:
                self._drop_first_occurrence(rec, sid)
            else:
                self.core.series_exclude(sid, date_key)
                self.core.save()
        else:
            if not messagebox.askyesno("Delete event", f"Delete this event?\n\n{date_key}  {s.splitlines()[0][:70]}\n\n"
                                       f"It disappears from the phone too.", parent=self.winfo_toplevel()):
                return
            self._events_remove(date_key, s)
        self.save_data()
        self.refresh_calendar()
        self._run_alarm_check()
        logger.info(f"Event deleted on {date_key}: {shown}")

    # ── Notes ──────────────────────────────────────────────────────────────────
    def show_notes_for_day(self, date):
        self.notes_text.config(state="normal")
        self.notes_text.delete("1.0", tk.END)
        key = date.strftime("%Y-%m-%d")
        if key in self.notes:
            self.notes_text.insert(tk.END, self.notes[key])
        self._show_bt_for_day(date)

    def _show_bt_for_day(self, date):
        """The BirthdayTracker line above the note box, for one day."""
        marks = bt_marks_for_month(date.year, date.month,
                                   base=self.show_bt.get(),
                                   extras=self.show_extras.get()).get(date, [])
        self.bt_day_label.config(text="   ·   ".join(marks))

    def save_note(self):
        text = self.notes_text.get("1.0", tk.END).strip()
        key  = self.selected_date.strftime("%Y-%m-%d")
        if text:
            self.notes[key] = text
        elif key in self.notes:
            del self.notes[key]
        self.save_data()

    def clear_note(self):
        self.notes_text.delete("1.0", tk.END)
        key = self.selected_date.strftime("%Y-%m-%d")
        if key in self.notes:
            del self.notes[key]
            self.save_data()

    # ── Navigation ─────────────────────────────────────────────────────────────
    def prev_month(self):
        self.current_date = (self.current_date.replace(day=1) - timedelta(days=1)).replace(day=1)
        self.refresh_calendar()

    def next_month(self):
        self.current_date = (self.current_date.replace(day=28) + timedelta(days=4)).replace(day=1)
        self.refresh_calendar()

    def go_to_today(self):
        self.current_date  = self.today.replace(day=1)
        self.selected_date = self.today.date()
        self.refresh_calendar()
        self.show_notes_for_day(self.today.date())

    # ── E-mail ─────────────────────────────────────────────────────────────────
    def save_email(self):
        email = self.email_entry.get().strip()
        if not email:
            return
        try:
            EMAIL_PATH.write_text(email, encoding="utf-8")
            logger.info(f"E-mail saved: {email}")
        except Exception as e:
            messagebox.showerror("Error", f"Could not save e-mail: {e}", parent=self)

    # ── Data I/O ───────────────────────────────────────────────────────────────
    def load_data(self):
        try:
            self.events = json.loads(EVENTS_PATH.read_text(encoding="utf-8"))
        except Exception:
            self.events = {}
        try:
            self.notes = json.loads(NOTES_PATH.read_text(encoding="utf-8"))
        except Exception:
            self.notes = {}
        try:
            self.email_entry.insert(0, EMAIL_PATH.read_text(encoding="utf-8").strip())
        except Exception:
            pass

    def _write_files(self):
        try:
            EVENTS_PATH.write_text(json.dumps(self.events, ensure_ascii=False, indent=2), encoding="utf-8")
            NOTES_PATH.write_text( json.dumps(self.notes,  ensure_ascii=False, indent=2), encoding="utf-8")
        except Exception as e:
            messagebox.showerror("Error", f"Could not save data: {e}", parent=self)
            logger.exception("Save error")

    def save_data(self):
        """Every change made here ends up in this one place: the files, the phone-sync mirror, and a sync a few seconds later."""
        self._write_files()
        self._reconcile_now()
        self.request_sync()

    # *************** DEL 41 - PHONE SYNC (the window side; the logic is CalCore, DEL 40) *****************
    def _reconcile_now(self):
        try:
            if self.core.reconcile(self.events, self.notes):
                self.core.save()
        except Exception:
            logger.exception("Phone sync: could not update the mirror")

    def _relay(self):
        """(address, key) from relay.json, or ('', '') when the phone sync is not set up."""
        try:
            d = json.loads(RELAY_PATH.read_text(encoding="utf-8"))
            return str(d.get("url", "")).strip(), str(d.get("key", "")).strip()
        except Exception:
            return "", ""

    def _push_marks(self):
        """Birthdays etc. (BirthdayTracker, the basic layer) for the next ~14 months go to the phone as read-only days."""
        if not BT_PERSONS_PATH.exists():
            return
        today = datetime.today().date()
        share = self._marks_share()
        try:
            stamp = (today, BT_PERSONS_PATH.stat().st_mtime, json.dumps(share, sort_keys=True), tuple(sorted(self.core.people)))
        except OSError:
            return
        if stamp == self._marks_stamp:
            return
        first, last = today - timedelta(days=7), today + timedelta(days=400)
        marks = {}
        y, m = first.year, first.month
        while (y, m) <= (last.year, last.month):
            who = {}
            for d, lines in bt_marks_for_month(y, m, base=True, extras=False, who=who).items():
                # every line goes with the audience of ITS person (the default: only me)
                marks[d.strftime("%Y-%m-%d")] = [(t, self._marks_audience(who.get((d, t), ""), share)) for t in lines]
            y, m = (y + 1, 1) if m == 12 else (y, m + 1)
        self.core.update_marks(marks, first.isoformat(), last.isoformat())
        self._marks_stamp = stamp

    def request_sync(self, delay_ms=4000):
        """A sync soon (a few seconds from now; many changes in a row make one sync).  Does nothing when the sync is not set up."""
        if not all(self._relay()):
            return
        if self._sync_after_id is not None:
            try:
                self.after_cancel(self._sync_after_id)
            except Exception:
                pass
        self._sync_after_id = self.after(delay_ms, self.sync_now)

    def _sync_tick(self):
        """Every 3 minutes: fetch what the phone has changed."""
        self.sync_now()
        self._sync_tick_id = self.after(180_000, self._sync_tick)

    def sync_now(self, manual=False):
        self._sync_after_id = None
        if self._sync_busy:
            return
        url, key = self._relay()
        if not url or not key:
            self._update_sync_label()
            return
        try:
            self._reconcile_now()
            self._push_marks()
            body = self.core.push_body(series=self.core.relay_v >= 2, people=self.core.relay_v >= 3)   # repeats / people wait until the relay has said that it keeps them
        except Exception:
            logger.exception("Phone sync: could not prepare")
            return
        self._sync_busy = True
        self.sync_label.config(text="Syncing…")
        q = queue.Queue()
        since = self.core.seq

        def work():
            try:
                q.put(("ok", relay_post(url, key, {"since": since, "items": body})))
            except SyncError as e:
                q.put(("err", str(e)))
            except Exception as e:                       # never let the worker die silently
                q.put(("err", f"Unexpected: {e}"))

        threading.Thread(target=work, daemon=True).start()
        self.after(150, lambda: self._sync_poll(q, body, manual))

    def _sync_poll(self, q, body, manual):
        try:
            kind, val = q.get_nowait()
        except queue.Empty:
            self.after(150, lambda: self._sync_poll(q, body, manual))
            return
        self._sync_busy = False
        if kind == "err":
            self.core.last_error = val
            logger.info(f"Phone sync failed: {val}")
        else:
            self.core.mark_pushed(body)
            was_v = self.core.relay_v
            self.core.note_relay_version(val.get("v"))
            self.core.note_people(val)
            if was_v < self.core.relay_v and self.core.held_back():
                self.request_sync(1500)                    # the relay was updated: the waiting repeats / shared events go now
            sel = self.selected_date.strftime("%Y-%m-%d")
            note_before = self.notes.get(sel, "")
            typed = self.notes_text.get("1.0", tk.END).strip()
            taken = self.core.apply_remote(val.get("items"), val.get("seq"), self.events, self.notes)
            self.core.last_ok = int(_time.time() * 1000)
            self.core.last_error = ""
            self.core.last_counts = (len(body), taken)
            self.core.forget_old()
            if taken:
                self._write_files()
                self.refresh_calendar()
                # The note box is only redrawn when the phone changed THIS day's note and nothing unsaved was typed in it
                if self.notes.get(sel, "") != note_before and typed == note_before.strip():
                    self.show_notes_for_day(self.selected_date)
                self._run_alarm_check()
            logger.info(f"Phone sync: sent {len(body)}, took {taken}")
        try:
            self.core.save()
        except Exception:
            logger.exception("Phone sync: could not save the mirror")
        self._update_sync_label()
        if manual and kind == "err":
            messagebox.showwarning("Phone sync", val, parent=self.winfo_toplevel())

    def _update_sync_label(self):
        if not all(self._relay()):
            text = "Phone sync not set up"
        elif self.core.last_error:
            text = "⚠ " + self.core.last_error
        elif self.core.last_ok:
            w = self.core.waiting()
            text = "📱 Synced " + datetime.fromtimestamp(self.core.last_ok / 1000).strftime("%H:%M") + (f" · {w} waiting" if w else "")
            if self.core.relay_v < 3 and self.core.held_back():
                text += " · sharing / repeats wait for the new relay (run job 'Calendar relay')"
        else:
            text = "📱 Not synced yet"
        try:
            self.sync_label.config(text=text)
        except Exception:
            pass

    def show_sync_dialog(self):
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title("Phone sync")
        top.transient(root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(False, False)
        url0, key0 = self._relay()

        tk.Label(top, justify="left", anchor="w", wraplength=460, font=("Segoe UI", 9),
                 text="The phone app Issu's Calendar and this window keep the same events and notes, through your own server. "
                      "The phone rings for every reminder, also with the screen off. The address and the key are private.").pack(
                          padx=12, pady=(12, 6), anchor="w")
        ttk.Label(top, text="Server address:").pack(padx=12, anchor="w")
        url_e = tk.Entry(top, width=58, insertofftime=0, insertontime=9_999_999)
        no_blink(url_e)
        url_e.insert(0, url0)
        url_e.pack(padx=12, anchor="w")
        ttk.Label(top, text="Key:").pack(padx=12, pady=(6, 0), anchor="w")
        key_e = tk.Entry(top, width=58, show="•", insertofftime=0, insertontime=9_999_999)
        no_blink(key_e)
        key_e.insert(0, key0)
        key_e.pack(padx=12, anchor="w")
        status = tk.Label(top, text="", foreground="#444444", font=("Segoe UI", 9), justify="left", anchor="w", wraplength=460)
        status.pack(padx=12, pady=(8, 0), anchor="w")

        def save():
            u, k = url_e.get().strip(), key_e.get().strip()
            if not u.startswith(("http://", "https://")) or len(k) < 8:
                status.config(text="The address must start with https:// and the key must be at least 8 characters.", foreground="#b00000")
                return False
            RELAY_PATH.write_text(json.dumps({"url": u if u.endswith("/") else u + "/", "key": k}, indent=2), encoding="utf-8")
            status.config(text="Saved.", foreground="#1b6b2a")
            return True

        def paste_code():
            try:
                text = top.clipboard_get()
            except Exception:
                text = ""
            got = pairing_parse(text)
            if not got:
                status.config(text="No phone code on the clipboard (it starts with ISSUSYNC1:).", foreground="#b00000")
                return
            if got[0] and got[0] != SYNC_APP:
                status.config(text=f"That code is for another app ({got[0]}).", foreground="#b00000")
                return
            url_e.delete(0, tk.END); url_e.insert(0, got[1])
            key_e.delete(0, tk.END); key_e.insert(0, got[2])
            if save():
                status.config(text="Code taken and saved.", foreground="#1b6b2a")

        def copy_code():
            if not save():
                return
            u, k = url_e.get().strip(), key_e.get().strip()
            top.clipboard_clear()
            top.clipboard_append(pairing_make(u if u.endswith("/") else u + "/", k))
            status.config(text="The phone code is on the clipboard. Paste it in the app (Settings > Sync with the PC). "
                               "It contains the key: send it only to your own phone.", foreground="#1b6b2a")

        def sync_and_close():
            if save():
                top.destroy()
                self.sync_now(manual=True)

        bf = ttk.Frame(top)
        bf.pack(fill="x", padx=12, pady=10)
        ttk.Button(bf, text="Sync now", command=sync_and_close).pack(side="right", padx=(4, 0))
        ttk.Button(bf, text="Close", command=top.destroy).pack(side="right")
        ttk.Button(bf, text="Save", command=save).pack(side="left")
        ttk.Button(bf, text="Paste code", command=paste_code).pack(side="left", padx=4)
        ttk.Button(bf, text="Copy phone code", command=copy_code).pack(side="left")
        url_e.focus()
        self._update_sync_label()

    # *************** DEL 42 - PEOPLE ON ONE CALENDAR (the window side; the logic is CalCore, DEL 40, and the relay, version 3) *****************
    def _people_call(self, body, parent):
        """One call of the owner's people operations; the answer, or None after the problem was shown."""
        url, key = self._relay()
        if not url or not key:
            messagebox.showinfo("People", "Set up the phone sync first (📱 Phone sync…).", parent=parent)
            return None
        try:
            ans = relay_post(url, key, body, path="/people")
        except SyncError as e:
            messagebox.showwarning("People", str(e), parent=parent)
            return None
        except Exception as e:
            messagebox.showwarning("People", f"Unexpected: {e}", parent=parent)
            return None
        if isinstance(ans.get("people"), dict):
            self.core.people = {pid: str(p.get("name", pid)) for pid, p in ans["people"].items() if not p.get("rev")}
            self.core.save()
        return ans

    def _ask_name(self, parent, title, initial=""):
        """A small modal 'Name:' window with a steady cursor (simpledialog's entry blinks); the text, or None after Cancel / Escape."""
        top = tk.Toplevel(parent)
        top.title(title)
        top.transient(parent)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(False, False)
        out = [None]
        ttk.Label(top, text="Name:").pack(padx=12, pady=(12, 0), anchor="w")
        e = tk.Entry(top, width=32, insertofftime=0, insertontime=9_999_999)
        no_blink(e)
        e.insert(0, initial)
        e.pack(padx=12, anchor="w")

        def ok(_e=None):
            out[0] = e.get()
            top.destroy()
        e.bind("<Return>", ok)
        bf = ttk.Frame(top)
        bf.pack(fill="x", padx=12, pady=10)
        ttk.Button(bf, text="OK", command=ok).pack(side="right", padx=(4, 0))
        ttk.Button(bf, text="Cancel", command=top.destroy).pack(side="right")
        e.focus_set()
        top.wait_window()
        return out[0]

    def _show_phone_code(self, parent, name, key):
        """The pairing code of a person, once: the relay keeps only a hash of the key, so it cannot be shown again (a new code can be made)."""
        url, _k = self._relay()
        code = pairing_make(url if url.endswith("/") else url + "/", key)
        top = tk.Toplevel(parent)
        top.title(f"Phone code for {name}")
        top.transient(parent)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(False, False)
        tk.Label(top, justify="left", anchor="w", wraplength=460, font=("Segoe UI", 9),
                 text=f"The code for {name}. It holds {name}'s own key: send it only to {name}. "
                      f"In the phone app: Settings > Sync with the PC > Paste code (on another PC: 📱 Phone sync… > Paste code). "
                      f"It is shown ONCE; if it is lost, make a new code.").pack(padx=12, pady=(12, 6), anchor="w")
        e = tk.Entry(top, width=60, insertofftime=0, insertontime=9_999_999)
        no_blink(e)
        e.insert(0, code)
        e.configure(state="readonly")
        e.pack(padx=12, anchor="w")
        st = tk.Label(top, text="", foreground="#1b6b2a", font=("Segoe UI", 9))
        st.pack(padx=12, pady=(4, 0), anchor="w")

        def copy():
            top.clipboard_clear()
            top.clipboard_append(code)
            st.config(text="Copied to the clipboard.")
        bf = ttk.Frame(top)
        bf.pack(fill="x", padx=12, pady=10)
        ttk.Button(bf, text="Copy", command=copy).pack(side="left")
        ttk.Button(bf, text="Close", command=top.destroy).pack(side="right")
        top.wait_window()

    def show_people_dialog(self):
        """People on this calendar: who they are (the owner makes them and their phone codes), what a NEW event starts with, sharing of the
        events that exist, and the events of others that I left out."""
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title("People")
        top.transient(root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(False, False)
        is_owner = self.core.me == OWNER_ID
        tk.Label(top, justify="left", anchor="w", wraplength=500, font=("Segoe UI", 9),
                 text="Several people can use the same calendar. Each person has an own phone code, so the server only gives a person what they may see. "
                      "Nothing is shared until you choose: every event says who can see it (only you, everybody, everybody except some people, or chosen people) and who it is about. "
                      "Anybody can leave out (✖) the events of others that do not interest them, and has their own reminders."
                 ).pack(padx=12, pady=(12, 6), anchor="w")
        ids = []
        lb = tk.Listbox(top, height=6, width=56, exportselection=False, activestyle="none")
        lb.pack(padx=12, anchor="w")
        status = tk.Label(top, text="", foreground="#444444", font=("Segoe UI", 9), justify="left", anchor="w", wraplength=500)

        revoked = set()

        def fill(listing=None):
            lb.delete(0, tk.END)
            ids.clear()
            revoked.clear()
            data = listing if listing is not None else {p: {"name": n, "rev": 0} for p, n in self.core.people.items()}
            for pid, p in sorted(data.items(), key=lambda a: (a[0] != OWNER_ID, a[1]["name"].lower())):
                if p.get("rev"):
                    revoked.add(pid)
                tag = "  (owner)" if pid == OWNER_ID else ""
                tag += "  (you)" if pid == self.core.me else ""
                tag += "  — access removed" if p.get("rev") else ""
                lb.insert(tk.END, p["name"] + tag)
                ids.append(pid)
        fill()

        def refresh():
            ans = self._people_call({"op": "list"}, top)
            if ans:
                fill(ans.get("people"))

        def selected():
            s = lb.curselection()
            return ids[s[0]] if s else None

        def ask_name(title, initial=""):
            return self._ask_name(top, title, initial)

        def add():
            name = ask_name("Add a person")
            if not name or not name.strip():
                return
            ans = self._people_call({"op": "add", "name": name.strip()}, top)
            if ans and ans.get("key"):
                fill(ans.get("people"))
                self._show_phone_code(top, name.strip(), ans["key"])

        def rename():
            pid = selected()
            if not pid:
                status.config(text="Pick a person in the list first.", foreground="#b00000")
                return
            name = ask_name("Rename", self.core.people.get(pid, ""))
            if name and name.strip():
                ans = self._people_call({"op": "rename", "id": pid, "name": name.strip()}, top)
                if ans:
                    fill(ans.get("people"))

        def newcode():
            pid = selected()
            if not pid or pid == OWNER_ID:
                status.config(text="Pick another person (not the owner) in the list first.", foreground="#b00000")
                return
            if not messagebox.askyesno("New phone code", "Make a new code for this person?\nTheir old code stops working at once.", parent=top):
                return
            ans = self._people_call({"op": "newkey", "id": pid}, top)
            if ans and ans.get("key"):
                fill(ans.get("people"))
                self._show_phone_code(top, self.core.people.get(pid, pid), ans["key"])

        def remove():
            pid = selected()
            if not pid or pid == OWNER_ID:
                status.config(text="Pick another person (not the owner) in the list first.", foreground="#b00000")
                return
            if not messagebox.askyesno("Remove access", f"Remove the access of {self.core.people.get(pid, pid)}?\n"
                                       f"Their phone and PC stop syncing. Their events stay where they are.", parent=top):
                return
            ans = self._people_call({"op": "revoke", "id": pid}, top)
            if ans:
                fill(ans.get("people"))

        def delete_from_list():
            pid = selected()
            if not pid or pid == OWNER_ID:
                status.config(text="Pick another person (not the owner) in the list first.", foreground="#b00000")
                return
            if pid not in revoked:
                status.config(text="Remove the access of that person first (Remove access…), then they can be deleted from the list.",
                              foreground="#b00000")
                return
            if not messagebox.askyesno("Delete from the list", "Delete %s from the list?\nWhat they made stays in the calendar as it is. "
                                       "(To let them in again later, add them as a new person.)" % lb.get(lb.curselection()[0]).split("  —")[0], parent=top):
                return
            ans = self._people_call({"op": "delete", "id": pid}, top)
            if ans:
                fill(ans.get("people"))

        bf = ttk.Frame(top)
        bf.pack(fill="x", padx=12, pady=(6, 0))
        for text, cmd in (("Add person…", add), ("Rename…", rename), ("New phone code…", newcode), ("Remove access…", remove),
                          ("Delete from list…", delete_from_list), ("Refresh", refresh)):
            b = ttk.Button(bf, text=text, command=cmd)
            b.pack(side="left", padx=(0, 4))
            if not is_owner and text != "Refresh":
                b.state(["disabled"])
        if not is_owner:
            tk.Label(top, text="Only the owner of the calendar adds or removes people.", foreground="#777777",
                     font=("Segoe UI", 8, "italic")).pack(padx=12, anchor="w")
        status.pack(padx=12, anchor="w")

        # What a NEW event starts with
        ttk.Label(top, text="A new event starts as visible to:", font=("Segoe UI", 9, "bold")).pack(padx=12, pady=(8, 0), anchor="w")
        cur = self._default_v()
        holder = {}

        def save_default():
            v = holder["get"]()
            cfg = load_cfg()
            cfg["default_v"] = self._v_to_cfg(v)
            save_cfg(cfg)
            status.config(text="Saved: new events start as '%s'." % v_label(v, self.core.people, self.core.me), foreground="#1b6b2a")
        frame, get = self._audience_widget(top, cur, on_change=save_default)
        holder["get"] = get
        frame.pack(padx=12, anchor="w")

        # The birthdays etc. from BirthdayTracker: shared ONE PERSON AT A TIME, in their own window (nobody gets any until you choose)
        if is_owner:
            tk.Label(top, justify="left", anchor="w", wraplength=500, font=("Segoe UI", 9), foreground="#444444",
                     text="Birthdays (from BirthdayTracker) are only on your own phone until you share them, one person at a time. "
                          "Everybody means everybody on the calendar, also people added later; tick a name under 'except' to keep one person out."
                     ).pack(padx=12, pady=(10, 0), anchor="w")

        bf2 = ttk.Frame(top)
        bf2.pack(fill="x", padx=12, pady=10)
        ttk.Button(bf2, text="Share my events…", command=lambda: (top.destroy(), self.show_share_dialog())).pack(side="left")
        if is_owner:
            ttk.Button(bf2, text="Share birthdays…", command=lambda: (top.destroy(), self.show_birthday_share_dialog())).pack(side="left", padx=4)
        ttk.Button(bf2, text="Events I left out…", command=lambda: (top.destroy(), self.show_hidden_dialog())).pack(side="left", padx=4)
        ttk.Button(bf2, text="Close", command=top.destroy).pack(side="right")

    def show_share_dialog(self):
        """Change who sees MY events that already exist: pick them in the list, pick the audience, Apply."""
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title("Share my events")
        top.transient(root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(False, False)
        tk.Label(top, justify="left", anchor="w", wraplength=520, font=("Segoe UI", 9),
                 text="Pick events (Ctrl / Shift for several), choose who can see them and press Apply. Events older than a month are not listed."
                 ).pack(padx=12, pady=(12, 4), anchor="w")
        box = ttk.Frame(top)
        box.pack(padx=12, anchor="w")
        lb = tk.Listbox(box, height=14, width=78, selectmode="extended", exportselection=False, activestyle="none")
        sb = ttk.Scrollbar(box, command=lb.yview)
        lb.configure(yscrollcommand=sb.set)
        lb.pack(side="left")
        sb.pack(side="left", fill="y")
        rows = []
        status = tk.Label(top, text="", foreground="#1b6b2a", font=("Segoe UI", 9), anchor="w")

        def fill():
            lb.delete(0, tk.END)
            rows.clear()
            limit = (datetime.today() - timedelta(days=30)).strftime("%Y-%m-%d")
            mine = [(iid, r) for iid, r in self.core.items.items()
                    if r.get("k") == "e" and not r.get("z") and self.core.is_mine(r) and (r["d"] >= limit or r.get("rp"))]
            mine.sort(key=lambda a: (a[1]["d"], a[1]["t"]))
            for iid, r in mine:
                first = r["x"].splitlines()[0][:34] if r["x"] else ""
                lb.insert(tk.END, f"{r['d']} {r['t']}  {first}   [{v_label(r.get('v'), self.core.people, self.core.me)}]")
                rows.append(iid)
        fill()
        ttk.Label(top, text="Visible to:", font=("Segoe UI", 9, "bold")).pack(padx=12, pady=(8, 0), anchor="w")
        frame, get = self._audience_widget(top, None)
        frame.pack(padx=12, anchor="w")

        def apply():
            sel = lb.curselection()
            if not sel:
                status.config(text="Pick at least one event first.", foreground="#b00000")
                return
            v = get()
            n = sum(1 for i in sel if self.core.set_audience(rows[i], v))
            self.core.save()
            self.request_sync()
            fill()
            self.refresh_calendar()
            status.config(text=f"{n} event(s) now visible to: {v_label(v, self.core.people, self.core.me)}.", foreground="#1b6b2a")
        status.pack(padx=12, anchor="w")
        bf = ttk.Frame(top)
        bf.pack(fill="x", padx=12, pady=10)
        ttk.Button(bf, text="Apply to the picked events", command=apply).pack(side="left")
        ttk.Button(bf, text="Close", command=top.destroy).pack(side="right")

    def show_birthday_share_dialog(self, pick=None):
        """Birthdays etc. (BirthdayTracker) shared ONE PERSON AT A TIME: pick people in the list, pick who sees their birthday, Apply.
        Everybody not shared stays on my own phone only.  pick = a person key to select at once."""
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title("Share birthdays")
        top.transient(root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(False, False)
        tk.Label(top, justify="left", anchor="w", wraplength=520, font=("Segoe UI", 9),
                 text="The birthdays (and anniversaries) of the people in BirthdayTracker. Each one is seen by you only, until you pick it here: "
                      "pick people in the list (Ctrl / Shift for several), choose who sees them and press Apply. "
                      "Death marks and other private ones: just leave them on 'Only me'."
                 ).pack(padx=12, pady=(12, 4), anchor="w")
        box = ttk.Frame(top)
        box.pack(padx=12, anchor="w")
        lb = tk.Listbox(box, height=16, width=70, selectmode="extended", exportselection=False, activestyle="none")
        sb = ttk.Scrollbar(box, command=lb.yview)
        lb.configure(yscrollcommand=sb.set)
        lb.pack(side="left")
        sb.pack(side="left", fill="y")
        rows = []
        status = tk.Label(top, text="", foreground="#1b6b2a", font=("Segoe UI", 9), anchor="w", justify="left", wraplength=520)

        def fill(keep=()):
            lb.delete(0, tk.END)
            rows.clear()
            share = self._marks_share()
            persons = sorted(_bt_persons(), key=lambda p: _bt_name(p).lower())
            for p in persons:
                key = bt_person_key(p)
                born = _bt_parse_date(p.get("birth_date"))
                when = born.strftime("%d %b") if born else "?"
                lb.insert(tk.END, f"{_bt_name(p)}   ·   {when}   [{v_label(self._marks_audience(key, share), self.core.people, self.core.me)}]")
                rows.append(key)
            if not rows:
                lb.insert(tk.END, "(no people found in BirthdayTracker)")
            for i, key in enumerate(rows):
                if key in keep:
                    lb.selection_set(i)
                    lb.see(i)
        fill([pick] if pick else ())

        ttk.Label(top, text="Seen by:", font=("Segoe UI", 9, "bold")).pack(padx=12, pady=(8, 0), anchor="w")
        frame, get = self._audience_widget(top, None)
        frame.pack(padx=12, anchor="w")

        def apply():
            sel = [rows[i] for i in lb.curselection() if i < len(rows)]
            if not sel:
                status.config(text="Pick at least one person first.", foreground="#b00000")
                return
            v = get()
            cfg = load_cfg()
            share = cfg.get("marks_share") if isinstance(cfg.get("marks_share"), dict) else {}
            for key in sel:
                if v:
                    share[key] = self._v_to_cfg(v)
                else:
                    share.pop(key, None)                     # only me = the default: nothing is stored
            cfg["marks_share"] = share
            save_cfg(cfg)
            self._marks_stamp = None
            self._push_marks()
            self.core.save()
            self.request_sync()
            fill(sel)
            status.config(text=f"{len(sel)} person(s): their birthdays are now seen by {v_label(v, self.core.people, self.core.me)}.", foreground="#1b6b2a")
        status.pack(padx=12, anchor="w")
        bf = ttk.Frame(top)
        bf.pack(fill="x", padx=12, pady=10)
        ttk.Button(bf, text="Apply to the picked", command=apply).pack(side="left")
        ttk.Button(bf, text="Pick all", command=lambda: lb.selection_set(0, tk.END) if rows else None).pack(side="left", padx=4)
        ttk.Button(bf, text="Close", command=top.destroy).pack(side="right")

    def show_hidden_dialog(self):
        """The events of others that I left out of my calendar: bring one back."""
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title("Events I left out")
        top.transient(root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda e: top.destroy())
        top.resizable(False, False)
        tk.Label(top, text="Events of other people that you left out of your calendar:", font=("Segoe UI", 9)).pack(padx=12, pady=(12, 4), anchor="w")
        lb = tk.Listbox(top, height=10, width=70, exportselection=False, activestyle="none")
        lb.pack(padx=12, anchor="w")
        rows = []

        def fill():
            lb.delete(0, tk.END)
            rows.clear()
            for iid, r in self.core.hidden_events():
                lb.insert(tk.END, f"{r['d']} {r['t']}  {r['x'].splitlines()[0][:40]}   (from {self.core.maker_name(r)})")
                rows.append(iid)
            if not rows:
                lb.insert(tk.END, "(none)")
        fill()

        def bring_back():
            s = lb.curselection()
            if not s or not rows:
                return
            self.core.set_override(rows[s[0]], self.events, self.notes, hid=False)
            self._after_override()
            fill()
        bf = ttk.Frame(top)
        bf.pack(fill="x", padx=12, pady=10)
        ttk.Button(bf, text="Show it again", command=bring_back).pack(side="left")
        ttk.Button(bf, text="Close", command=top.destroy).pack(side="right")

    # ── Reminders ──────────────────────────────────────────────────────────────
    def _schedule_alarm(self):
        """Schedule the next alarm check, cancelling any pending one first."""
        if self._alarm_after_id is not None:
            try:
                self.after_cancel(self._alarm_after_id)
            except Exception:
                pass
        self._alarm_after_id = self.after(60_000, self.check_alarms)

    def _run_alarm_check(self):
        """Run an immediate alarm check without touching the recurring schedule."""
        now = datetime.now().replace(second=0, microsecond=0)
        self._reconcile_now()                      # an event just added is known here before it is checked
        coming = self.core.alarm_times(now)        # every reminder moment still ahead (an event can have several: 1 day before, 10 min before ...)

        for at, ev_dt, text in coming:
            if at > now + timedelta(minutes=1):
                break
            if (at, text) in self._rung:
                continue
            self._rung.add((at, text))
            when = "now" if at == ev_dt else f"at {ev_dt.strftime('%H:%M')}"
            messagebox.showinfo("Reminder", f"Reminder {when}\n\n{ev_dt.strftime('%Y-%m-%d %H:%M')} {text}", parent=self)

        upcoming = [a for a in coming if a[0] > now + timedelta(minutes=1) or (a[0], a[2]) not in self._rung]
        if upcoming:
            at, ev_dt, text = upcoming[0]
            desc = text.splitlines()[0][:20]
            self.upcoming_label.config(
                text=f"🔔 Next reminder: {at.strftime('%Y-%m-%d %H:%M')} – {desc}…"
            )
        else:
            self.upcoming_label.config(text="🔔 Next reminder: None")

    def check_alarms(self):
        """Called by the recurring timer; runs alarm logic then reschedules."""
        self._run_alarm_check()
        self._schedule_alarm()

    # ── Hub-hook ───────────────────────────────────────────────────────────────
    def save_state(self):
        self.save_data()

    # ── About ──────────────────────────────────────────────────────────────────
    def _show_about(self):
        # FIX: webbrowser is now a top-level import; no local import needed
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title("About Calendar")
        top.resizable(False, False)
        top.transient(root)
        top.grab_set()
        top.focus_force()                               # FIX: focus so ESC works
        top.bind("<Escape>", lambda e: top.destroy())   # FIX: ESC closes

        # Header
        hdr = tk.Frame(top)
        hdr.pack(fill="x")
        tk.Label(hdr, text="📅", font=("Segoe UI", 36)).pack(pady=(18, 0))
        tk.Label(hdr, text="Calendar",
                 font=("Segoe UI", 20, "bold")).pack()
        tk.Label(hdr, text="Events, notes and reminders in one place",
                 fg="gray", font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
        tk.Frame(top, bg="#cccccc", height=1).pack(fill="x", padx=20)

        # Author
        tk.Label(top, text='Created by  Lars "Issu" Olsson',
                 font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

        # Documentation link
        DOC_URL = (
            "https://docs.google.com/document/d/"
            "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
        doc_lbl = tk.Label(top, text="📄  View documentation",
                           fg="#2563eb", font=("Segoe UI", 9, "underline"),
                           cursor="hand2")
        doc_lbl.pack(pady=(6, 2))
        doc_lbl.bind("<Button-1>", lambda e: open_url(DOC_URL))
        doc_lbl.bind("<Enter>",    lambda e: doc_lbl.configure(fg="#1d4ed8"))
        doc_lbl.bind("<Leave>",    lambda e: doc_lbl.configure(fg="#2563eb"))

        tk.Frame(top, bg="#cccccc", height=1).pack(fill="x", padx=20, pady=(14, 0))

        # Donation section
        tk.Label(top, text="☕  If you enjoy Calendar, a small gift is always welcome!",
                 fg="gray", font=("Segoe UI", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

        donate_frame = tk.Frame(top, bg="#f0f0f0", padx=16, pady=10)
        donate_frame.pack(fill="x", padx=20, pady=(0, 6))

        REVOLUT_URL = "https://revolut.me/lars72oeh"
        PAYPAL_URL  = "https://paypal.me/issusbarn"
        WISE_URL    = "https://wise.com/pay/me/larsdenniso"

        def _donate_btn(parent, label, url, color):
            b = tk.Label(parent, text=label, bg=color, fg="#ffffff",
                         font=("Segoe UI", 9, "bold"), padx=10, pady=5, cursor="hand2")
            b.bind("<Button-1>", lambda e: open_url(url))
            return b

        btn_row = tk.Frame(donate_frame, bg="#f0f0f0")
        btn_row.pack()
        _donate_btn(btn_row, "💳  Revolut", REVOLUT_URL, "#0666eb").pack(side="left", padx=4)
        _donate_btn(btn_row, "🅿  PayPal",  PAYPAL_URL,  "#003087").pack(side="left", padx=4)
        _donate_btn(btn_row, "🌍  Wise",    WISE_URL,    "#2d6a4f").pack(side="left", padx=4)

        tk.Frame(top, bg="#cccccc", height=1).pack(fill="x", padx=20, pady=(8, 0))
        tk.Label(top, text="Press ESC or click Close to dismiss",
                 fg="gray", font=("Segoe UI", 8, "italic")).pack(pady=(6, 2))
        ttk.Button(top, text="Close", command=top.destroy).pack(pady=(2, 14))

    # ── Help ───────────────────────────────────────────────────────────────────
    def _show_help(self):
        root = self.winfo_toplevel()
        top = tk.Toplevel(root)
        top.title("Calendar — Help")
        top.resizable(True, True)
        top.transient(root)
        top.grab_set()
        top.focus_force()                               # FIX: focus so ESC works
        top.bind("<Escape>", lambda e: top.destroy())   # FIX: ESC closes
        top.geometry("620x580")

        tk.Label(top, text="❓  Calendar — Help",
                 font=("Segoe UI", 14, "bold")).pack(pady=(14, 4))
        tk.Frame(top, bg="#cccccc", height=1).pack(fill="x", padx=20, pady=(0, 6))

        outer = tk.Frame(top)
        outer.pack(fill="both", expand=True, padx=16, pady=(0, 8))
        vs = ttk.Scrollbar(outer, orient="vertical")
        txt = tk.Text(outer, font=("Segoe UI", 10), relief="flat", borderwidth=0,
                      wrap="word", state="normal", yscrollcommand=vs.set,
                      padx=10, pady=8, cursor="arrow",
                      insertofftime=0, insertontime=9999999)
        vs.config(command=txt.yview)
        vs.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.bind("<MouseWheel>",
                 lambda e: txt.yview_scroll(int(-1*(e.delta/120)), "units"))

        # NOTE: tk.Text.tag_configure uses foreground=, NOT fg=
        txt.tag_configure("h1",   font=("Segoe UI", 12, "bold"))
        txt.tag_configure("h2",   font=("Segoe UI", 10, "bold"))
        txt.tag_configure("ok",   foreground="#145214")
        txt.tag_configure("warn", foreground="#7b0000")
        txt.tag_configure("dim",  foreground="#888888", font=("Segoe UI", 9))

        def w(text, tag=None):
            txt.insert("end", text, tag) if tag else txt.insert("end", text)

        w("What is Calendar?\n\n", "h1")
        w(
            "Calendar is a personal planner that shows a monthly grid with "
            "public holidays, lets you add timed events with automatic reminders, "
            "and stores free-text notes for any day. Birthdays and anniversaries "
            "are read live from BirthdayTracker's own list, so there is only one "
            "list of people to keep. All data is saved locally "
            "and persists between sessions.\n\n"
        )

        w("Navigating the Calendar\n\n", "h1")
        w("←  /  →  ", "h2")
        w("— move one month backwards or forwards.\n\n")
        w("Today  ", "h2")
        w("— jumps straight back to the current month and re-selects today's date.\n\n")
        w("Calendar format  ", "h2")
        w(
            "— choose between Sweden, UK, and Russia. This changes:\n"
            "  •  Which public holidays are highlighted in pink\n"
            "  •  The first day of the week "
            "(Monday-first for Sweden/UK, Sunday-first for Russia)\n\n"
        )

        w("Colour coding\n\n", "h1")
        w("Light blue  ", "h2");  w("— today's date\n")
        w("Selected (light blue, #cce5ff)  ", "h2"); w("— the day you have currently clicked\n")
        w("Pink / misty rose  ", "h2"); w("— public holiday\n")
        w("Red text in a cell  ", "h2"); w("— an event has been added to that day\n")
        w("Green text in a cell  ", "h2"); w("— a birthday or anniversary from BirthdayTracker\n\n")

        w("Birthdays and anniversaries\n\n", "h1")
        w(
            "The Calendar keeps no list of people of its own. Everything green "
            "is read straight out of the file BirthdayTracker owns:\n"
        )
        w("  Helpfiles/BirthdayTracker/persons.json\n\n", "h2")
        w(
            "That means there is only ever one list to maintain. Add or correct "
            "a person in BirthdayTracker and it appears here the next time the "
            "month is drawn — no import, no copy, nothing to keep in step. The "
            "Calendar never writes to that file.\n\n"
        )
        w("🎂 Name and age  ", "h2"); w("— an annual birthday, from the person's date of birth\n")
        w("★ Name: what, and how many years  ", "h2");
        w("— one of the person's own events (anniversaries)\n\n")
        w("The two checkboxes\n\n", "h1")
        w("🎂 Birthdays  ", "h2")
        w(
            "— on by default. Birthdays and the personal anniversaries listed "
            "against each person.\n\n"
        )
        w("✨ Extras  ", "h2")
        w(
            "— also on by default, and adds four more kinds of day for the same "
            "people:\n"
        )
        w("  ⭐ ", "h2"); w("day-count milestones — 1 000, 10 000, 22 222 days old\n")
        w("  🏆 ", "h2"); w("round-number ages — 18, 50, 65 …\n")
        w("  💜 ", "h2"); w("Swedish name days, for every name a person answers to "
                            "(preferred, first and middle)\n")
        w("  ⏳ ", "h2"); w("mini-birthdays — every 1, 3 or 6 months, for the people "
                            "who have that set in BirthdayTracker\n\n")
        w(
            "The two are independent — either one on its own draws exactly what "
            "it says. Both choices are remembered between sessions, and "
            "switching either one changes only what a day shows, never the size "
            "of the calendar.\n\n"
        )

        w("How much fits, and the day window\n\n", "h1")
        w(
            "The grid takes the whole space it is given, in both directions, and "
            "the cells are measured from that — not from their text. Make the "
            "window bigger and every cell grows with it, showing more lines; the "
            "layout never jumps about because a day happens to be busy.\n\n"
        )
        w("+N more …  ", "h2")
        w(
            "— what a cell could not fit. Click that day and it opens in a "
            "window of its own, with everything on it in full: holiday, your own "
            "events, every line from BirthdayTracker, and the day's note.\n\n"
        )
        w("Double-click  ", "h2")
        w(
            "— opens that window for any day, busy or not.\n\n"
        )
        w("Esc  ", "h2"); w("— closes it. Only one is ever open at a time, so clicking "
                            "through several busy days replaces it rather than piling "
                            "windows up.\n\n")
        w("⚠  ", "warn")
        w(
            "Milestones, name days and mini-birthdays are not stored anywhere. "
            "They are worked out from the dates in persons.json using "
            "BirthdayTracker's own arithmetic, so the two programs can never "
            "name different days. The name-day almanac is a copy of "
            "BirthdayTracker's — that one is a Swedish almanac, not data, and "
            "BirthdayTracker stays its master copy.\n\n"
        )

        w("Adding Events\n\n", "h1")
        w(
            "Click a day to select it, then click  ➕ Add event  in the toolbar. "
            "A small dialog opens where you enter:\n"
        )
        w("  Date (YYYY-MM-DD)  ", "h2"); w("— the day (filled in from the selected day)\n")
        w("  Time (HH:MM)  ", "h2"); w("— the time the event occurs, e.g. 14:30\n")
        w("  Description  ", "h2");  w("— a short text describing the event\n")
        w("  Remind me  ", "h2");  w("— at the time (the default), and/or 10 min, 30 min, 1 hour or 1 day before. "
                                 "Tick  quiet  beside a reminder and the phone only shows a notification for it instead of the loud alarm\n")
        w("  Repeat  ", "h2");  w("— every day, week, month or year (every 2nd, 3rd ... if you like), with an optional last day. "
                                 "A repeating event is ONE event; its later days are drawn with  ↻  and can be changed or deleted "
                                 "one at a time, from a day on, or all at once (you are asked). A monthly event on the 31st uses "
                                 "the last day of the shorter months\n\n")
        w(
            "Click  Save  to store the event. It will appear as red text "
            "inside the day cell. Events are saved to  "
            "Helpfiles/kalender/kalender-events.json.\n"
            "Double-click a day (or click a crowded one) to see it in full: each event there has  ✎  (change it) "
            "and  🗑  (delete it).\n\n"
        )

        w("Reminders\n\n", "h1")
        w(
            "The calendar checks every minute whether any reminder is due "
            "(each event can have several). If so, a reminder popup "
            "appears automatically. The footer bar always shows the next "
            "upcoming reminder.\n\n"
        )

        w("Phone sync\n\n", "h1")
        w(
            "The phone app  Issu's Calendar  keeps the same events and notes, through your own server, and rings "
            "for every reminder - also with the screen off and while this window is closed. Click  📱 Phone sync…  "
            "and enter the server address and key (or  Paste code  if you have a phone code), then  Sync now. "
            "From then on it syncs by itself: at start, a few seconds after every change, and every 3 minutes. "
            "An event made on the phone appears here, and the other way round; if both sides changed the same event "
            "the later change wins. Birthdays from BirthdayTracker are sent to the phone too (read-only there). "
            "Copy phone code  puts a code on the clipboard that the app accepts instead of typing the address and key; "
            "it contains the key, so send it only to your own phone. "
            "The links between the two sides are kept in  Helpfiles/kalender/kalender-sync.json  "
            "(leave that file alone); the address and key are in  relay.json  in the same folder.\n"
            "Repeating events need the new relay (version 2): until you have run the job  Calendar relay  they stay here "
            "and the footer says so; nothing is lost, and they are sent on their own when the relay has been updated. "
            "The phone also has a week view and a list of coming events; this window has the month only.\n\n"
        )

        w("People on one calendar\n\n", "h1")
        w(
            "Several people can share ONE calendar and still keep things apart. Click  👥 People…  to add a person: "
            "they get an own key and a phone code (shown once - send it only to that person). Their phone pastes the code "
            "under Settings > Sync with the PC and from then on only receives what they are allowed to see.\n"
            "Every event has an  audience:  Only me,  Everybody  or chosen people (default for new events is set in the People window), "
            "and you can write who it is  about.  Change who sees many events at once with  Share my events…  in the People window. "
            "Events made by others show who made them; you cannot change them, but you can  leave them out  of your own calendar "
            "(the others keep them;  Events I left out…  in the People window brings them back) and give them your own reminders. "
            "Birthdays etc. from BirthdayTracker are only yours until you share them ONE PERSON AT A TIME:  Share birthdays…  in the People "
            "window, or  Share…  next to a birthday in the day window. Nobody gets any by default.  Everybody  means everybody on the calendar, "
            "also people added later; to keep somebody out of one thing, tick their name under  except:  (Everybody except Leo). "
            "On a phone a birthday somebody shared with you can be left out by a long press on it. "
            "Day notes are private to each person. Everybody has their own reminders, quiet or loud, on their own phone.\n"
            "On the phone, the  📷  button photographs a paper with an appointment (a notice): you circle the date and time, the place and a "
            "comment one at a time, the phone reads the text, and the event window opens filled in - you only choose who it is about "
            "and who may see it. Place and comment follow the event here.\n"
            "People and sharing need the new relay (version 3): run the job  Calendar relay  once. "
            "An event that only you can see stays exactly as before.\n\n"
        )

        w("Notes\n\n", "h1")
        w(
            "Click any day to select it. The  📝 Notes for selected day  panel "
            "at the bottom of the window loads any note saved for that date. "
            "Type freely in the text area, then click:\n"
        )
        w("  💾 Save  ", "h2"); w("— saves the note for the selected day\n")
        w("  ✖ Clear  ", "h2"); w("— deletes the note for the selected day\n\n")
        w("Notes are saved to  Helpfiles/kalender/kalender-notes.json.\n\n")

        w("E-mail\n\n", "h1")
        w(
            "Enter your e-mail address in the footer field and click  Save. "
            "The address is stored locally in  "
            "Helpfiles/kalender/kalender-email.txt  "
            "and restored on next launch. "
            "(Future versions may use this for e-mail reminders.)\n\n"
        )

        w("Tips\n\n", "h1")
        w("✓  ", "ok"); w("Click a day first, then  ➕ Add event  — the event is added to the selected day.\n")
        w("✓  ", "ok"); w("The window size is saved and restored between sessions.\n")
        w("✓  ", "ok"); w("Week numbers (ISO 8601) are shown in the leftmost column.\n")
        w("⚠  ", "warn"); w("Reminders HERE only fire while the Calendar window is open - the phone app rings on its own.\n\n")

        txt.configure(state="disabled")
        tk.Label(top, text="Press ESC or click Close to dismiss",
                 fg="gray", font=("Segoe UI", 8, "italic")).pack(pady=(0, 2))
        ttk.Button(top, text="Close", command=top.destroy).pack(pady=(0, 12))


# Alias for hub compatibility
EditorFrame = CalendarFrame


# ── Hub API (module-level) ─────────────────────────────────────────────────────
def build_module(master, hub=None):
    return CalendarFrame(master, hub=hub)

def menu_spec():
    return {
        "module_name":  MODULE_NAME,
        "menu_label":   MENU_LABEL,
        "menu_group":   MENU_GROUP,
        "menu_pos":     MENU_POS,
        "want_hub_dir": True,
    }


# ── Standalone ─────────────────────────────────────────────────────────────────
def run_standalone():
    cfg = load_cfg()

    # FIX: AppUserModelID BEFORE tk.Tk()
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "LarsOlsson.Kalender.1")
    except Exception:
        pass

    root = tk.Tk()
    root.title(APP_TITLE)
    try:
        root.geometry(cfg.get("geometry", DEFAULT_CFG["geometry"]))
    except Exception:
        pass

    app = CalendarFrame(root)
    app.pack(fill="both", expand=True)

    # FIX: icon via after(0) — never set directly; tkinter overwrites it otherwise
    root.after(0, lambda: _set_window_icon(root))

    def on_close():
        try:
            # Re-read rather than reuse the copy loaded at start-up: the
            # birthday toggle writes to the same file while the window is open,
            # and a stale copy would undo it on the way out.
            latest = load_cfg()
            latest["geometry"] = root.geometry()
            save_cfg(latest)
            app.save_data()
        except Exception:
            pass
        root.destroy()

    root.protocol("WM_DELETE_WINDOW", on_close)
    root.minsize(800, 600)
    root.mainloop()


if __name__ == "__main__":
    run_standalone()
