#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ======================================================================
# ALLT I PROGRAMMET SKA ALLTID VARA PÅ ENGELSKA - ALDRIG SVENSKA!
# (All in-program text must always be in English - never Swedish!
#  This line is a standing instruction for any human or AI editing
#  this file later - do not translate UI strings into Swedish.)
# ======================================================================
"""
TutorCal
--------
Calendar & schedule manager for a private tutor.

THIS HAS GROWN PAST THE ORIGINAL SKELETON STAGE. Every item on the master
ToDo list below is DONE, except #7 (WhatsApp/Email share), which is only
PARTIALLY DONE - see that entry for exactly what's still missing (no
PDF-to-clipboard, no fully automatic share-sheet with a pre-filled
recipient). Any other loose ends are tracked as individual inline
"# TODO" comments near the relevant code (e.g. DOC_URL, the alarm-interval
tiers) rather than as whole missing features.

# ToDo (master list - see also inline TODOs near the relevant code):
#   1. DONE (month + week + day): the Calendar tab has a "Month View"
#      sub-tab with a proper month grid (prev/next/today navigation, one
#      cell per day), a "Week View" sub-tab (DEL 08d) that draws the same
#      week as a real time grid: seven day columns, one row per hour,
#      every entry drawn as a block whose height is its actual duration,
#      overlapping entries tiled side by side, untimed ones in an all-day
#      strip above the grid, and the hour range widened automatically when
#      something that week falls outside normal hours. Double-clicking a
#      block opens the editor for whatever produced it (entry / recurring
#      slot / override); double-clicking empty space starts a new entry on
#      that day at that time. The Month View grid can't take a
#      double-click of its own (the first click has already opened the day
#      box), so its editing lives one step in: double-click a line inside
#      that day box. A "Day View" sub-tab (DEL 08e) now does the same
#      single-column zoom for one day at a time - same block/all-day-strip
#      drawing, same double-click-to-edit / double-click-empty-space-to-add
#      - reached either from its own tab or via an "Open Day View" button
#      in the same day box that Month View cells and Week View day headers
#      already open. Which of the four views was open is remembered
#      between runs. DONE (DEL 08f): dragging a block on the Week View or
#      Day View grid moves it (dropping it on a different day/time on the
#      Week View, or a different time on the Day View, which only shows
#      one day) - and dragging its bottom edge resizes it by changing its
#      end time. A one-off List View entry is edited directly; a
#      recurring Base/Family Schedule slot gets a Move override instead
#      (same as adding one by hand), so only that one occurrence shifts,
#      not the whole weekly series; an already-moved occurrence can be
#      dragged again to fine-tune it, updating that same override rather
#      than stacking a second one on top. Both grids snap to the quarter
#      hour and show a dashed preview with the new time while dragging.
#      A cancelled slot or a plain note isn't draggable - there's nothing
#      sensible to drag it to - so those stay double-click-only.
#
# ----------------------------------------------------------------------
# NOTES FOR WHOEVER EDITS THIS NEXT (human or AI)
# ----------------------------------------------------------------------
# Four Tk facts this program was built around. They cost real debugging
# time here, and they apply to any Tkinter program, not just this one:
#
#   a) Tk REFUSES to synthesize a double-click:
#          widget.event_generate("<Double-Button-1>")
#      raises TclError: "Double, Triple, or Quadruple modifier not
#      allowed". A test cannot fake one. Assert that the binding exists -
#      widget.bind("<Double-Button-1>") returns a non-empty string - and
#      then call the handler directly. Plain "<Button-1>" generates fine.
#
#   b) A generated KEY event is delivered to the focus window, and
#      focus_get() is None while the app has no visible, OS-focused
#      window. So a test that presses Enter/Escape must NOT run with
#      root.withdraw() - the event silently vanishes and the assertion
#      passes without having tested anything. Mouse events are fine
#      withdrawn.
#
#   c) isinstance(w, tk.Entry) is TRUE for a ttk.Combobox (it subclasses
#      it). Probing widgets for real text fields needs type(w) is
#      tk.Entry, or cget("insertofftime") raises TclError on the combos.
#
#   d) A widget whose single click opens a modal window can never also
#      carry a double-click: the first click puts the modal (and its
#      grab) in front, so the second click lands there instead. That is
#      why the Month View's day cells open the day box on a single click
#      and the editing lives on a double-click INSIDE that box, while the
#      Week View - whose blocks have no single-click action - takes the
#      double-click directly.
#
# Also: run the seven test_tutorcal_*.py files that live beside the
# working copy (Claude_working/<date>/TutorCal/) after any change. They
# drive the real app object in a throwaway sandbox (no real Helpfiles are
# touched) and cover the settings lists, the shared edit dialog, the Week
# View grid, a cold-start/restart round trip, reminder state around
# moves/cancellations, the crash-safe data files, and the .ics export.
# One trap they hit: the live alarm poll will pop its own reminder into
# the middle of a test that drives the popup by hand, so a test that does
# that must call app._stop_alarm_loop() first.
#   2. DONE: Alarm engine now actually fires reminders while the app is
#      running. A Tk `after()` timer (not a background thread - Tkinter
#      isn't thread-safe) polls the clock every ALARM_CHECK_INTERVAL_MS
#      and, for any entry whose "Warn before" window has been entered,
#      pops up a reminder (with sound) and re-fires it at the chosen
#      repeat interval until it's dismissed or the time passes. This now
#      covers Calendar > List View entries AND recurring Base Schedule /
#      Family Schedule slots - each recurring row got its own "Warn
#      before" + "Repeat reminder" fields (same choices as List View),
#      and a rolling 9-day window of upcoming occurrences is generated
#      each check (see generate_recurring_alarm_instances, DEL 07b),
#      correctly skipping occurrences a Cancel override suppressed and
#      alarming a Moved occurrence at its *new* date/time instead of the
#      original slot. Per-occurrence fired/dismissed state is persisted
#      to Helpfiles/Settings/alarm_state.json (keyed by "<row id>:<date>"
#      for recurring slots, so each week's occurrence is tracked
#      independently, vs. a plain event id for one-off List View
#      entries) and survives an app restart the same way List View
#      alarms already did; stale recurring-slot keys more than a few
#      days old are pruned automatically so the file doesn't grow
#      forever. DONE: every reminder now also raises a real OS-level
#      notification alongside the in-app popup (DEL 07f) - a Windows
#      Action Center toast (via Shell_NotifyIcon, using the
#      AppUserModelID already set in DEL 05), a macOS notification-center
#      banner (via osascript), or a Linux notify-send toast - so it's
#      noticed even when TutorCal's window is minimized or in the
#      background. It's additive only: the in-app popup + sound still
#      fire exactly as before regardless of whether the OS toast
#      succeeds, so an unsupported platform or a missing notify-send
#      binary just means one less toast, never a missed reminder.
#   3. DONE (base schedule only): Base weekly schedule now auto-generates
#      recurring lesson occurrences straight into the Month View, and
#      temporary moves/cancellations are now structured (target date +
#      optional specific slot + Cancel/Move/Note-only) so they actually
#      suppress or relocate the right occurrence instead of just sitting
#      in an unused side list. Old free-text overrides from earlier
#      versions are auto-upgraded to the new format on load (shown as
#      "Note only" so nothing is lost).
#   4. DONE: Family schedules (her own schedule, son's school, bus,
#      daycare) now also render as recurring weekly items on the same
#      Month View grid (toggle which layers are visible with the
#      checkboxes above the grid), AND the same Cancel/Move/Note-only
#      overrides the base tutoring schedule already had now work for
#      family schedule entries too - a "Schedule" dropdown on the Base
#      Schedule tab's override form picks which of the five recurring
#      schedules a given override applies to, so e.g. "son's bus is
#      cancelled on the 12th" suppresses just that occurrence, the same
#      way a cancelled lesson does.
#   5. DONE: Export tab now builds a real merged agenda (same base
#      schedule + overrides + family layers + one-off events logic as the
#      Month View) for a chosen date range (this or next Monday-to-Sunday
#      week - matching the Week View - the next 7/30 days, the current
#      month, or a custom from/to range) and writes it to
#      Helpfiles/Export as a phone-friendly .txt, .png, or .pdf file. The
#      Image and PDF formats need Pillow / fpdf2 installed respectively
#      (pip install pillow / pip install fpdf2) - if either is missing,
#      that button shows a clear message instead of crashing; Export as
#      Text has no extra dependency. "Export as Image" now also copies the
#      PNG straight onto the OS clipboard (see #7/DEL 07e) so it can be
#      pasted directly into a chat or email; PDF still just gets revealed
#      in the OS file manager, since nothing treats a PDF as pasteable
#      image data.
#   6. DONE: Contacts tab now has a live Search box (matches name, role,
#      app, contact value, note, and any linked student/event), and a
#      contact can optionally be linked to a specific Student contact
#      (e.g. tie a Guardian to their child) and/or a specific Calendar
#      List View event (e.g. tie a School contact to a particular
#      meeting). Links are shown resolved in a "Linked to" column and
#      degrade gracefully to "(deleted)" if the linked item is removed.
#   7. PARTIALLY DONE: Export tab now has "Share as WhatsApp Message" and
#      "Share as Email" buttons that send the merged agenda as *text*
#      straight into a WhatsApp chat picker or a new email draft, using
#      WhatsApp's own click-to-chat (wa.me) link and a standard mailto:
#      link - no API key or extra package needed. The saved Image/PNG also
#      gets pushed onto the OS clipboard as real image data the moment
#      it's exported (DEL 07e - PowerShell's System.Windows.Forms on
#      Windows, osascript on macOS, xclip/wl-copy on Linux, all already
#      installed on their respective OS except the Linux tools), so a
#      simple Ctrl+V/Cmd+V inside WhatsApp Desktop, Telegram, Signal, or
#      most email compose boxes attaches it with no dragging. STILL TODO:
#      no equivalent for PDF (no app treats a PDF as pasteable image
#      data), and no *fully automatic* send with a chosen recipient
#      pre-filled - that still needs a real platform-specific share-sheet
#      API (WinRT DataTransferManager on Windows, NSSharingService on
#      macOS), which isn't wired up.
#   8. DONE: nothing is a fixed list any more. A new SETTINGS TAB (DEL 08b)
#      holds three user-owned lists, each saved under Helpfiles/Settings:
#      (a) contact apps - contact_apps.json, deliberately EMPTY to start
#      with, so the Contacts tab's "App" dropdown is blank by default
#      instead of silently pre-filling "WhatsApp" the way it used to;
#      (b) contact roles - contact_roles.json (only "Student" is fixed,
#      because the "Linked student" feature looks for it); and
#      (c) schedule_types.json - the recurring schedules themselves. The
#      old hard-coded five ("lesson" + her schedule + son's school / bus /
#      daycare) are now just the seeded defaults: she can rename them,
#      recolour them (16 suggested swatches or any custom colour), reorder
#      them, delete them, and add as many new ones as she likes. Adding
#      one immediately gives it its own Family Schedules sub-tab, Month
#      View layer checkbox, override-dropdown entry and Export checkbox -
#      apply_schedule_defs() republishes CATEGORY_STYLES /
#      FAMILY_SCHEDULE_FIELDS / OVERRIDE_CATEGORY_CHOICES /
#      EXPORT_LAYER_KEYS and _schedules_changed() redraws everything built
#      from them. Chip text colour is derived from the picked colour
#      (readable_fg) so a light custom colour never gives white-on-white.
#      Old bus rows keep their "departs"/"arrives" field names via the
#      per-schedule start_field/end_field, so no saved data is orphaned.
#   9. DONE: it was never obvious what day it actually was. The Month View
#      now spells today's date out in full between the Next button and the
#      month title ("Today: Wednesday, 26 August 2026"), and today's cell
#      got a much heavier marker than the old 1-pixel line: a 3px orange
#      outline, a tinted background, and its day number in a filled orange
#      badge. If the app is left open past midnight, the next alarm tick
#      notices the date change and redraws the grid.
#  10. DONE: every list was add-and-delete only - fixing a typo in a lesson
#      time meant deleting the row, retyping it, and losing its reminder
#      state. All five lists (Calendar > List View, Base Schedule, its
#      overrides, every Family Schedule, Contacts) now have "Edit
#      selected..." plus double-click-to-edit, all backed by one shared
#      modal built from a field spec (_edit_record_dialog, DEL 08c) so
#      they validate and behave identically: Enter saves from a one-line
#      field but stays a line break in a Note, Escape cancels, dropdowns
#      stay dropdowns, and the Warn-before/Repeat pair narrows itself the
#      same way the add-forms do. Editing something that changes *when* a
#      reminder is due (date/weekday/start/lead/repeat) drops that row's
#      fired/dismissed state so it can alarm again at the new time.
#      A Family row is edited through its own schedule's field names, so a
#      bus row edits Departs/Arrives rather than Start/End; the override
#      editor recomputes its Slot dropdown live when the schedule or date
#      is changed inside the dialog.
#  11. DONE (DEL 08f - the last piece of master ToDo #1): the Week View and
#      Day View grids now support drag-to-move and drag-to-resize directly
#      on a block, instead of only double-click-to-edit. See the note next
#      to ToDo #1 above for exactly how a drag turns into a saved change
#      for each of the three kinds of block it can grab.
#  12. DONE (DEL 04b): the data files can no longer be lost. Every save is
#      atomic (write "<file>.tmp", flush, then os.replace it into place)
#      and keeps the previous content one generation back as "<file>.bak",
#      so a crash or a power cut mid-write can't leave a half-written
#      file. And a damaged file is no longer read as an *empty* one: it is
#      renamed to "<file>.corrupt-<timestamp>", the .bak is used instead
#      if it is readable, and the user is told at startup what happened.
#      (The old behaviour was the dangerous one: unreadable events.json ->
#      empty list -> the next save wrote that emptiness over the only copy
#      of a year of lessons.) On top of that, make_daily_backup() copies
#      every data file into Helpfiles/Backups/<date>/ once a day at
#      startup, keeping the last 14 days - that is what undoes a deletion
#      noticed a week later, which no amount of atomic writing can. File >
#      "Restore from a backup..." puts one of those days back: it copies
#      the current files aside into a "before-restore-<timestamp>" folder
#      first, then closes the program WITHOUT saving (via
#      _quit_without_saving - a normal close would write the in-memory
#      lists straight back over what was just restored).
#  13. DONE (DEL 07c): "Export to Calendar (.ics)". The Text/Image/PDF
#      exports are things to look at; this one is a real iCalendar file
#      that Google Calendar, Outlook, Thunderbird and both phone OSes
#      import, so the schedule can live in her own phone calendar with its
#      own alerts. Times are written floating (no VTIMEZONE, no Z suffix)
#      so 17:00 stays 17:00 wherever it is opened, and each entry's UID is
#      derived from its date/time/title, so re-exporting the same week
#      updates those entries instead of duplicating them.
#  14. DONE (DEL 07/08): reminders that came due while TutorCal was
#      CLOSED are no longer lost. The engine only ever looks forward (it
#      skips anything already started, which is right while the app is
#      running and useless while it isn't), so the first alarm tick after
#      startup now looks *back* instead: find_missed_reminders() collects
#      anything with a "Warn before" that started within the last 12
#      hours and never actually got shown, and one non-modal summary
#      window lists them. Acknowledging it marks them handled so the same
#      list doesn't greet her again at the next start.
#  15. DONE (DEL 06b): dates are no longer typed. Every date field - the
#      List View add form, both override date fields, the Export tab's
#      custom range, and the date rows in the shared edit dialog (field
#      kind "date") - has a small calendar button beside it that opens a
#      month grid (ask_date), with today marked and the current value
#      highlighted. Typing YYYY-MM-DD by hand still works exactly as
#      before; the picker just writes the same text into the field. Two
#      details worth keeping: date_picker_button takes an on_pick hook,
#      because picking a date fires no key event and the override form
#      recalculates its Slot dropdown on <KeyRelease>; and ask_date hands
#      the grab back to whatever modal window it was opened from, since
#      Tk has only one global grab and destroying the picker does not
#      restore the previous one by itself.
#  16. DONE (DEL 08d/08e): the Week View and Day View draw a "you are
#      here" line across today at the current time, with the time written
#      at its right end. It creeps down once a minute via _tick_now_line,
#      which deletes and redraws only the three items tagged "now_line" -
#      the grid itself is never rebuilt for it, so nothing flickers.
#  17. DONE (DEL 07c): "Hours summary" on the Export tab. For whatever
#      date range the tab is set to, it counts how many times each entry
#      happened and how long they added up to, grouped by schedule and
#      then by title - which for the lesson schedule is the student's
#      name, i.e. exactly the unit an invoice is written in. It reads the
#      same occurrence data as the agenda, so a cancelled lesson is not
#      counted and a moved one counts on the day it actually happened.
#      Copy to Clipboard gives the same thing as plain text.
#
# 2026-08-29 note for whoever merges next: flash_taskbar() and the
# minimised-window fallback in _center_over() had gone missing from this
# file (they exist in the 2026-08-26 working copy) - a reminder popping up
# while the window was minimised was being centred on an iconified
# window's coordinates, i.e. off-screen, with nothing blinking in the
# taskbar. Both are back. The taskbar flash is deliberately finite now
# (five flashes, then Windows leaves the button highlighted) rather than
# blinking until looked at.
"""

import sys
import os
import json
import platform
import ctypes
import shutil
import subprocess
import traceback
import datetime
import webbrowser
import uuid
import urllib.parse
import urllib.request                  # DEL 10 - the phone page: sends the schedule to the server
import urllib.error
import threading
import hashlib
import base64

import tkinter as tk
from tkinter import ttk, messagebox, colorchooser


# ---- 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


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


try:
    import winsound          # Windows only - used for a nicer alarm sound
except ImportError:
    winsound = None          # any other OS just falls back to root.bell()

try:
    from PIL import Image, ImageDraw, ImageFont   # Export as Image (DEL 07c)
except ImportError:
    Image = ImageDraw = ImageFont = None          # not installed - "Export as Image" shows a friendly message

try:
    from fpdf import FPDF                          # Export as PDF (DEL 07c) - the fpdf2 package
except ImportError:
    FPDF = None                                    # not installed - "Export as PDF" shows a friendly message

# *************** DEL 00 - APP IDENTITY & COLOR CONSTANTS ***************

APP_NAME = "TutorCal"                       # keeps "Issu" out of the visible program name
APP_TITLE = "TutorCal - Lesson & Family Schedule Manager"
APP_ORG_ID = "Issu.TutorCal.1"              # AppUserModelID, set before Tk() is created

# Documentation link - TODO: add a real link here once written, and un-hide
# the label in _show_about() below (kept hidden while DOC_URL is empty so we
# never show a fake/broken link).
DOC_URL = ""

# Donation links (same links used across Issu's other tools)
REVOLUT_URL = "https://revolut.me/lars72oeh"
PAYPAL_URL = "https://paypal.me/issusbarn"
WISE_URL = "https://wise.com/pay/me/larsdenniso"

# ---- Button / UI colors --------------------------------------------
# Change any of these to red / blue / green / white / grey etc. below -
# nothing else in the code needs to change.
COLOR_BG_MAIN = "#f4f1ec"
COLOR_BG_PANEL = "#ffffff"
COLOR_BG_HEADER = "#1e5f52"
COLOR_TEXT_MAIN = "#232323"
COLOR_TEXT_DIM = "#6c6c6c"
COLOR_TEXT_ON_HEADER = "#ffffff"
COLOR_SEPARATOR = "#d8d4cc"

COLOR_BTN_NORMAL = "#3a3a3a"     # neutral / default button
COLOR_BTN_NORMAL_FG = "#ffffff"
COLOR_BTN_ACCENT = "#e67a3c"     # primary action (e.g. "Add")
COLOR_BTN_ACCENT_FG = "#ffffff"
COLOR_BTN_SUCCESS = "#2f9e63"    # confirmations / positive action
COLOR_BTN_SUCCESS_FG = "#ffffff"
COLOR_BTN_DANGER = "#c94f4f"     # delete / destructive action
COLOR_BTN_DANGER_FG = "#ffffff"

FONT_MAIN = ("Segoe UI", 10)
FONT_HEADER = ("Segoe UI", 13, "bold")
FONT_SMALL = ("Segoe UI", 8)
FONT_TINY = ("Segoe UI", 7)

WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

# ---- Week View geometry (DEL 08d) ------------------------------------
# The Week View is a real time grid: seven day columns, one row per hour,
# and every lesson/appointment drawn as a block whose height is its actual
# duration. These are the defaults - the drawn range grows automatically
# when something that week starts earlier or ends later.
WEEK_VIEW_DEFAULT_START_HOUR = 7
WEEK_VIEW_DEFAULT_END_HOUR = 21
WEEK_VIEW_HOUR_HEIGHT = 42      # pixels per hour (a 14-hour day fits a default window)
WEEK_VIEW_GUTTER_WIDTH = 56     # left column holding the hour labels
WEEK_VIEW_HEADER_HEIGHT = 40    # day-name row at the top of the grid
WEEK_VIEW_MIN_BLOCK_HEIGHT = 16
WEEK_VIEW_DEFAULT_MINUTES = 60  # block length used when a row has no end time
WEEK_VIEW_DRAG_EDGE_PX = 6      # bottom strip of a block that grabs for resize, not move
WEEK_VIEW_DRAG_SNAP_MINUTES = 15  # dragging/resizing snaps to a quarter hour
WEEK_VIEW_DRAG_THRESHOLD_PX = 3  # smaller mouse movement than this is a click, not a drag
COLOR_NOW_LINE = "#c0392b"      # "you are here" line across today's column
NOW_LINE_TICK_MS = 60000        # once a minute; only that one line is redrawn, never the grid
COLOR_WEEK_GRID_LINE = "#e2ded6"
COLOR_WEEK_HALFHOUR_LINE = "#f0ece5"
COLOR_WEEK_TODAY_COLUMN = "#fdf0e6"

# ---- "Today" highlight on the Month View grid ------------------------
# Deliberately heavier than the rest of the grid lines - the old 1-pixel
# orange outline was too easy to miss (see DEL 08b).
COLOR_TODAY_OUTLINE = "#e0651b"
COLOR_TODAY_CELL_BG = "#fdf0e6"
TODAY_OUTLINE_THICKNESS = 3

# ---- Fixed ("system") chip styling ------------------------------------
# (label, background, foreground) - used both for the small chips inside
# each day cell and for the legend above the grid. These four are produced
# by the program itself (an override or a one-off entry), so they are NOT
# user-editable; every *schedule* category is defined by the user on the
# Settings tab instead (see SCHEDULE_DEFS below).
SYSTEM_CATEGORY_STYLES = {
    "moved":       ("Moved lesson",  "#3b6fa0",         "#ffffff"),
    "cancelled":   ("Cancelled",     "#c9c4b8",         "#5a5650"),
    "note_only":   ("Override note", "#cfae4a",         "#3a3020"),
    "event":       ("Event / note",  COLOR_BTN_SUCCESS, COLOR_BTN_SUCCESS_FG),
}

# ---- User-defined schedule types (DEL 08b) ---------------------------
# Everything that used to be a hard-coded category ("her schedule", "son's
# school", "son's bus", "son's daycare") is now just a row in this list,
# which the user edits on the Settings tab: she can rename them, recolour
# them, reorder them, delete them, and add as many new ones as she likes.
# Only "lesson" is built in and undeletable - it is the base tutoring
# schedule and its rows live in base_schedule.json, not in
# personal_schedules.json like every other schedule's rows do.
#
# Each definition:
#   key          internal id, never shown, never changes (data is keyed by it)
#   name         what the user typed - shown on chips, tabs, dropdowns
#   color        chip background; the text colour is derived automatically
#   start_field  name of the "from" field in that schedule's saved rows
#   end_field    name of the "to" field
#   start_label  column/field heading for the "from" field
#   end_label    column/field heading for the "to" field
#   builtin      True only for "lesson" (cannot be deleted)
#
# start_field/end_field exist purely for backwards compatibility: the old
# bus schedule saved its times as "departs"/"arrives" rather than
# "start"/"end", and those rows must keep working. Newly created
# schedules always use plain "start"/"end".
DEFAULT_SCHEDULE_DEFS = [
    {"key": "lesson", "name": "Lesson", "color": COLOR_BTN_ACCENT,
     "start_field": "start", "end_field": "end",
     "start_label": "Start", "end_label": "End", "builtin": True},
    {"key": "tutor_own", "name": "Her schedule", "color": "#8a5fb0",
     "start_field": "start", "end_field": "end",
     "start_label": "Start", "end_label": "End", "builtin": False},
    {"key": "son_school", "name": "Son: school", "color": "#3a8fa0",
     "start_field": "start", "end_field": "end",
     "start_label": "Start", "end_label": "End", "builtin": False},
    {"key": "son_bus", "name": "Son: bus", "color": "#a06a3a",
     "start_field": "departs", "end_field": "arrives",
     "start_label": "Departs", "end_label": "Arrives", "builtin": False},
    {"key": "son_daycare", "name": "Son: daycare", "color": "#5f9e6a",
     "start_field": "start", "end_field": "end",
     "start_label": "Start", "end_label": "End", "builtin": False},
]

# Colours offered as ready-made swatches in the colour picker - the user
# can always click "Custom colour..." for anything else.
SUGGESTED_COLORS = [
    "#e67a3c", "#c94f4f", "#a0522d", "#cfae4a", "#8a8f2f", "#2f9e63",
    "#5f9e6a", "#3a8fa0", "#3b6fa0", "#5a63b8", "#8a5fb0", "#b0508f",
    "#7a6a5a", "#4a4a4a", "#8f9aa6", "#1e5f52",
]

# Suggested messaging/contact apps - offered as a one-click "Add suggested
# apps" button on the Settings tab. The saved list itself starts EMPTY on
# purpose: the App dropdown must default to blank until the user has said
# which apps she actually uses.
SUGGESTED_CONTACT_APPS = [
    "WhatsApp", "SMS", "Phone", "Email", "Signal", "Telegram",
    "Messenger", "Instagram", "Teams", "Discord",
]

# Roles offered in the Contacts tab. Also user-editable (Settings tab),
# except "Student", which the "Linked student" feature depends on.
DEFAULT_CONTACT_ROLES = ["Student", "Guardian", "School", "Daycare", "Other"]
PROTECTED_CONTACT_ROLES = ("Student",)

# ---- Runtime tables derived from the user's schedule definitions ------
# These four used to be hand-written constants. They are now rebuilt by
# apply_schedule_defs() at startup and again every time the user edits the
# schedule list, so the rest of the program (chips, layer checkboxes,
# override dropdown, alarm engine, export) picks up the change with no
# further wiring.
SCHEDULE_DEFS = [dict(d) for d in DEFAULT_SCHEDULE_DEFS]
CATEGORY_STYLES = {}          # category key -> (label, bg, fg)
FAMILY_SCHEDULE_FIELDS = {}   # non-lesson key -> (start_field, end_field)
OVERRIDE_CATEGORY_CHOICES = []  # [(key, label), ...] for the override dropdown
EXPORT_LAYER_KEYS = ()        # every schedule key, in the user's own order


def readable_fg(hex_color):
    """Black or white text, whichever stays readable on `hex_color`.
    Keeps user-picked chip colours legible without asking her to pick a
    text colour too."""
    try:
        h = hex_color.lstrip("#")
        r, g, b = (int(h[i:i + 2], 16) for i in (0, 2, 4))
    except Exception:
        return "#ffffff"
    return "#232323" if (0.299 * r + 0.587 * g + 0.114 * b) > 150 else "#ffffff"


def apply_schedule_defs(defs):
    """Publish a new list of schedule definitions into the module-level
    lookup tables every other part of the program reads."""
    global SCHEDULE_DEFS, CATEGORY_STYLES, FAMILY_SCHEDULE_FIELDS
    global OVERRIDE_CATEGORY_CHOICES, EXPORT_LAYER_KEYS

    SCHEDULE_DEFS = defs
    styles = dict(SYSTEM_CATEGORY_STYLES)
    fields, choices, keys = {}, [], []
    for d in defs:
        key = d["key"]
        styles[key] = (d["name"], d["color"], readable_fg(d["color"]))
        choices.append((key, d["name"]))
        keys.append(key)
        if key != "lesson":   # "lesson" rows live in base_schedule.json
            fields[key] = (d.get("start_field", "start"), d.get("end_field", "end"))
    CATEGORY_STYLES = styles
    FAMILY_SCHEDULE_FIELDS = fields
    OVERRIDE_CATEGORY_CHOICES = choices
    EXPORT_LAYER_KEYS = tuple(keys)


apply_schedule_defs(SCHEDULE_DEFS)   # sane defaults until the saved list is loaded


def normalize_schedule_defs(defs):
    """Repair anything missing/garbled in a loaded schedule_types.json and
    guarantee the built-in "lesson" schedule is present exactly once."""
    clean = []
    seen = set()
    for d in defs if isinstance(defs, list) else []:
        if not isinstance(d, dict):
            continue
        key = str(d.get("key", "")).strip()
        if not key or key in seen or key in SYSTEM_CATEGORY_STYLES:
            continue    # no key, a duplicate, or clashing with a system chip
        seen.add(key)
        clean.append({
            "key": key,
            "name": str(d.get("name") or key),
            "color": str(d.get("color") or "#3a8fa0"),
            "start_field": str(d.get("start_field") or "start"),
            "end_field": str(d.get("end_field") or "end"),
            "start_label": str(d.get("start_label") or "Start"),
            "end_label": str(d.get("end_label") or "End"),
            "builtin": bool(d.get("builtin")) or key == "lesson",
        })
    if "lesson" not in seen:
        clean.insert(0, dict(DEFAULT_SCHEDULE_DEFS[0]))
    return clean


def new_schedule_key(name, existing_keys):
    """Build a stable internal key for a newly created schedule. Derived
    from the typed name so the JSON stays readable, but never reused."""
    base = "".join(ch if ch.isalnum() else "_" for ch in name.strip().lower()).strip("_")
    base = base or "schedule"
    if base in SYSTEM_CATEGORY_STYLES:
        base = f"{base}_schedule"
    key, n = base, 2
    while key in existing_keys:
        key, n = f"{base}_{n}", n + 1
    return key


# *************** DEL 01 - PATH HANDLING (works as .py and frozen .exe) ***************

def get_base_dir():
    """Always resolve relative to the program itself - .py or frozen .exe."""
    if getattr(sys, "frozen", False):
        return _program_home()
    return _program_home()


BASE_DIR = get_base_dir()
HELPFILES_DIR = os.path.join(BASE_DIR, "Helpfiles")

DIR_LOGS = os.path.join(HELPFILES_DIR, "0---Empty")            # logs only, per convention
DIR_SETTINGS = os.path.join(HELPFILES_DIR, "Settings")
DIR_CALENDAR = os.path.join(HELPFILES_DIR, "Calendar")
DIR_SCHEDULE = os.path.join(HELPFILES_DIR, "Schedule")
DIR_CONTACTS = os.path.join(HELPFILES_DIR, "Contacts")
DIR_EXPORT = os.path.join(HELPFILES_DIR, "Export")
DIR_BACKUPS = os.path.join(HELPFILES_DIR, "Backups")      # one dated folder per day (DEL 04b)

ICON_PATH = os.path.join(BASE_DIR, "Icons", f"{APP_NAME}.ico")  # external icon - not bundled

for _d in (DIR_LOGS, DIR_SETTINGS, DIR_CALENDAR, DIR_SCHEDULE, DIR_CONTACTS, DIR_EXPORT):
    os.makedirs(_d, exist_ok=True)

SETTINGS_PATH = os.path.join(DIR_SETTINGS, "settings.json")
ALARM_STATE_PATH = os.path.join(DIR_SETTINGS, "alarm_state.json")
# User-defined lists edited on the Settings tab (DEL 08b)
SCHEDULE_TYPES_PATH = os.path.join(DIR_SETTINGS, "schedule_types.json")
CONTACT_APPS_PATH = os.path.join(DIR_SETTINGS, "contact_apps.json")
CONTACT_ROLES_PATH = os.path.join(DIR_SETTINGS, "contact_roles.json")
EVENTS_PATH = os.path.join(DIR_CALENDAR, "events.json")
BASE_SCHEDULE_PATH = os.path.join(DIR_SCHEDULE, "base_schedule.json")
OVERRIDES_PATH = os.path.join(DIR_SCHEDULE, "temp_overrides.json")
PERSONAL_SCHEDULES_PATH = os.path.join(DIR_SCHEDULE, "personal_schedules.json")
CONTACTS_PATH = os.path.join(DIR_CONTACTS, "contacts.json")

# Everything that is genuinely the user's own data (settings and
# alarm_state are deliberately left out - they rebuild themselves and are
# not worth restoring from a week-old copy). Backed up once a day by
# make_daily_backup(), DEL 04b.
BACKED_UP_DATA_FILES = (
    EVENTS_PATH, BASE_SCHEDULE_PATH, OVERRIDES_PATH, PERSONAL_SCHEDULES_PATH,
    CONTACTS_PATH, SCHEDULE_TYPES_PATH, CONTACT_APPS_PATH, CONTACT_ROLES_PATH,
)


# *************** DEL 02 - CRASH CATCHER & DIAGNOSTICS ***************

def install_crash_catcher():
    def handle_exception(exc_type, exc_value, exc_tb):
        ts = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        log_path = os.path.join(DIR_LOGS, f"crash_{ts}.txt")
        text = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
        try:
            with open(log_path, "w", encoding="utf-8") as f:
                f.write(text)
        except Exception:
            pass
        try:
            messagebox.showerror(
                "Unexpected error",
                f"{APP_NAME} ran into a problem.\n\n"
                f"Details were saved to:\n{log_path}\n\n{exc_value}",
            )
        except Exception:
            pass

    sys.excepthook = handle_exception


# *************** DEL 03 - NO-BLINK TEXT WIDGET HELPERS ***************
# Rule: never ttk.Entry for text input - only tk.Entry / tk.Text, with a
# fixed (non-blinking) caret, applied at creation time on every widget,
# including ones inside Toplevel dialogs.

def no_blink(widget):
    try:
        widget.configure(insertofftime=0, insertontime=9999999)
    except Exception:
        pass


def make_entry(parent, **kw):
    e = tk.Entry(parent, insertofftime=0, insertontime=9999999, **kw)
    assert e.cget("insertofftime") == 0
    return e


def make_text(parent, **kw):
    t = tk.Text(parent, insertofftime=0, insertontime=9999999, **kw)
    assert t.cget("insertofftime") == 0
    return t


# *************** DEL 04 - SETTINGS PERSISTENCE (window size, last tab, ...) ***************

DEFAULT_SETTINGS = {
    "geometry": "1180x760",
    "last_tab": 0,
    "last_calendar_tab": 0,   # Month View / Week View / List View
    "export_range": "Next 7 days",
    "export_layers": {},   # populated with EXPORT_LAYER_KEYS defaults at app init (DEL 07c/08) -
                            # can't reference EXPORT_LAYER_KEYS here, it's defined further down the file
    "phone_enabled": False,   # DEL 10: keep the phone page up to date automatically
    "phone_code": "",         # DEL 10: the TCAL1:... code from the server installer (address + key)
}


# ---- Crash-safe JSON files (DEL 04b) ---------------------------------
# Every list/dict below IS the user's data - a year of lessons, her
# contacts, the family schedules. Two rules make sure a bad moment can
# never quietly erase it:
#
#   1. WRITING is atomic. The new content goes to "<file>.tmp", is
#      flushed to disk, and only then replaces the real file with
#      os.replace(). A crash or a power cut mid-write leaves either the
#      old file or the temp file - never a half-written one. The previous
#      content is kept one generation back as "<file>.bak" first.
#   2. READING never turns damage into silence. The old code treated an
#      unreadable file exactly like a missing one and returned an empty
#      list; the app then came up empty and the next save wrote that
#      emptiness straight over the only copy. Now an unreadable file is
#      RENAMED to "<file>.corrupt-<timestamp>" (so it survives for a hand
#      repair), its ".bak" is tried as a fallback, and what happened is
#      recorded in DATA_PROBLEMS and shown to the user at startup instead
#      of being swallowed.
#
# The four load_json_* / save_json_* names below are kept as-is so the
# rest of the program (and the test files) call exactly what they always
# called - only what happens underneath changed.

DATA_PROBLEMS = []      # human-readable notes, reported once the window is up


def _quarantine_file(path, why):
    """Move a file that couldn't be read out of the way instead of
    letting it be overwritten, and remember why. Returns the new path, or
    None if even the rename failed."""
    stamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    target = f"{path}.corrupt-{stamp}"
    try:
        os.replace(path, target)
    except Exception:
        DATA_PROBLEMS.append(f"{os.path.basename(path)}: {why} (and it could not be moved aside)")
        return None
    DATA_PROBLEMS.append(f"{os.path.basename(path)}: {why}\n"
                         f"    kept as: {os.path.basename(target)}")
    return target


def _read_json_typed(path, expected_type):
    """(data, None) on success, (None, reason) if the file can't be used.
    A file of the wrong shape (an object where a list belongs) counts as
    unusable - handing it on would just crash somewhere less obvious."""
    try:
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
    except Exception as exc:
        return None, f"unreadable ({type(exc).__name__})"
    if not isinstance(data, expected_type):
        return None, f"wrong format (expected a JSON {expected_type.__name__})"
    return data, None


def load_json_file(path, default):
    """Read one of the program's JSON data files. The expected shape is
    taken from `default` (a list or a dict), so personal_schedules.json -
    a dict saved through save_json_list() - still checks correctly."""
    expected_type = type(default)
    if os.path.isfile(path):
        data, why = _read_json_typed(path, expected_type)
        if why is None:
            return data
        # Damaged: keep it, then try the copy made before the last write.
        _quarantine_file(path, why)
        backup = f"{path}.bak"
        if os.path.isfile(backup):
            data, backup_why = _read_json_typed(backup, expected_type)
            if backup_why is None:
                DATA_PROBLEMS.append(f"    -> recovered from {os.path.basename(backup)}")
                return data
    return default


def save_json_file(path, data):
    """Atomic write + one generation of backup. Returns True on success."""
    tmp = f"{path}.tmp"
    try:
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
            f.flush()
            os.fsync(f.fileno())
    except Exception:
        try:
            os.remove(tmp)
        except Exception:
            pass
        return False
    if os.path.isfile(path):
        try:
            shutil.copy2(path, f"{path}.bak")
        except Exception:
            pass      # a missing .bak is a smaller problem than not saving at all
    try:
        os.replace(tmp, path)
        return True
    except Exception:
        return False


def load_settings():
    merged = dict(DEFAULT_SETTINGS)
    merged.update(load_json_file(SETTINGS_PATH, {}))
    return merged


def save_settings(data):
    save_json_file(SETTINGS_PATH, data)


def load_json_list(path, default=None):
    return load_json_file(path, [] if default is None else default)


def save_json_list(path, data):
    save_json_file(path, data)


def load_json_dict(path, default=None):
    """Same as load_json_list but for a JSON object instead of an array -
    used for alarm_state.json (keyed by event id)."""
    return load_json_file(path, {} if default is None else default)


def save_json_dict(path, data):
    save_json_file(path, data)


def make_daily_backup(keep=14):
    """Once a day, on startup, copy every data file into
    Helpfiles/Backups/<date>/ before the running program can touch it.
    The atomic writes above protect against a bad write; this protects
    against a bad *edit* - a schedule deleted by accident three days ago
    is still sitting in one of these folders. Only the newest `keep` days
    are kept, and a day that already has a folder is skipped, so this
    costs nothing on the second start of the day."""
    try:
        os.makedirs(DIR_BACKUPS, exist_ok=True)
        today_dir = os.path.join(DIR_BACKUPS, datetime.date.today().isoformat())
        if os.path.isdir(today_dir):
            return None
        os.makedirs(today_dir, exist_ok=True)
        copied = 0
        for src in BACKED_UP_DATA_FILES:
            if os.path.isfile(src):
                try:
                    shutil.copy2(src, os.path.join(today_dir, os.path.basename(src)))
                    copied += 1
                except Exception:
                    pass
        if not copied:      # nothing to protect yet (first ever run) - don't leave an empty folder
            try:
                os.rmdir(today_dir)
            except Exception:
                pass
            return None
        old = sorted(d for d in os.listdir(DIR_BACKUPS)
                     if os.path.isdir(os.path.join(DIR_BACKUPS, d)))
        for name in old[:-keep] if len(old) > keep else []:
            shutil.rmtree(os.path.join(DIR_BACKUPS, name), ignore_errors=True)
        return today_dir
    except Exception:
        return None      # a backup that fails must never stop the program from starting


# *************** DEL 05 - ICON HANDLING (external .ico, 3-rule approach) ***************

def apply_app_user_model_id():
    if platform.system() != "Windows":
        return
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APP_ORG_ID)
    except Exception:
        pass


def set_window_icon(root):
    if platform.system() != "Windows":
        return
    if not os.path.isfile(ICON_PATH):
        return
    try:
        root.iconbitmap(ICON_PATH)
    except Exception:
        pass
    try:
        user32 = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE = 0x0040
        IMAGE_ICON = 1
        WM_SETICON = 0x0080
        hwnd = user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ICON_PATH, IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ICON_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 06 - GENERIC UI HELPERS (scroll, auto-dismiss popup, Enter-to-submit) ***************

def make_scrollable_frame(parent, bg=COLOR_BG_PANEL):
    """Returns (outer_frame, inner_frame). Put widgets inside inner_frame.
    Scrollbar + mouse-wheel scroll are wired automatically, and the wheel
    binding is scoped to only be active while the mouse is over this
    canvas (so it does not hijack scrolling on other tabs)."""
    outer = tk.Frame(parent, bg=bg)
    canvas = tk.Canvas(outer, bg=bg, highlightthickness=0)
    vsb = ttk.Scrollbar(outer, orient="vertical", command=canvas.yview)
    inner = tk.Frame(canvas, bg=bg)
    canvas.create_window((0, 0), window=inner, anchor="nw")

    def _on_configure(_event):
        canvas.configure(scrollregion=canvas.bbox("all"))

    inner.bind("<Configure>", _on_configure)
    canvas.configure(yscrollcommand=vsb.set)
    canvas.pack(side="left", fill="both", expand=True)
    vsb.pack(side="right", fill="y")

    def _on_wheel(event):
        canvas.yview_scroll(-1 if event.delta > 0 else 1, "units")

    def _bind_wheel(_e):
        canvas.bind_all("<MouseWheel>", _on_wheel)

    def _unbind_wheel(_e):
        canvas.unbind_all("<MouseWheel>")

    canvas.bind("<Enter>", _bind_wheel)
    canvas.bind("<Leave>", _unbind_wheel)
    return outer, inner


def show_auto_popup(root, message, title="Done", ms=1000):
    """Success-style popup that closes itself after ms milliseconds."""
    top = tk.Toplevel(root)
    top.title(title)
    top.configure(bg=COLOR_BG_PANEL)
    top.resizable(False, False)
    top.transient(root)
    tk.Label(
        top, text=message, bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
        font=FONT_MAIN, padx=26, pady=18,
    ).pack()
    top.update_idletasks()
    _center_over(top, root)
    top.after(ms, lambda: top.destroy() if top.winfo_exists() else None)


def _center_over(win, root):
    try:
        win.update_idletasks()
        # Centring over a minimised main window puts the dialog wherever
        # Windows parks an iconified window - i.e. nowhere useful. That
        # matters for reminders, which are exactly the thing that shows up
        # while TutorCal is out of the way, so fall back to the screen.
        if root.state() == "iconic" or not root.winfo_viewable():
            _center_on_screen(win)
            return
        x = root.winfo_x() + (root.winfo_width() - win.winfo_width()) // 2
        y = root.winfo_y() + (root.winfo_height() - win.winfo_height()) // 2
        win.geometry(f"+{max(0, x)}+{max(0, y)}")
    except Exception:
        pass


def _center_on_screen(win):
    try:
        win.update_idletasks()
        x = (win.winfo_screenwidth() - win.winfo_width()) // 2
        y = (win.winfo_screenheight() - win.winfo_height()) // 3
        win.geometry(f"+{max(0, x)}+{max(0, y)}")
    except Exception:
        pass


def flash_taskbar(window):
    """Blink the app's taskbar button so a reminder is noticed even when
    TutorCal is minimised or buried behind another program. Windows-only.

    Deliberately FINITE: five flashes (FLASHW_ALL, no FLASHW_TIMERNOFG),
    not "blink until someone looks at it". Windows leaves the taskbar
    button highlighted afterwards, so the reminder is still visible when
    she comes back, without anything on screen strobing away for minutes.
    Flashing never steals focus either way, so nothing is lost by it.
    Returns True if the OS accepted it; everywhere else the caller still
    gets the sound, the OS toast and the topmost popup."""
    if platform.system() != "Windows":
        return False
    try:
        class FLASHWINFO(ctypes.Structure):
            _fields_ = [("cbSize", ctypes.c_uint),
                        ("hwnd", ctypes.c_void_p),
                        ("dwFlags", ctypes.c_uint),
                        ("uCount", ctypes.c_uint),
                        ("dwTimeout", ctypes.c_uint)]

        # winfo_id() is the Tk frame; the window with the taskbar button
        # (and thus the one worth flashing) is its parent.
        user32 = ctypes.windll.user32
        user32.GetParent.restype = ctypes.c_void_p
        user32.GetParent.argtypes = [ctypes.c_void_p]
        child = ctypes.c_void_p(window.winfo_id())
        hwnd = user32.GetParent(child) or window.winfo_id()
        info = FLASHWINFO(ctypes.sizeof(FLASHWINFO), ctypes.c_void_p(hwnd),
                          0x00000003,   # FLASHW_ALL - caption + taskbar button, five times
                          5, 0)
        user32.FlashWindowEx(ctypes.byref(info))
        return True
    except Exception:
        return False


def bind_enter_to(widget, callback):
    widget.bind("<Return>", lambda _e: callback())


def styled_button(parent, text, command, bg, fg, **kw):
    return tk.Button(
        parent, text=text, command=command, bg=bg, fg=fg,
        activebackground=bg, activeforeground=fg,
        relief="flat", padx=10, pady=4, font=FONT_MAIN, **kw,
    )


def not_implemented_yet(root, feature_name):
    messagebox.showinfo(
        "Not built yet",
        f"'{feature_name}' is a placeholder in this skeleton version.\n"
        f"See the '# TODO' comments in the source for what it needs to do.",
        parent=root,
    )


# ---- Date picker (DEL 06b) -------------------------------------------
# Every date in this program is stored and typed as YYYY-MM-DD, which is
# unambiguous but a poor thing to have to type - and the rest of the app
# is click-and-drag. So every date field gets a small calendar button
# beside it. The picker is a plain month grid built from the same
# month_grid_weeks() the Month View uses, so "the 3rd Tuesday" looks the
# same in both places. It writes the same YYYY-MM-DD text back into the
# field, so nothing downstream has to know it exists and typing by hand
# keeps working exactly as before.

def ask_date(root, initial=None, title="Pick a date"):
    """Modal month grid. Returns a datetime.date, or None if cancelled."""
    initial = initial or datetime.date.today()
    result = {"date": None}
    shown = {"year": initial.year, "month": initial.month}
    # Tk has one global grab. Opening this on top of a modal edit dialog
    # takes that dialog's grab away, and destroying this window does not
    # give it back on its own - so remember who had it and hand it back.
    try:
        previous_grab = root.grab_current()
    except Exception:
        previous_grab = None

    top = tk.Toplevel(root)
    top.title(title)
    top.configure(bg=COLOR_BG_PANEL)
    top.resizable(False, False)
    top.transient(root)
    top.grab_set()
    top.bind("<Escape>", lambda _e: top.destroy())

    head = tk.Frame(top, bg=COLOR_BG_PANEL)
    head.pack(fill="x", padx=10, pady=(10, 4))
    title_lbl = tk.Label(head, text="", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                         font=("Segoe UI", 11, "bold"), width=18)
    grid_frame = tk.Frame(top, bg=COLOR_BG_PANEL)
    grid_frame.pack(padx=10, pady=(0, 4))

    def choose(date_obj):
        result["date"] = date_obj
        top.destroy()

    def redraw():
        for child in grid_frame.winfo_children():
            child.destroy()
        title_lbl.configure(text=datetime.date(shown["year"], shown["month"], 1)
                            .strftime("%B %Y"))
        for column, name in enumerate(WEEKDAYS):
            tk.Label(grid_frame, text=name[:2], bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM,
                     font=FONT_SMALL, width=4).grid(row=0, column=column, padx=1, pady=(0, 2))
        today = datetime.date.today()
        for row, week in enumerate(month_grid_weeks(shown["year"], shown["month"]), start=1):
            for column, d in enumerate(week):
                in_month = (d.month == shown["month"])
                if d == initial:
                    bg, fg = COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG
                elif d == today:
                    bg, fg = COLOR_TODAY_CELL_BG, COLOR_TODAY_OUTLINE
                else:
                    bg, fg = (COLOR_BG_PANEL, COLOR_TEXT_MAIN if in_month else COLOR_TEXT_DIM)
                tk.Button(grid_frame, text=str(d.day), width=4, relief="flat",
                          bg=bg, fg=fg, activebackground=COLOR_SEPARATOR, font=FONT_SMALL,
                          command=lambda dd=d: choose(dd)).grid(row=row, column=column,
                                                                padx=1, pady=1)

    def step(months):
        month = shown["month"] + months
        year = shown["year"] + (month - 1) // 12
        shown["year"], shown["month"] = year, (month - 1) % 12 + 1
        redraw()

    styled_button(head, "<", lambda: step(-1), COLOR_BTN_NORMAL,
                  COLOR_BTN_NORMAL_FG).pack(side="left")
    title_lbl.pack(side="left", padx=6)
    styled_button(head, ">", lambda: step(1), COLOR_BTN_NORMAL,
                  COLOR_BTN_NORMAL_FG).pack(side="left")

    foot = tk.Frame(top, bg=COLOR_BG_PANEL)
    foot.pack(fill="x", padx=10, pady=(0, 10))
    styled_button(foot, "Today", lambda: choose(datetime.date.today()),
                  COLOR_BTN_SUCCESS, COLOR_BTN_SUCCESS_FG).pack(side="left")
    styled_button(foot, "Cancel (Esc)", top.destroy, COLOR_BTN_NORMAL,
                  COLOR_BTN_NORMAL_FG).pack(side="right")

    redraw()
    top.update_idletasks()
    _center_over(top, root)
    top.wait_window()
    if previous_grab is not None:
        try:
            if previous_grab.winfo_exists():
                previous_grab.grab_set()
        except Exception:
            pass
    return result["date"]


def date_picker_button(parent, root, entry=None, var=None, title="Pick a date", on_pick=None):
    """The little calendar button that sits next to a date field. Reads
    whatever is in the field as the starting month (today if it's blank or
    nonsense) and writes the chosen date back in YYYY-MM-DD. Works with
    either a plain Entry or a StringVar-backed field.

    on_pick runs after a date has been written, for fields that something
    else watches: picking a date fires no key event, so a form that
    recalculates itself on <KeyRelease> would otherwise not notice."""
    def read():
        if var is not None:
            return var.get()
        return entry.get() if entry is not None else ""

    def write(text):
        if var is not None:
            var.set(text)
        elif entry is not None:
            entry.delete(0, "end")
            entry.insert(0, text)

    def open_picker():
        picked = ask_date(root, safe_parse_date(read().strip()), title)
        if picked:
            write(picked.isoformat())
            if on_pick is not None:
                on_pick()

    button = tk.Button(parent, text="\U0001F4C5", command=open_picker, relief="flat",
                       bg=COLOR_BG_PANEL, activebackground=COLOR_SEPARATOR,
                       font=FONT_MAIN, cursor="hand2", padx=2, pady=0)
    return button


# *************** DEL 07 - ALARM / REMINDER LEAD-TIME + INTERVAL LOGIC ***************
# This part computes *which choices make sense to offer* for lead time /
# repeat interval. The part that actually fires a reminder while the event
# approaches now lives in DEL 07b (the Tk `after()` polling loop - see
# master ToDo #2 above) and armed/fired state is persisted to
# Helpfiles/Settings/alarm_state.json so it survives an app restart.

ALARM_LEAD_CHOICES = [
    ("None", None),
    ("1 hour before", 60 * 60),
    ("3 hours before", 3 * 60 * 60),
    ("6 hours before", 6 * 60 * 60),
    ("12 hours before", 12 * 60 * 60),
    ("1 day before", 24 * 60 * 60),
    ("2 days before", 2 * 24 * 60 * 60),
    ("3 days before", 3 * 24 * 60 * 60),
    ("1 week before", 7 * 24 * 60 * 60),
]


def get_allowed_alarm_intervals(lead_seconds):
    """Return only the repeat-interval choices that make sense for how far
    out the lead time is - e.g. don't offer 'every hour' when the lead
    time is 3 days, and don't offer 'every day' when it's 3 hours.
    TODO: placeholder tiers - refine the exact cadence with real usage."""
    if not lead_seconds:
        return ["(no repeat)"]
    day = 24 * 60 * 60
    hour = 60 * 60
    if lead_seconds > 3 * day:
        return ["(no repeat)", "Once a day", "Every 12 hours"]
    elif lead_seconds > day:
        return ["(no repeat)", "Every 12 hours", "Every 6 hours", "Every hour"]
    elif lead_seconds > 6 * hour:
        return ["(no repeat)", "Every hour", "Every 30 minutes"]
    else:
        return ["(no repeat)", "Every 30 minutes", "Every 15 minutes", "Every 5 minutes"]


# Seconds-per-repeat-label lookup for the choices produced above - this is
# what the alarm engine (DEL 08) uses to decide how often to re-fire a
# reminder that's still inside its warning window.
ALARM_REPEAT_SECONDS = {
    "(no repeat)": None,
    "Once a day": 24 * 60 * 60,
    "Every 12 hours": 12 * 60 * 60,
    "Every 6 hours": 6 * 60 * 60,
    "Every hour": 60 * 60,
    "Every 30 minutes": 30 * 60,
    "Every 15 minutes": 15 * 60,
    "Every 5 minutes": 5 * 60,
}

ALARM_CHECK_INTERVAL_MS = 15000  # how often the alarm engine polls the clock


def event_datetime(ev):
    """Combine a Calendar > List View event's date + start time into a
    single datetime, so the alarm engine can compare it against 'now'.
    An event with no start time (or an unparsable one) is treated as
    happening at midnight on its date."""
    d = safe_parse_date(ev.get("date", ""))
    if d is None:
        return None
    start = (ev.get("start") or "").strip()
    if start:
        try:
            hh, mm = start.split(":", 1)
            return datetime.datetime.combine(d, datetime.time(int(hh), int(mm)))
        except Exception:
            pass
    return datetime.datetime.combine(d, datetime.time(0, 0))


def ensure_event_ids(events):
    """Assign a stable id to any calendar event that doesn't already have
    one (events.json files saved before the alarm engine existed won't
    have ids yet). Returns True if anything changed, so the caller knows
    it needs to re-save the list."""
    changed = False
    for ev in events:
        if not ev.get("id"):
            ev["id"] = uuid.uuid4().hex
            changed = True
    return changed


def ensure_contact_ids(contacts):
    """Same idea as ensure_event_ids, but for contacts.json - contacts now
    need a stable id so the 'Linked student' / 'Linked event' dropdowns on
    other contacts can reference them reliably (and so deleting a contact
    by its Treeview selection always removes the right one)."""
    changed = False
    for c in contacts:
        if not c.get("id"):
            c["id"] = uuid.uuid4().hex
            changed = True
    return changed


def ensure_schedule_ids(rows):
    """Same idea as ensure_event_ids/ensure_contact_ids above, but for
    Base Schedule / Family Schedule rows. Each recurring slot now needs a
    stable id too, because the alarm engine tracks fired/dismissed state
    per *occurrence* (row id + the date that particular week's occurrence
    falls on - see generate_recurring_alarm_instances, DEL 07b, and the
    alarm engine, DEL 08), the same way one-off List View events already
    do. Rows saved before recurring slots supported alarms won't have an
    id yet, hence the back-fill."""
    changed = False
    for row in rows:
        if not row.get("id"):
            row["id"] = uuid.uuid4().hex
            changed = True
    return changed


def sync_repeat_choices_to_lead(lead_label, repeat_combobox, repeat_var):
    """Shared by every 'Warn before' / 'Repeat reminder' combobox pair in
    the app - the Calendar > List View form, and the lead/repeat fields
    added to Base Schedule and each Family Schedule row. Narrows the
    offered repeat intervals to ones that make sense for the chosen lead
    time (see get_allowed_alarm_intervals above) and resets the current
    selection if it's no longer one of the offered choices."""
    lead_seconds = dict(ALARM_LEAD_CHOICES).get(lead_label)
    choices = get_allowed_alarm_intervals(lead_seconds)
    repeat_combobox.configure(values=choices)
    if repeat_var.get() not in choices:
        repeat_var.set(choices[0])


# *************** DEL 07b - MONTH VIEW: DATES, OVERRIDES, OCCURRENCE GENERATION ***************
# This is the part of TODO #1 / #3 / #4 that is now implemented: turning the
# base weekly schedule + family schedules + one-off events + structured
# overrides into a set of dated "occurrences" the Month View grid can draw.
# Cancel/Move/Note-only overrides now work against any of the five
# recurring schedules (the base tutoring schedule, or any of the four
# family schedules - see FAMILY_SCHEDULE_FIELDS / OVERRIDE_CATEGORY_CHOICES
# and each override's "category" field), not just the tutoring schedule.
# DONE: drag-to-move/resize directly on the Week/Day View grids (the
# single-day zoom view mentioned in earlier revisions of this comment is
# now built - see DEL 08e - and the drag support itself is DEL 08f).

def safe_parse_date(s):
    """Parse 'YYYY-MM-DD' -> datetime.date, or None if invalid/blank."""
    try:
        return datetime.datetime.strptime((s or "").strip(), "%Y-%m-%d").date()
    except Exception:
        return None


def parse_hhmm(text, allow_24=False):
    """"17:30" -> 1050 (minutes past midnight). None for anything that
    isn't a real time, so the Week View can put such a row in the
    all-day strip instead of drawing it at a nonsense position."""
    try:
        parts = str(text).strip().split(":")
        hour, minute = int(parts[0]), int(parts[1])
    except (ValueError, IndexError, TypeError):
        return None
    limit = 24 if allow_24 else 23
    if not (0 <= hour <= limit and 0 <= minute < 60):
        return None
    if hour == 24 and minute:
        return None
    return hour * 60 + minute


def minutes_to_hhmm(minute, allow_24=False):
    """The inverse of parse_hhmm: minutes-past-midnight -> "HH:MM". Used
    by the Week/Day View drag-to-move/resize handlers (DEL 08f) to turn a
    dragged pixel position back into a time string. Clamped to a single
    day so a block can never be dragged into a nonsense time; allow_24
    mirrors parse_hhmm's own flag, for an end time allowed to land
    exactly on midnight ("24:00")."""
    minute = int(round(minute))
    if allow_24 and minute >= 24 * 60:
        return "24:00"
    minute = max(0, min(minute, 24 * 60 - 1))
    return f"{minute // 60:02d}:{minute % 60:02d}"


def week_start_for(date_obj):
    """The Monday of the week `date_obj` falls in - WEEKDAYS starts on
    Monday, so the Week View columns line up with the Month View's."""
    return date_obj - datetime.timedelta(days=date_obj.weekday())


def occurrence_span(occ):
    """(start_minute, end_minute) for a Week View block, or None when the
    occurrence has no usable start time (an all-day note, an entry saved
    without a time). An end that is missing, unparsable, or not after the
    start falls back to a default-length block rather than a zero-height
    sliver or an upside-down one."""
    start = parse_hhmm(occ.get("start"))
    if start is None:
        return None
    end = parse_hhmm(occ.get("end"), allow_24=True)
    if end is None or end <= start:
        end = start + WEEK_VIEW_DEFAULT_MINUTES
    return start, min(end, 24 * 60)


def layout_overlapping_blocks(items):
    """Side-by-side layout for blocks that overlap in time - the usual
    calendar behaviour, so two lessons at 17:00 sit next to each other
    instead of one hiding the other.

    items: [(start_minute, end_minute, payload), ...] in any order.
    Returns [(start, end, payload, column_index, column_count), ...],
    where column_count is shared by every block in the same overlapping
    cluster so they tile the day column exactly."""
    def place(cluster):
        column_ends = []      # when each column becomes free
        placed = []
        for start, end, payload in cluster:
            for index, free_at in enumerate(column_ends):
                if start >= free_at:
                    column_ends[index] = end
                    placed.append((start, end, payload, index))
                    break
            else:
                column_ends.append(end)
                placed.append((start, end, payload, len(column_ends) - 1))
        return [(s, e, p, i, len(column_ends)) for s, e, p, i in placed]

    out, cluster, cluster_end = [], [], None
    for item in sorted(items, key=lambda t: (t[0], t[1])):
        if cluster and item[0] < cluster_end:
            cluster.append(item)
            cluster_end = max(cluster_end, item[1])
        else:
            if cluster:
                out.extend(place(cluster))
            cluster, cluster_end = [item], item[1]
    if cluster:
        out.extend(place(cluster))
    return out


def week_view_hour_range(occurrences_by_date, dates):
    """The first and last hour the grid has to cover: the normal working
    range, widened when something that week falls outside it (an early bus
    at 06:40, an evening lesson ending at 21:30) so nothing is ever drawn
    off the top or bottom of the grid."""
    first, last = WEEK_VIEW_DEFAULT_START_HOUR, WEEK_VIEW_DEFAULT_END_HOUR
    for d in dates:
        for occ in occurrences_by_date.get(d.isoformat(), []):
            span = occurrence_span(occ)
            if span is None:
                continue
            first = min(first, span[0] // 60)
            last = max(last, -(-span[1] // 60))      # ceil to the next hour
    return max(0, first), min(24, max(last, first + 1))


def month_grid_weeks(year, month):
    """Return a list of weeks (Monday-first); each week is a list of 7
    datetime.date objects, padded with the trailing/leading days of the
    neighboring months so every week is full."""
    first = datetime.date(year, month, 1)
    start = first - datetime.timedelta(days=first.weekday())  # back up to Monday
    if month == 12:
        next_first = datetime.date(year + 1, 1, 1)
    else:
        next_first = datetime.date(year, month + 1, 1)
    last = next_first - datetime.timedelta(days=1)
    end = last + datetime.timedelta(days=(6 - last.weekday()))  # forward to Sunday

    weeks, cur = [], start
    while cur <= end:
        weeks.append([cur + datetime.timedelta(days=i) for i in range(7)])
        cur += datetime.timedelta(days=7)
    return weeks


def normalize_override(o):
    """Upgrade an older free-text {"date", "note"} override (from before
    the Month View existed) into the new structured schema, so old
    Helpfiles/Schedule/temp_overrides.json data keeps working untouched.
    Already-structured overrides are returned as-is. Also back-fills
    "category" (added when overrides gained support for family
    schedules, not just the base tutoring schedule) so overrides saved
    by an older version of TutorCal default to "lesson" - the only
    schedule that could be overridden before."""
    if "target_date" in o:
        o.setdefault("category", "lesson")
        return o
    return {
        "target_date": o.get("date", ""),
        "category": "lesson",
        "weekday": "",
        "slot_start": "",
        "slot_end": "",
        "action": "note_only",
        "new_date": "",
        "new_start": "",
        "new_end": "",
        "note": o.get("note", ""),
    }


def overrides_for_date(overrides, date_iso):
    return [o for o in overrides if o.get("target_date", "") == date_iso]


def slot_is_overridden(overrides_today, slot, category="lesson"):
    """True if a Cancel/Move override on this date, for this schedule
    ("lesson" = base tutoring schedule, or a family-schedule category key
    from FAMILY_SCHEDULE_FIELDS), applies to this slot (matched by
    start/end, or a blanket 'all slots' override left blank). The
    category check keeps e.g. a cancelled 08:00-09:00 lesson from
    accidentally also cancelling an unrelated 08:00-09:00 family-schedule
    entry that happens to share the same time."""
    for o in overrides_today:
        if o.get("action") not in ("cancel", "move"):
            continue
        if o.get("category", "lesson") != category:
            continue
        s_start, s_end = o.get("slot_start", ""), o.get("slot_end", "")
        if (not s_start and not s_end) or (s_start == slot.get("start", "") and s_end == slot.get("end", "")):
            return o
    return None


def date_range_inclusive(start_date, end_date):
    """List of datetime.date from start_date to end_date, inclusive of
    both ends. Used by the Export tab (DEL 07c), which - unlike the Month
    View - works over an arbitrary from/to range rather than a full
    calendar month."""
    if end_date < start_date:
        start_date, end_date = end_date, start_date
    n_days = (end_date - start_date).days
    return [start_date + datetime.timedelta(days=i) for i in range(n_days + 1)]


def generate_month_occurrences(year, month, base_schedule, temp_overrides, personal_schedules,
                                calendar_events, layers):
    """Build {date_iso: [occurrence, ...]} for every day touched by the
    given month's grid (including the padding days from neighboring
    months). See generate_occurrences_for_dates() for what an
    'occurrence' dict looks like and how it's built."""
    weeks = month_grid_weeks(year, month)
    all_dates = [d for week in weeks for d in week]
    return generate_occurrences_for_dates(
        all_dates, base_schedule, temp_overrides, personal_schedules, calendar_events, layers
    )


def generate_occurrences_for_dates(all_dates, base_schedule, temp_overrides, personal_schedules,
                                    calendar_events, layers):
    """Turn the base weekly schedule + family schedules + one-off events +
    structured overrides into {date_iso: [occurrence, ...]} for an
    arbitrary list of dates. This is the shared core behind both the
    Month View grid (which passes a month's padded date grid) and the
    Export tab's agenda builders (DEL 07c, which pass a plain from/to
    range) - keeping one implementation means the two views can never
    drift apart. Each occurrence is a dict with: category, title, start,
    end, note, plus a back-reference to whatever produced it
    ("source_kind" - "event" / "row" / "override" - and "source_key" /
    "source_id"), which is what lets the Week View open the right editor
    when a block is double-clicked (DEL 08d). 'layers' is a dict of
    category -> bool controlling which
    of the recurring layers (the base "lesson" schedule plus every
    user-defined family schedule) are included; one-off calendar events and
    override notes are always shown. Cancel/Move overrides apply to
    whichever recurring schedule they were recorded against (see
    FAMILY_SCHEDULE_FIELDS and each override's "category" field) - not
    just the base tutoring schedule."""
    out = {d.isoformat(): [] for d in all_dates}
    # Overrides have no id of their own - they are addressed by position in
    # temp_overrides (which is also how the overrides list/editor address
    # them), so remember which position each one came from.
    override_pos = {id(o): i for i, o in enumerate(temp_overrides)}

    # --- every weekly-recurring schedule that can carry a Cancel/Move/
    # Note-only override: the base tutoring schedule ("lesson") plus every
    # family schedule the user defined. One shared loop keeps override handling
    # identical everywhere instead of duplicating it per schedule.
    recurring_specs = [("lesson", base_schedule, "start", "end")] + [
        (key, personal_schedules.get(key, []), start_field, end_field)
        for key, (start_field, end_field) in FAMILY_SCHEDULE_FIELDS.items()
    ]
    for category, rows, start_field, end_field in recurring_specs:
        if not layers.get(category, category == "lesson"):
            continue
        cat_label = CATEGORY_STYLES.get(category, (category, "", ""))[0]
        # "Lesson" keeps the original unprefixed wording (no behavior
        # change for existing users/exports); family schedules get a
        # "<Schedule name> " prefix so a cancelled/moved chip shows
        # *which* schedule it belongs to (note: labels like "Son: bus"
        # already contain a colon, so the prefix itself doesn't add one).
        prefix = "" if category == "lesson" else f"{cat_label} "
        for d in all_dates:
            iso = d.isoformat()
            weekday = WEEKDAYS[d.weekday()]
            todays_overrides = overrides_for_date(temp_overrides, iso)
            for row in rows:
                if row.get("weekday") != weekday:
                    continue
                slot = {"start": row.get(start_field, ""), "end": row.get(end_field, "")}
                ov = slot_is_overridden(todays_overrides, slot, category)
                # Cancelled/moved-away chips point at the override that
                # suppressed the slot; a normal one points at the row.
                ov_ref = ({"source_kind": "override", "source_id": override_pos.get(id(ov), -1)}
                          if ov else {})
                if ov and ov.get("action") == "cancel":
                    out[iso].append({
                        "category": "cancelled",
                        "title": f"Cancelled: {prefix}{slot['start']}-{slot['end']}",
                        "start": slot["start"], "end": slot["end"],
                        "note": ov.get("note", row.get("note", "")),
                        **ov_ref,
                    })
                elif ov and ov.get("action") == "move":
                    out[iso].append({
                        "category": "cancelled",
                        "title": f"Moved away: {prefix}{slot['start']}-{slot['end']}",
                        "start": slot["start"], "end": slot["end"],
                        "note": ov.get("note", ""),
                        **ov_ref,
                    })
                else:
                    out[iso].append({
                        "category": category,
                        "title": row.get("note") or cat_label,
                        "start": slot["start"], "end": slot["end"],
                        "note": row.get("note", ""),
                        "source_kind": "row", "source_key": category,
                        "source_id": row.get("id", ""),
                    })
        # occurrences that were *moved to* a date inside this grid, for
        # this same schedule
        for o in temp_overrides:
            if o.get("action") != "move" or o.get("category", "lesson") != category:
                continue
            new_iso = o.get("new_date", "")
            if new_iso in out:
                out[new_iso].append({
                    "category": "moved",
                    "title": "Moved lesson" if category == "lesson" else f"Moved: {cat_label}",
                    "start": o.get("new_start", ""), "end": o.get("new_end", ""),
                    "note": o.get("note", ""),
                    "source_kind": "override", "source_id": override_pos.get(id(o), -1),
                })

    # --- note-only overrides (including auto-upgraded legacy entries) -
    # general calendar notes, always shown regardless of which schedule
    # they were filed against or which layers are toggled on.
    for o in temp_overrides:
        if o.get("action") == "note_only" and o.get("target_date", "") in out:
            out[o["target_date"]].append({
                "category": "note_only", "title": "Note", "start": "", "end": "",
                "note": o.get("note", ""),
                "source_kind": "override", "source_id": override_pos.get(id(o), -1),
            })

    # --- one-off manually added calendar events (always shown)
    for ev in calendar_events:
        iso = ev.get("date", "")
        if iso in out:
            out[iso].append({
                "category": "event", "title": ev.get("title", ""),
                "start": ev.get("start", ""), "end": ev.get("end", ""),
                "note": ev.get("note", ""),
                "source_kind": "event", "source_id": ev.get("id", ""),
            })

    for iso in out:
        out[iso].sort(key=lambda o: (o.get("start") or "99:99"))
    return out


def find_missed_reminders(now, events, recurring_instances, alarm_state, window_hours=12):
    """Reminders that came due while TutorCal wasn't running.

    The alarm engine only ever looks *forward*: it skips anything whose
    start time has already passed, because a reminder for something that
    is already underway is not a reminder any more. That is right while
    the program is open - and useless when it isn't, which is most of the
    day. Closing the laptop at 16:00 and opening it at 17:20 used to mean
    the 17:00 lesson simply never said anything.

    So on startup we look back instead: anything with a "Warn before"
    setting that has already started, no more than `window_hours` ago,
    and that never actually got shown (no last_fired, not dismissed).
    Returns [(state key, item, start datetime), ...] oldest first; the
    items are event-shaped dicts either way, so the caller can render
    both kinds the same."""
    out = []
    lead_seconds_for = dict(ALARM_LEAD_CHOICES)
    candidates = [(e.get("id"), e) for e in events]
    candidates += [(i.get("key"), i) for i in recurring_instances]
    for key, item in candidates:
        if not key:
            continue
        if not lead_seconds_for.get(item.get("lead", "None")):
            continue        # no reminder was ever asked for
        dt = event_datetime(item)
        if dt is None or dt > now:
            continue        # still in the future - the normal engine owns it
        if (now - dt).total_seconds() > window_hours * 3600:
            continue        # old news; don't reopen last week
        state = alarm_state.get(key, {})
        if state.get("dismissed") or state.get("last_fired"):
            continue        # it did get shown, and was dealt with
        out.append((key, item, dt))
    out.sort(key=lambda triple: triple[2])
    return out


def generate_recurring_alarm_instances(dates, base_schedule, personal_schedules, temp_overrides):
    """Build a flat list of upcoming Base Schedule / Family Schedule
    occurrences that have a 'Warn before' setting, for the given window
    of dates. This is what lets the alarm engine (DEL 08) treat recurring
    slots the same way it already treats one-off Calendar > List View
    events - each returned dict has "date"/"start"/"title"/"note" fields
    shaped just like a calendar event, so event_datetime(), _fire_alarm()
    and _show_alarm_popup() can all be reused as-is.

    Mirrors the Cancel/Move override handling in
    generate_occurrences_for_dates() above: a Cancelled occurrence is
    dropped entirely (it never alarms), and a Moved occurrence alarms at
    its *new* date/start/end instead of the original slot, still using
    the original row's own lead/repeat settings. Each instance's "key" is
    "<row id>:<the date the occurrence actually falls on>" so the alarm
    engine can track fired/dismissed state per-occurrence - a stable row
    id (see ensure_schedule_ids) plus the date means next week's
    occurrence of the same recurring slot gets its own independent
    state, exactly like a distinct one-off event would."""
    recurring_specs = [("lesson", base_schedule, "start", "end")] + [
        (key, personal_schedules.get(key, []), start_field, end_field)
        for key, (start_field, end_field) in FAMILY_SCHEDULE_FIELDS.items()
    ]
    out = []
    for category, rows, start_field, end_field in recurring_specs:
        cat_label = CATEGORY_STYLES.get(category, (category, "", ""))[0]
        prefix = "" if category == "lesson" else f"{cat_label}: "
        for d in dates:
            iso = d.isoformat()
            weekday = WEEKDAYS[d.weekday()]
            todays_overrides = overrides_for_date(temp_overrides, iso)
            for row in rows:
                if row.get("weekday") != weekday:
                    continue
                if not dict(ALARM_LEAD_CHOICES).get(row.get("lead", "None")):
                    continue  # "Warn before: None" - no alarm configured for this slot
                row_id = row.get("id")
                if not row_id:
                    continue  # shouldn't happen once ensure_schedule_ids() has run at load time
                slot = {"start": row.get(start_field, ""), "end": row.get(end_field, "")}
                ov = slot_is_overridden(todays_overrides, slot, category)
                if ov and ov.get("action") == "cancel":
                    continue  # a cancelled occurrence never alarms
                title = f"{prefix}{row.get('note') or cat_label}"
                if ov and ov.get("action") == "move":
                    new_iso = ov.get("new_date", "")
                    if not safe_parse_date(new_iso):
                        continue  # malformed move override - nothing sensible to alarm for
                    out.append({
                        "key": f"{row_id}:{new_iso}",
                        "title": f"{title} (moved)",
                        "date": new_iso, "start": ov.get("new_start", ""), "end": ov.get("new_end", ""),
                        "lead": row.get("lead", "None"), "repeat": row.get("repeat", "(no repeat)"),
                        "note": row.get("note", ""),
                    })
                else:
                    out.append({
                        "key": f"{row_id}:{iso}",
                        "title": title,
                        "date": iso, "start": slot["start"], "end": slot["end"],
                        "lead": row.get("lead", "None"), "repeat": row.get("repeat", "(no repeat)"),
                        "note": row.get("note", ""),
                    })
    return out


# *************** DEL 07c - EXPORT: AGENDA BUILDING (TEXT / IMAGE / PDF) ***************
# This is TODO #5. All three formats render the *same* underlying agenda -
# generate_occurrences_for_dates() output turned into rows by
# build_agenda_rows() - so Text/Image/PDF never show different content.
# Image needs Pillow, PDF needs fpdf2; both degrade to a clear error
# instead of a crash when the library isn't installed (see the try/except
# imports near the top of the file). Every function below is a plain data
# function with no Tkinter dependency, so it can be unit-tested on its own.

# What the Export tab's range dropdown offers. "This week" / "Next week"
# are the same Monday-to-Sunday week the Week View draws (DEL 08d), which
# is what "send her the week" actually means - "Next 7 days" starts today
# and runs into the middle of the following week instead.
EXPORT_RANGE_CHOICES = ("This week", "Next week", "Next 7 days", "Next 30 days",
                        "This month", "Custom range")

# NOTE: EXPORT_LAYER_KEYS is no longer a fixed tuple here - it is rebuilt
# from the user's own schedule list by apply_schedule_defs() (DEL 00/08b),
# so an added or renamed schedule shows up as an Include checkbox by itself.


def build_agenda_rows(dates, occurrences_by_date):
    """[(date, weekday_name, [occurrence, ...]), ...] for the given dates,
    in order - the shared shape all three export formats render from."""
    return [(d, WEEKDAYS[d.weekday()], occurrences_by_date.get(d.isoformat(), [])) for d in dates]


def format_occurrence_line(occ):
    """One occurrence as a single line of plain text, e.g.
    '09:00-10:00  [Lesson] Algebra review - bring the practice sheet'."""
    label = CATEGORY_STYLES.get(occ.get("category"), (occ.get("category", "") or "Note", "", ""))[0]
    start, end = occ.get("start", ""), occ.get("end", "")
    time_part = f"{start}-{end}" if (start or end) else "--:--"
    title = occ.get("title") or label
    if title == label or title.lower().startswith(label.lower()):
        line = f"{time_part}  {title}"      # title already carries the category info - no need to repeat it
    else:
        line = f"{time_part}  [{label}] {title}"
    note = occ.get("note", "")
    if note and note != title:
        line += f" - {note}"
    return line


def build_agenda_text(dates, occurrences_by_date, generated_at=None):
    """Plain-text agenda grouped by day - easy to paste straight into a
    message. See TODO #5: 'Export as Text'."""
    generated_at = generated_at or datetime.datetime.now()
    lines = [f"{APP_NAME} - Agenda"]
    if dates:
        lines.append(f"{dates[0].isoformat()} to {dates[-1].isoformat()}")
    lines.append(f"Generated {generated_at.strftime('%Y-%m-%d %H:%M')}")
    lines.append("")
    for d, weekday, occs in build_agenda_rows(dates, occurrences_by_date):
        header = f"{weekday}, {d.strftime('%d %b %Y')}"
        lines.append(header)
        lines.append("-" * max(len(header), 20))
        if occs:
            for occ in occs:
                lines.append(f"  {format_occurrence_line(occ)}")
        else:
            lines.append("  (no entries)")
        lines.append("")
    return "\n".join(lines).rstrip("\n") + "\n"


# ---- Hours summary ---------------------------------------------------
# "How many hours did I actually teach Anna in September?" was a question
# the program could not answer, even though it already knew: the agenda
# for any range is built from the same occurrence data everything else
# uses, cancellations and moves included. This just adds them up.
#
# Grouping is (schedule, title) - for the lesson schedule the title is
# the student's name as she typed it, which is exactly the unit an
# invoice is written in. Cancelled slots and plain notes are skipped: a
# cancelled lesson is precisely the one that must not be counted.

def summarize_hours(dates, occurrences_by_date):
    """Returns (rows, totals):
      rows   = [(schedule label, title, occurrences, minutes), ...]
               busiest first
      totals = {schedule label: (occurrences, minutes)} with the key
               "" holding the grand total.
    Untimed entries count as an occurrence with zero minutes rather than
    being dropped - they did happen, they just have no length."""
    tally = {}
    for _d, _weekday, occs in build_agenda_rows(dates, occurrences_by_date):
        for occ in occs:
            category = occ.get("category")
            if category in ("cancelled", "note_only"):
                continue
            label = CATEGORY_STYLES.get(category, (category or "Other", "", ""))[0]
            title = (occ.get("title") or label).strip()
            span = occurrence_span(occ)
            minutes = (span[1] - span[0]) if span else 0
            count, total = tally.get((label, title), (0, 0))
            tally[(label, title)] = (count + 1, total + minutes)

    rows = [(label, title, count, minutes)
            for (label, title), (count, minutes) in tally.items()]
    rows.sort(key=lambda r: (-r[3], -r[2], r[0], r[1]))

    totals = {}
    for label, _title, count, minutes in rows:
        had_count, had_minutes = totals.get(label, (0, 0))
        totals[label] = (had_count + count, had_minutes + minutes)
    totals[""] = (sum(r[2] for r in rows), sum(r[3] for r in rows))
    return rows, totals


def format_hours(minutes):
    """90 -> '1 h 30 min'. Whole hours drop the minutes part."""
    hours, rest = divmod(int(minutes), 60)
    if hours and rest:
        return f"{hours} h {rest} min"
    if hours:
        return f"{hours} h"
    return f"{rest} min"


def build_hours_summary_text(dates, occurrences_by_date):
    """The same summary as plain text, ready to paste into an invoice or
    a message."""
    rows, totals = summarize_hours(dates, occurrences_by_date)
    lines = [f"{APP_NAME} - Hours summary"]
    if dates:
        lines.append(f"{dates[0].isoformat()} to {dates[-1].isoformat()}")
    lines.append("")
    if not rows:
        lines.append("(nothing in this range)")
        return "\n".join(lines) + "\n"
    current_label = None
    for label, title, count, minutes in sorted(rows, key=lambda r: (r[0], -r[3], r[1])):
        if label != current_label:
            current_label = label
            count_all, minutes_all = totals[label]
            lines.append(f"{label} - {count_all} in total, {format_hours(minutes_all)}")
        times = "1 time" if count == 1 else f"{count} times"
        lines.append(f"    {title}: {times}, {format_hours(minutes)}")
    count_all, minutes_all = totals[""]
    lines.append("")
    lines.append(f"TOTAL: {count_all} entries, {format_hours(minutes_all)}")
    return "\n".join(lines) + "\n"


# ---- Calendar file export (.ics) -------------------------------------
# The Text/Image/PDF exports are all things to *look at*. This one is the
# thing to *import*: an iCalendar file that Google Calendar, Outlook, the
# iPhone/Android calendar and Thunderbird all understand, so the week can
# live in her phone's own calendar - with its own reminders - instead of
# only inside TutorCal. Same agenda data as the other three formats.
#
# Times are written "floating" (no timezone, no Z suffix): the lesson at
# 17:00 is at 17:00 wherever the file is opened, which is exactly right
# for a local weekly schedule and avoids shipping a whole VTIMEZONE
# definition (and avoids the classic "everything moved an hour" bug when
# the DST rules of the exporting and importing machines disagree).

ICS_PRODID = f"-//Issu//{APP_NAME}//EN"


def _ics_escape(text):
    """RFC 5545 text escaping: backslash, semicolon and comma are special,
    and a real newline has to travel as a literal '\\n'."""
    return (str(text or "")
            .replace("\\", "\\\\")
            .replace(";", "\\;")
            .replace(",", "\\,")
            .replace("\r\n", "\\n")
            .replace("\n", "\\n")
            .replace("\r", "\\n"))


def _ics_fold(line):
    """Content lines must not exceed 75 octets; longer ones continue on
    the next line starting with a single space. Folding is done on UTF-8
    byte boundaries, so an 'ä' is never split in half."""
    raw = line.encode("utf-8")
    if len(raw) <= 75:
        return line
    chunks, start = [], 0
    limit = 75
    while start < len(raw):
        end = min(start + limit, len(raw))
        while end < len(raw) and (raw[end] & 0xC0) == 0x80:    # don't cut inside a character
            end -= 1
        chunks.append(raw[start:end].decode("utf-8"))
        start = end
        limit = 74      # continuation lines carry a leading space
    return "\r\n ".join(chunks)


def _ics_uid(date_iso, start, title):
    """Stable per-occurrence id, so re-importing an updated export
    replaces the entry in the phone's calendar instead of adding a second
    copy of the same lesson. uuid5 = a plain hash of the text, identical
    on every run (unlike Python's own hash())."""
    return f"{uuid.uuid5(uuid.NAMESPACE_URL, f'tutorcal:{date_iso}:{start}:{title}')}@tutorcal"


def build_agenda_ics(dates, occurrences_by_date, generated_at=None):
    """The same agenda the other exports render, as an iCalendar (.ics)
    file. Cancelled/moved-away markers are left out - they are notes
    about the TutorCal schedule, not appointments, and the moved lesson
    itself is already exported at its new time."""
    generated_at = generated_at or datetime.datetime.now()
    stamp = generated_at.strftime("%Y%m%dT%H%M%S")
    out = ["BEGIN:VCALENDAR", "VERSION:2.0", f"PRODID:{ICS_PRODID}",
           "CALSCALE:GREGORIAN", "METHOD:PUBLISH", f"X-WR-CALNAME:{APP_NAME}"]
    for d, _weekday, occs in build_agenda_rows(dates, occurrences_by_date):
        for occ in occs:
            if occ.get("category") == "cancelled":
                continue
            label = CATEGORY_STYLES.get(occ.get("category"), ("", "", ""))[0]
            title = occ.get("title") or label or "Entry"
            if label and label not in title:
                title = f"{label}: {title}"
            span = occurrence_span(occ)
            out.append("BEGIN:VEVENT")
            out.append(f"UID:{_ics_uid(d.isoformat(), occ.get('start', ''), title)}")
            out.append(f"DTSTAMP:{stamp}")
            if span is None:
                # No usable time - an all-day entry, which in iCalendar is
                # a DATE range whose end is the *next* day (exclusive).
                out.append(f"DTSTART;VALUE=DATE:{d.strftime('%Y%m%d')}")
                out.append(f"DTEND;VALUE=DATE:{(d + datetime.timedelta(days=1)).strftime('%Y%m%d')}")
            else:
                start_min, end_min = span
                start_dt = datetime.datetime.combine(d, datetime.time()) + datetime.timedelta(minutes=start_min)
                end_dt = datetime.datetime.combine(d, datetime.time()) + datetime.timedelta(minutes=end_min)
                out.append(f"DTSTART:{start_dt.strftime('%Y%m%dT%H%M%S')}")
                out.append(f"DTEND:{end_dt.strftime('%Y%m%dT%H%M%S')}")
            out.append(f"SUMMARY:{_ics_escape(title)}")
            note = occ.get("note", "")
            if note and note != occ.get("title"):
                out.append(f"DESCRIPTION:{_ics_escape(note)}")
            out.append("END:VEVENT")
    out.append("END:VCALENDAR")
    return "\r\n".join(_ics_fold(line) for line in out) + "\r\n"


def _hex_to_rgb(hex_color):
    hex_color = (hex_color or "#000000").lstrip("#")
    return tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4))


def _wrap_pil_text(measurer, text, font, max_width):
    """Word-wrap text to max_width using the given font's real metrics
    (measurer is any ImageDraw.Draw instance - only used to measure, not
    to draw). Falls back to returning the text unsplit if a single word
    already overflows max_width, rather than looping forever."""
    words = text.split(" ")
    lines, cur = [], ""
    for w in words:
        trial = f"{cur} {w}".strip()
        if not cur or measurer.textlength(trial, font=font) <= max_width:
            cur = trial
        else:
            lines.append(cur)
            cur = w
    if cur:
        lines.append(cur)
    return lines or [""]


def _find_export_font(size, bold=False):
    """Best-effort TTF lookup for image/PDF export: Segoe UI first (matches
    the app's on-screen FONT_MAIN/FONT_HEADER on Windows), then common
    cross-platform fallbacks, then Pillow's built-in bitmap font so this
    never raises even on a machine with no TrueType fonts findable by name."""
    if ImageFont is None:
        return None
    names = (["segoeuib.ttf", "seguisb.ttf"] if bold else ["segoeui.ttf"]) + [
        "Arial Bold.ttf" if bold else "Arial.ttf",
        "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf",
        "Helvetica.ttf",
    ]
    for name in names:
        try:
            return ImageFont.truetype(name, size)
        except Exception:
            continue
    try:
        return ImageFont.load_default(size=size)   # Pillow >= 10.1
    except Exception:
        return ImageFont.load_default()


def build_agenda_image(dates, occurrences_by_date, generated_at=None, width=760):
    """Render the merged agenda to a Pillow Image, one column, sized for a
    phone screen, styled with the app's own colors/fonts. See TODO #5:
    'Export as Image'. Raises RuntimeError if Pillow isn't installed."""
    if Image is None:
        raise RuntimeError("Pillow is not installed. Install it with:  pip install pillow")

    generated_at = generated_at or datetime.datetime.now()
    rows = build_agenda_rows(dates, occurrences_by_date)

    font_title = _find_export_font(24, bold=True)
    font_sub = _find_export_font(13)
    font_day = _find_export_font(17, bold=True)
    font_entry = _find_export_font(14)

    pad = 20
    line_h = 23
    day_gap = 14
    header_h = 66
    entry_indent = pad + 30
    max_text_width = width - entry_indent - pad

    measurer = ImageDraw.Draw(Image.new("RGB", (10, 10)))
    prepared = []
    total_h = header_h + pad
    for d, weekday, occs in rows:
        entries = []
        if occs:
            for occ in occs:
                wrapped = _wrap_pil_text(measurer, format_occurrence_line(occ), font_entry, max_text_width)
                entries.extend((i == 0, w) for i, w in enumerate(wrapped))
        else:
            entries = [(True, "(no entries)")]
        prepared.append((d, weekday, occs, entries))
        total_h += line_h + 6 + len(entries) * line_h + day_gap
    total_h += pad

    img = Image.new("RGB", (width, total_h), COLOR_BG_PANEL)
    draw = ImageDraw.Draw(img)

    draw.rectangle([0, 0, width, header_h], fill=COLOR_BG_HEADER)
    draw.text((pad, 11), f"{APP_NAME} - Agenda", font=font_title, fill=COLOR_TEXT_ON_HEADER)
    range_txt = f"{dates[0].isoformat()} to {dates[-1].isoformat()}" if dates else "(no dates)"
    draw.text((pad, 42), f"{range_txt}   |   generated {generated_at.strftime('%Y-%m-%d %H:%M')}",
              font=font_sub, fill=COLOR_TEXT_ON_HEADER)

    cy = header_h + pad
    for d, weekday, occs, entries in prepared:
        day_color = CATEGORY_STYLES.get(occs[0]["category"], (None, COLOR_SEPARATOR, None))[1] if occs else COLOR_SEPARATOR
        draw.rectangle([pad, cy + 2, pad + 6, cy + line_h - 3], fill=day_color)
        draw.text((pad + 14, cy), f"{weekday}, {d.strftime('%d %b %Y')}", font=font_day, fill=COLOR_BG_HEADER)
        cy += line_h + 6

        occ_i = -1
        for is_first, text in entries:
            if is_first and occs:
                occ_i += 1
                dot_color = CATEGORY_STYLES.get(occs[occ_i]["category"], ("", COLOR_SEPARATOR, ""))[1]
                draw.ellipse([pad + 14, cy + 7, pad + 21, cy + 14], fill=dot_color)
            draw.text((entry_indent, cy), text, font=font_entry,
                      fill=COLOR_TEXT_DIM if not occs else COLOR_TEXT_MAIN)
            cy += line_h
        cy += day_gap

    draw.line([0, total_h - 1, width, total_h - 1], fill=COLOR_SEPARATOR)
    return img


def build_agenda_pdf(dates, occurrences_by_date, generated_at=None):
    """Render the merged agenda to an in-memory fpdf2 document (same
    content as the text export, plus category-colored bullets). Caller
    does pdf.output(path) to write it. See TODO #5: 'Export as PDF'.
    Raises RuntimeError if fpdf2 isn't installed."""
    if FPDF is None:
        raise RuntimeError("fpdf2 is not installed. Install it with:  pip install fpdf2")

    generated_at = generated_at or datetime.datetime.now()
    rows = build_agenda_rows(dates, occurrences_by_date)

    pdf = FPDF(format="A4", unit="mm")
    pdf.set_auto_page_break(auto=True, margin=15)
    pdf.set_margins(18, 16, 18)
    pdf.add_page()

    pdf.set_text_color(*_hex_to_rgb(COLOR_BG_HEADER))
    pdf.set_font("Helvetica", "B", 18)
    pdf.cell(0, 10, f"{APP_NAME} - Agenda", new_x="LMARGIN", new_y="NEXT")

    pdf.set_text_color(*_hex_to_rgb(COLOR_TEXT_DIM))
    pdf.set_font("Helvetica", "", 10)
    range_txt = f"{dates[0].isoformat()} to {dates[-1].isoformat()}" if dates else "(no dates)"
    pdf.cell(0, 6, f"{range_txt}   |   generated {generated_at.strftime('%Y-%m-%d %H:%M')}",
             new_x="LMARGIN", new_y="NEXT")
    pdf.ln(3)

    for d, weekday, occs in rows:
        pdf.set_text_color(*_hex_to_rgb(COLOR_BG_HEADER))
        pdf.set_font("Helvetica", "B", 12)
        pdf.cell(0, 8, f"{weekday}, {d.strftime('%d %b %Y')}", new_x="LMARGIN", new_y="NEXT")
        pdf.set_draw_color(*_hex_to_rgb(COLOR_SEPARATOR))
        pdf.line(pdf.get_x(), pdf.get_y(), pdf.get_x() + 174, pdf.get_y())
        pdf.ln(2)

        pdf.set_font("Helvetica", "", 10)
        if occs:
            for occ in occs:
                _label, chip_bg, _chip_fg = CATEGORY_STYLES.get(
                    occ.get("category"), (occ.get("category", "") or "Note", COLOR_TEXT_DIM, ""))
                pdf.set_fill_color(*_hex_to_rgb(chip_bg))
                pdf.rect(pdf.get_x(), pdf.get_y() + 1.5, 3, 3, style="F")
                pdf.set_x(pdf.get_x() + 6)
                pdf.set_text_color(*_hex_to_rgb(COLOR_TEXT_MAIN))
                avail_w = pdf.w - pdf.r_margin - pdf.get_x()
                pdf.multi_cell(avail_w, 6, format_occurrence_line(occ), new_x="LMARGIN", new_y="NEXT")
        else:
            pdf.set_text_color(*_hex_to_rgb(COLOR_TEXT_DIM))
            pdf.cell(0, 6, "(no entries)", new_x="LMARGIN", new_y="NEXT")
        pdf.ln(3)

    return pdf


def open_in_file_manager(path):
    """Reveal an exported file (or its folder) in the OS's default file
    manager - best-effort, silently does nothing if the platform call
    fails (e.g. running headless). Windows/macOS/Linux all handled since
    TutorCal is meant to be portable even though winsound/ctypes bits
    elsewhere are Windows-only."""
    try:
        system = platform.system()
        if system == "Windows":
            open_path(path)   # noqa: S606 - opens Explorer or the file's default app
        elif system == "Darwin":
            subprocess.Popen(["open", path])
        else:
            subprocess.Popen(["xdg-open", path])
    except Exception:
        pass


# *************** DEL 07d - SHARE: DIRECT-TO-PHONE SEND (TODO #7) ***************
# TODO #7 update: sending the *text* agenda straight to WhatsApp or a new
# email draft now works with no extra dependencies, using each app's own
# official URL scheme (WhatsApp's "click-to-chat" wa.me link, and the
# standard mailto: link) rather than needing an API key or an installed
# SDK. What still isn't possible from plain, cross-platform Python is
# auto-attaching a *file* to that message with a recipient already picked -
# WhatsApp and mail clients only accept an attachment through their own
# share sheet, drag-and-drop, or a clipboard paste, not through a URL. The
# saved Image/PNG gets a real answer for this via the clipboard-paste route
# (see DEL 07e, right below); the PDF still doesn't, since no app accepts a
# pasted PDF as attachment data - so for that one format,
# _export_finish() below still just reveals the saved file (via
# open_in_file_manager, DEL 07c) for the user to drag in themselves. A
# native share-sheet integration (the Windows DataTransferManager, or
# macOS's NSSharingService) would remove that last manual step, but needs
# a platform-specific package (pywin32/winrt, PyObjC) this skeleton
# doesn't depend on yet.

SHARE_TEXT_SAFE_CHARS = 1800   # conservative common denominator so the
                                # generated wa.me / mailto: link doesn't get
                                # silently cut off by the OS, the browser,
                                # or WhatsApp/the mail client itself


def whatsapp_click_to_chat_url(text):
    """Build a WhatsApp 'click-to-chat' link (https://wa.me) with the given
    text pre-filled in the compose box and no phone number, so opening it
    lets the user pick who to send it to from their own WhatsApp chat
    list. This is WhatsApp's own official link format - no API key needed
    - and works with either WhatsApp Desktop (if it's registered to
    handle the link) or WhatsApp Web in the default browser."""
    return "https://wa.me/?text=" + urllib.parse.quote(text, safe="")


def mailto_url(subject, body):
    """Build a mailto: link that opens the OS default email client with
    the subject/body pre-filled, ready to address and send."""
    return "mailto:?subject={}&body={}".format(
        urllib.parse.quote(subject, safe=""),
        urllib.parse.quote(body, safe=""),
    )


def contact_link_for(app_name, value):
    """Work out how to actually reach a contact from the two free-ish
    fields she filled in - the app she picked ("WhatsApp", "SMS", ...)
    and the value (a number, an address, a link).

    Returns (kind, payload):
        "url"        -> open payload with the OS default handler
        "whatsapp"   -> a wa.me link; the caller warns first if the number
                        wasn't in international form (payload is the link,
                        built from the digits as typed)
        "clipboard"  -> nothing sensible to open; copy payload instead
    Kept as a plain function with no Tkinter in it so the mapping can be
    tested on its own."""
    app_name = (app_name or "").strip().lower()
    value = (value or "").strip()
    if not value:
        return "clipboard", ""

    if value.lower().startswith(("http://", "https://")):
        return "url", value
    if "@" in value and " " not in value:
        return "url", "mailto:" + value

    digits = "".join(ch for ch in value if ch.isdigit() or ch == "+")
    international = digits.startswith("+") or digits.startswith("00")
    bare = digits.lstrip("+").lstrip("0") if international else digits.lstrip("+")

    if "whatsapp" in app_name and bare:
        return ("whatsapp" if not international else "url"), "https://wa.me/" + bare
    if "sms" in app_name or "text" in app_name:
        return "url", "sms:" + digits
    if any(word in app_name for word in ("phone", "tel", "mobile", "call")):
        return "url", "tel:" + digits
    if any(word in app_name for word in ("mail", "e-post", "epost")):
        return "url", "mailto:" + value
    # Signal, Telegram, Messenger, Instagram, ... - no reliable link
    # format from a bare number/handle, so hand it over via the clipboard.
    return "clipboard", value


def confirm_long_share_text(root, text, channel_label):
    """WhatsApp/mailto links are plain URLs under the hood, so a very long
    agenda can get silently truncated by the OS/browser/app before it
    ever reaches the compose box. If the text fits within
    SHARE_TEXT_SAFE_CHARS, return it unchanged. Otherwise ask the user
    whether to still try (best-effort - the tail of a long agenda may not
    make it through), or cancel and pick a shorter date range / fewer
    layers instead. Returns the text to send, or None if the user
    cancelled."""
    if len(text) <= SHARE_TEXT_SAFE_CHARS:
        return text
    proceed = messagebox.askyesno(
        "Agenda is long",
        f"This agenda is {len(text)} characters - longer than {channel_label} "
        f"reliably carries in one pre-filled message, so the end of it may "
        f"get cut off.\n\nSend it anyway, or press No and pick a shorter "
        f"date range (or fewer layers, or one of the file export buttons) "
        f"instead?",
        parent=root,
    )
    return text if proceed else None


def share_text_via_whatsapp(root, text):
    """Resolve a possibly-too-long agenda via confirm_long_share_text(),
    then open it as a WhatsApp click-to-chat link. Returns False without
    opening anything if the user cancelled at the length-warning step."""
    text = confirm_long_share_text(root, text, "WhatsApp")
    if text is None:
        return False
    open_url(whatsapp_click_to_chat_url(text))
    return True


def share_text_via_email(root, subject, text):
    """Same idea as share_text_via_whatsapp() but opens a mailto: draft
    instead."""
    text = confirm_long_share_text(root, text, "an email link")
    if text is None:
        return False
    open_url(mailto_url(subject, text))
    return True


# *************** DEL 07e - COPY EXPORTED IMAGE TO CLIPBOARD (TODO #7 cont.) ***************
# The other half of TODO #7: the wa.me/mailto links above can carry text,
# but not a file - WhatsApp and mail clients only accept an attachment
# through their own share sheet or drag-and-drop. A full native share-sheet
# integration (Windows DataTransferManager, macOS NSSharingService) needs a
# platform-specific package this skeleton doesn't depend on. Short of that,
# though, there's a real, dependency-free middle ground: WhatsApp Desktop,
# Telegram, Signal, and most email clients (Gmail/Outlook web included) all
# accept a plain Ctrl+V/Cmd+V paste of an *image* straight from the
# clipboard - no share sheet needed. So after "Export as Image" saves the
# PNG, it's also pushed onto the OS image clipboard via each platform's own
# built-in tool (PowerShell's System.Windows.Forms on Windows, osascript on
# macOS, xclip/wl-copy on Linux) - still zero new pip dependencies, same
# philosophy as open_in_file_manager()/send_os_notification() above. If
# none of those tools are available, this just quietly does nothing and
# the old "drag the saved file in yourself" flow still works exactly as
# before. A PDF can't be pasted the same way (no app treats a PDF as
# clipboard image data), so that format still only offers the file-reveal
# path.

def copy_image_to_clipboard(path):
    """Best-effort: push the PNG at `path` onto the OS clipboard as image
    data (not as a file path) so it can be pasted directly into a chat or
    email compose box. Returns True if it's confident the copy worked,
    False otherwise - always safe to call, never raises."""
    try:
        system = platform.system()
        if system == "Windows":
            # System.Windows.Forms.Clipboard is built into every Windows
            # install - no extra package, just shelling out to the
            # PowerShell that ships with the OS.
            ps_script = (
                "Add-Type -AssemblyName System.Windows.Forms,System.Drawing; "
                "[System.Windows.Forms.Clipboard]::SetImage("
                "[System.Drawing.Image]::FromFile('" + path.replace("'", "''") + "'))"
            )
            result = subprocess.run(
                ["powershell", "-NoProfile", "-Command", ps_script],
                timeout=10, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
            )
            return result.returncode == 0
        elif system == "Darwin":
            script = (
                'set the clipboard to (read (POSIX file "' + path.replace('"', '\\"') +
                '") as «class PNGf»)'
            )
            result = subprocess.run(["osascript", "-e", script], timeout=10,
                                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            return result.returncode == 0
        else:
            # Linux: try the X11 tool first, then the Wayland one. Neither
            # ships with the OS by default, so this is the one path most
            # likely to have nothing installed - that's fine, it degrades
            # to the existing file-reveal flow.
            for cmd in (["xclip", "-selection", "clipboard", "-t", "image/png", "-i", path],
                        ["wl-copy", "--type", "image/png"]):
                try:
                    if cmd[0] == "wl-copy":
                        with open(path, "rb") as f:
                            result = subprocess.run(cmd, stdin=f, timeout=10,
                                                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                    else:
                        result = subprocess.run(cmd, timeout=10,
                                                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                    if result.returncode == 0:
                        return True
                except FileNotFoundError:
                    continue
            return False
    except Exception:
        return False


# *************** DEL 07f - OS-LEVEL NOTIFICATIONS (TODO #2) ***************
# Best-effort *native* OS notification, fired alongside the existing
# in-app popup (_show_alarm_popup) so a reminder still gets noticed when
# TutorCal is minimized or sitting behind other windows - not just while
# it's the focused, visible window. This is purely additive: the in-app
# popup + sound keep working exactly as before regardless of whether the
# OS notification succeeds, so a platform quirk here can never cause a
# reminder to go silently missing.
#
#   Windows: a real Action Center toast via the classic Shell_NotifyIcon
#   tray API (NIF_INFO) - ctypes only, no extra package. This shows as a
#   modern toast (not an old XP-style balloon) on Windows 10/11 because
#   apply_app_user_model_id() already registered our AppUserModelID
#   before Tk() was created (DEL 05) - Windows uses that ID to decide the
#   notification is "from" this app rather than a generic one. A tiny
#   invisible tray icon is added just long enough to carry the message,
#   then removed a few seconds later.
#   macOS: shells out to `osascript -e 'display notification ...'` -
#   built into every Mac, nothing to install.
#   Linux: shells out to `notify-send` if it's on PATH (present on
#   GNOME/KDE/most desktop distros); does nothing if it isn't installed.
#
# Any failure anywhere in here (missing notify-send, no display server,
# sandboxed/locked-down environment, odd ctypes error, ...) is swallowed
# and just means no OS toast that time - never a crash, and never a
# reason for the in-app popup to not appear.

class _WinNotifyIconData(ctypes.Structure):
    """Mirrors the Win32 NOTIFYICONDATAW struct (just the fields this
    app actually uses) - only ever instantiated on Windows."""
    _fields_ = [
        ("cbSize", ctypes.c_ulong),
        ("hWnd", ctypes.c_void_p),
        ("uID", ctypes.c_uint),
        ("uFlags", ctypes.c_uint),
        ("uCallbackMessage", ctypes.c_uint),
        ("hIcon", ctypes.c_void_p),
        ("szTip", ctypes.c_wchar * 128),
        ("dwState", ctypes.c_ulong),
        ("dwStateMask", ctypes.c_ulong),
        ("szInfo", ctypes.c_wchar * 256),
        ("uTimeoutOrVersion", ctypes.c_uint),
        ("szInfoTitle", ctypes.c_wchar * 64),
        ("dwInfoFlags", ctypes.c_ulong),
    ]


_WIN_TRAY_ICON_ID = 7371   # arbitrary constant, just needs to stay fixed

# The one tray icon this program ever owns, plus a token identifying the
# toast currently using it. Two reminders inside the same few seconds used
# to fight over it: the first one's timer deleted the icon out from under
# the second one's toast, and closing the app in between left the icon
# stranded in the notification area until Explorer got around to noticing.
_win_tray = {"data": None, "token": 0}


def remove_tray_icon():
    """Take the notification-area icon away again. Safe to call at any
    time, on any platform, however many times - it is a no-op unless an
    icon is actually registered right now."""
    data = _win_tray.get("data")
    _win_tray["data"] = None
    if data is None or platform.system() != "Windows":
        return False
    try:
        ctypes.windll.shell32.Shell_NotifyIconW(2, ctypes.byref(data))   # NIM_DELETE
        return True
    except Exception:
        return False


def _load_tray_icon_handle():
    """The app's own .ico at 16x16 if it's there, else the generic system
    application icon. restype/argtypes are set explicitly: an icon HANDLE
    is pointer-sized, and ctypes' default int return would chop the top
    half off it on 64-bit Python."""
    IMAGE_ICON, LR_LOADFROMFILE, IDI_APPLICATION = 1, 0x0010, 32512
    user32 = ctypes.windll.user32
    user32.LoadImageW.restype = ctypes.c_void_p
    user32.LoadImageW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_uint,
                                  ctypes.c_int, ctypes.c_int, ctypes.c_uint]
    user32.LoadIconW.restype = ctypes.c_void_p
    user32.LoadIconW.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
    handle = None
    if os.path.isfile(ICON_PATH):
        try:
            handle = user32.LoadImageW(None, ICON_PATH, IMAGE_ICON, 16, 16, LR_LOADFROMFILE)
        except Exception:
            handle = None
    if not handle:
        handle = user32.LoadIconW(None, ctypes.c_void_p(IDI_APPLICATION))
    return handle


def _send_windows_toast(root, title, message):
    if platform.system() != "Windows":
        return False
    try:
        NIM_ADD, NIM_MODIFY = 0, 1
        NIF_ICON, NIF_MESSAGE, NIF_TIP, NIF_INFO = 0x2, 0x1, 0x4, 0x10
        NIIF_INFO = 0x1
        WM_USER = 0x0400

        shell32 = ctypes.windll.shell32
        data = _win_tray.get("data")
        first_time = data is None
        if first_time:
            data = _WinNotifyIconData()
            data.cbSize = ctypes.sizeof(_WinNotifyIconData)
            data.hWnd = root.winfo_id()
            data.uID = _WIN_TRAY_ICON_ID
            data.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO
            data.uCallbackMessage = WM_USER + 20
            data.hIcon = _load_tray_icon_handle()
            data.szTip = APP_NAME[:127]
            data.dwInfoFlags = NIIF_INFO

        data.szInfo = message[:255]
        data.szInfoTitle = title[:63]

        if first_time:
            shell32.Shell_NotifyIconW(NIM_ADD, ctypes.byref(data))
        shell32.Shell_NotifyIconW(NIM_MODIFY, ctypes.byref(data))   # this is what raises the toast
        _win_tray["data"] = data
        _win_tray["token"] += 1
        token = _win_tray["token"]

        def _cleanup():
            # Only tidy up if no *newer* toast has taken the icon over in
            # the meantime - otherwise a second reminder arriving inside
            # these eight seconds would have its toast pulled away.
            if _win_tray.get("token") == token:
                remove_tray_icon()

        root.after(8000, _cleanup)   # the icon only needs to live long enough to hand off the toast
        return True
    except Exception:
        return False


def _send_mac_notification(title, message):
    if platform.system() != "Darwin":
        return False
    try:
        def _esc(s):
            return s.replace("\\", "\\\\").replace('"', '\\"')
        script = f'display notification "{_esc(message)}" with title "{_esc(title)}"'
        subprocess.run(["osascript", "-e", script], timeout=5,
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return True
    except Exception:
        return False


def _send_linux_notification(title, message):
    if platform.system() != "Linux":
        return False
    try:
        subprocess.run(["notify-send", title, message], timeout=5,
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return True
    except Exception:
        return False


def send_os_notification(root, title, message):
    """Best-effort native OS notification for the given platform. Always
    safe to call - returns False (and does nothing else) if the platform
    isn't one of the three handled above, or if the underlying OS call
    fails for any reason."""
    try:
        system = platform.system()
        if system == "Windows":
            return _send_windows_toast(root, title, message)
        elif system == "Darwin":
            return _send_mac_notification(title, message)
        elif system == "Linux":
            return _send_linux_notification(title, message)
    except Exception:
        pass
    return False


# *************** DEL 10 - PHONE PAGE (sends the schedule to the server so the phone can read it) ***************
# What this does: TutorCal builds the finished days (fixed weekly schedule + every temporary change + one-off entries, merged by
# generate_occurrences_for_dates - the SAME function the Month/Week/Day Views use, so the phone can never disagree with the PC), plus the
# fixed weekly rows and the upcoming temporary changes, and PUTs that one JSON to the relay (TutorCalRelay\tutorcal_relay.py, page at
# https://<name>/cal/). The phone page only READS it. Contacts are never sent.
# ToDo: editing from the phone is NOT built, on purpose (Lars: "det räcker att man kan ändra från dator"). Phone alarms would need
# a native app - not built either.
PHONE_DAYS_BACK = 14
PHONE_DAYS_AHEAD = 150
PHONE_CHECK_MS = 20000            # how often the program looks whether the schedule changed
PHONE_HEARTBEAT_S = 12 * 3600     # send again at least this often while TutorCal is open (the page shows how old the copy is)
PHONE_RETRY_S = 300               # wait this long after a failed automatic send
PHONE_TIMEOUT_S = 15


def parse_phone_code(text):
    """'TCAL1:<base64 of {"u": address, "s": key}>' -> (address ending in '/', key), or None when it is not such a code."""
    text = (text or "").strip()
    if not text.startswith("TCAL1:"):
        return None
    try:
        obj = json.loads(base64.b64decode(text[6:].encode("ascii"), validate=True).decode("utf-8"))
        url, key = str(obj["u"]).strip(), str(obj["s"]).strip()
    except Exception:
        return None
    if not url.lower().startswith(("https://", "http://127.0.0.1", "http://localhost")) or not key or len(key) > 120:
        return None
    if not url.endswith("/"):
        url += "/"
    return url, key


def phone_link_for(code):
    """The link that opens the phone page already connected (the key sits after the #, which is never sent to the server)."""
    parsed = parse_phone_code(code)
    if not parsed:
        return ""
    return parsed[0] + "#k=" + urllib.parse.quote(parsed[1], safe="")


def build_phone_payload(today, base_schedule, temp_overrides, personal_schedules, calendar_events, now=None):
    """The one JSON the phone page reads (format version 1, see TutorCalRelay\\www\\app.js)."""
    dates = [today + datetime.timedelta(days=i) for i in range(-PHONE_DAYS_BACK, PHONE_DAYS_AHEAD + 1)]
    layers = {"lesson": True}
    layers.update({key: True for key in FAMILY_SCHEDULE_FIELDS})
    occ = generate_occurrences_for_dates(dates, base_schedule, temp_overrides, personal_schedules, calendar_events, layers)
    days = {}
    for iso_day, rows in occ.items():
        out = []
        for o in rows:
            item = {"c": o.get("category", ""), "t": o.get("title", ""), "s": o.get("start", ""),
                    "e": o.get("end", ""), "k": o.get("source_kind", "")}
            if o.get("note"):
                item["n"] = o["note"]
            out.append(item)
        days[iso_day] = out
    types = [{"key": k, "name": v[0], "color": v[1], "fg": v[2]} for k, v in CATEGORY_STYLES.items()]
    weekly = []
    specs = [("lesson", base_schedule, "start", "end")] + [
        (key, personal_schedules.get(key, []), fields[0], fields[1]) for key, fields in FAMILY_SCHEDULE_FIELDS.items()]
    for category, rows, start_field, end_field in specs:
        for r in rows:
            if r.get("weekday") in WEEKDAYS:
                weekly.append({"c": category, "wd": r["weekday"], "s": r.get(start_field, ""),
                               "e": r.get(end_field, ""), "n": r.get("note", "")})
    changes = []
    today_iso = today.isoformat()
    for o in temp_overrides:
        target, new_day = o.get("target_date", ""), o.get("new_date", "")
        if not target or (target < today_iso and not (o.get("action") == "move" and new_day >= today_iso)):
            continue
        changes.append({"d": target, "c": o.get("category", "lesson"), "a": o.get("action", ""),
                        "s": o.get("slot_start", ""), "e": o.get("slot_end", ""), "nd": new_day,
                        "ns": o.get("new_start", ""), "ne": o.get("new_end", ""), "n": o.get("note", "")})
    generated = (now or datetime.datetime.now()).strftime("%Y-%m-%dT%H:%M:%S")
    return {"v": 1, "generated": generated, "today": today_iso, "types": types, "days": days,
            "weekly": weekly, "changes": changes}


def payload_signature(payload):
    """Same schedule -> same text, whatever time it was built (the 'generated' stamp is left out)."""
    body = {k: v for k, v in payload.items() if k != "generated"}
    return hashlib.sha1(json.dumps(body, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()


def phone_request(method, url, key, body=None, timeout=PHONE_TIMEOUT_S):
    """-> (status, text). Never raises: a network problem comes back as (0, message)."""
    req = urllib.request.Request(url, data=body, method=method, headers={
        "X-TC-Key": key, "User-Agent": "TutorCal", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, r.read(65536).decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        try:
            text = e.read(2000).decode("utf-8", "replace")
        except Exception:
            text = ""
        return e.code, text
    except Exception as e:
        return 0, str(e)


def phone_error_text(status, text):
    if status == 0:
        return "No connection to the server (%s)." % (text or "unknown error")[:120]
    if status == 401:
        return "The server did not accept the key - the code is wrong or old."
    if status == 404:
        return "The server has no TutorCal page at that address (has the 'TutorCal relay' job been run?)."
    if status == 429:
        return "The server says too many tries - wait a while."
    return "The server answered %d: %s" % (status, (text or "")[:120])


# *************** DEL 08 - MAIN APPLICATION ***************

class TutorCalApp:
    def __init__(self, root, settings):
        self.root = root
        self.settings = settings

        # Snapshot today's data files before this session can change
        # anything (DEL 04b). Cheap - a handful of small JSON files, once
        # a day - and it is the only thing that can undo a deletion the
        # user only notices next week.
        make_daily_backup()

        # --- user-defined lists (DEL 08b) -------------------------------
        # Loaded FIRST: the schedule definitions decide which categories,
        # colours, layer checkboxes and Family Schedule sub-tabs exist, so
        # everything built below depends on them being in place already.
        self.schedule_defs = normalize_schedule_defs(
            load_json_list(SCHEDULE_TYPES_PATH, None) or [dict(d) for d in DEFAULT_SCHEDULE_DEFS]
        )
        apply_schedule_defs(self.schedule_defs)
        # Contact apps start EMPTY on purpose - the App dropdown stays blank
        # until she has entered the apps she actually uses (Settings tab).
        self.contact_apps = [str(a) for a in (load_json_list(CONTACT_APPS_PATH, []) or []) if str(a).strip()]
        self.contact_roles = [str(r) for r in (load_json_list(CONTACT_ROLES_PATH, None)
                                               or list(DEFAULT_CONTACT_ROLES)) if str(r).strip()]
        for _protected in PROTECTED_CONTACT_ROLES:      # never let the list lose "Student"
            if _protected not in self.contact_roles:
                self.contact_roles.insert(0, _protected)

        # In-memory state, loaded from /Helpfiles JSON stores. The flat-list
        # model below turned out to be enough: Month/Week/Day View, the
        # alarm engine, and the overrides all read straight from these
        # same lists rather than needing a separate calendar data structure.
        self.calendar_events = load_json_list(EVENTS_PATH, [])
        if ensure_event_ids(self.calendar_events):   # back-fill ids for events.json
            save_json_list(EVENTS_PATH, self.calendar_events)  # saved before the alarm engine existed
        self.base_schedule = load_json_list(BASE_SCHEDULE_PATH, [])
        if ensure_schedule_ids(self.base_schedule):   # back-fill ids for base_schedule.json
            save_json_list(BASE_SCHEDULE_PATH, self.base_schedule)  # saved before recurring alarms existed
        self.temp_overrides = [normalize_override(o) for o in load_json_list(OVERRIDES_PATH, [])]
        self._drag_state = None    # in-progress Week/Day View drag-to-move/resize (DEL 08f), or None
        self.personal_schedules = load_json_list(
            PERSONAL_SCHEDULES_PATH,
            {key: [] for key in FAMILY_SCHEDULE_FIELDS},
        )
        for _key in FAMILY_SCHEDULE_FIELDS:        # a schedule added later has no list yet
            self.personal_schedules.setdefault(_key, [])
        # any() would short-circuit and skip back-filling later lists once an
        # earlier one already returned True, so collect into a list first to
        # make sure every family schedule gets checked, not just the first.
        if any([ensure_schedule_ids(rows) for rows in self.personal_schedules.values()]):
            save_json_list(PERSONAL_SCHEDULES_PATH, self.personal_schedules)  # back-fill ids, same as above
        self.contacts = load_json_list(CONTACTS_PATH, [])
        if ensure_contact_ids(self.contacts):   # back-fill ids for contacts.json saved before linking existed
            save_json_list(CONTACTS_PATH, self.contacts)

        # Per-event alarm state (last time a reminder fired, whether it's
        # been dismissed) - keyed by event id, persisted so reminders
        # behave correctly across app restarts (see DEL 07 and the alarm
        # engine methods below).
        self.alarm_state = load_json_dict(ALARM_STATE_PATH, {})

        # Month View navigation + which recurring layers are shown on it.
        _today = datetime.date.today()
        self.month_view_year = _today.year
        self.month_view_month = _today.month
        self.week_view_start = week_start_for(_today)   # Monday of the shown week
        self.day_view_date = _today                     # the single date Day View zooms into (DEL 08e)
        # One checkbox per user-defined schedule; "lesson" starts on, the
        # rest off. Rebuilt by _sync_layer_vars() when she edits the list.
        self.month_layer_vars = {}

        # Export tab state (DEL 07c) - which date range and which recurring
        # layers to include; restored from settings.json if a prior session
        # saved a choice (see _on_close), otherwise defaults to everything on
        # since an export is usually meant to be a complete phone-friendly
        # agenda.
        _saved_export_range = self.settings.get("export_range", "Next 7 days")
        if _saved_export_range not in EXPORT_RANGE_CHOICES:
            _saved_export_range = "Next 7 days"   # ignore garbage/old values rather than erroring
        _saved_export_layers = self.settings.get("export_layers") or {}
        self.export_range_var = tk.StringVar(value=_saved_export_range)
        self.export_from_var = tk.StringVar(value=_today.isoformat())
        self.export_to_var = tk.StringVar(value=(_today + datetime.timedelta(days=6)).isoformat())
        self.export_layer_vars = {}
        self._saved_export_layers = _saved_export_layers
        self._sync_layer_vars()          # fills month_layer_vars + export_layer_vars

        # DEL 10 - phone page: state of the automatic sender. Made BEFORE the tabs, because the Settings tab shows the status.
        self._phone_busy = False
        self._phone_last_sig = ""
        self._phone_last_ok = 0.0
        self._phone_next_try = 0.0
        self._phone_poll_id = None
        self.phone_status_var = tk.StringVar(value="")

        self._build_menu()
        self._build_tabs()
        self._reload_all_treeviews()

        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

        # Used to notice the clock rolling past midnight while the app is
        # left open, so the "Today:" label and the highlighted day cell
        # don't quietly go on pointing at yesterday (DEL 08b).
        self._last_seen_date = datetime.date.today()

        # Start the alarm engine's clock-polling loop (see DEL 07 for the
        # constants/helpers and the "Alarm engine" methods further down
        # for the actual check/fire/dismiss logic). A short initial delay
        # lets the window finish drawing before the first check runs.
        # The id is kept so the loop can be stopped: a pending after()
        # that fires into a destroyed window raises "invalid command
        # name" on the way out, and a test that drives the app by hand
        # wants the clock out of it (see _on_close and _stop_alarm_loop).
        self._alarm_after_id = self.root.after(1500, self._check_alarms)

        # The current-time line on the Week/Day grids creeps down once a
        # minute. Separate from the alarm poll on purpose: it redraws three
        # canvas items and nothing else.
        self._week_now_geom = None
        self._day_now_geom = None
        self._now_after_id = self.root.after(NOW_LINE_TICK_MS, self._tick_now_line)

        # DEL 10 - phone page: the clock loop starts a few seconds after the window is up (its state is made before the tabs, see above).
        self._phone_after_id = self.root.after(5000, self._phone_tick)

        # If a data file was damaged and had to be set aside on the way in
        # (DEL 04b), say so - loudly, once, and only then. Silence is what
        # made the old behaviour dangerous.
        if DATA_PROBLEMS:
            self.root.after(400, self._report_data_problems)

    # ---------------- DEL 10: phone page ----------------
    def _phone_payload(self):
        return build_phone_payload(datetime.date.today(), self.base_schedule, self.temp_overrides,
                                   self.personal_schedules, self.calendar_events)

    def _phone_say(self, text):
        try:
            self.phone_status_var.set(text)
        except Exception:
            pass

    def _phone_run(self, job, on_done):
        """Run job() on a helper thread (never block the window on the network), then call on_done(*result) back on the Tk thread.
        Returns False when a send is already running."""
        if self._phone_busy:
            return False
        self._phone_busy = True
        box = {}

        def work():
            try:
                box["r"] = job()
            except Exception as e:
                box["r"] = (-1, "Error: %s" % e)

        threading.Thread(target=work, daemon=True).start()

        def poll():
            self._phone_poll_id = None
            if "r" not in box:
                self._phone_poll_id = self.root.after(250, poll)
                return
            self._phone_busy = False
            on_done(*box["r"])

        poll()
        return True

    def _phone_push(self, manual):
        """Build the schedule and send it. manual = the button (says what is wrong); otherwise quiet unless it worked or failed."""
        parsed = parse_phone_code(self.settings.get("phone_code", ""))
        if not parsed:
            if manual:
                self._phone_say("Paste the code from the server first, then press 'Save code'.")
            return False
        base, key = parsed
        payload = self._phone_payload()
        sig = payload_signature(payload)
        body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        days = len(payload["days"])

        def job():
            return phone_request("PUT", base + "api/data", key, body)

        def done(status, text):
            now = datetime.datetime.now()
            if status == 200:
                self._phone_last_sig = sig
                self._phone_last_ok = now.timestamp()
                self._phone_next_try = 0.0
                self._phone_say("Sent to the phone page at %s (%d days, %d KB)." % (now.strftime("%H:%M"), days, max(1, len(body) // 1024)))
            else:
                self._phone_next_try = now.timestamp() + PHONE_RETRY_S
                self._phone_say(phone_error_text(status, text) + (" Trying again in a few minutes." if not manual else ""))

        started = self._phone_run(job, done)
        if started:
            self._phone_say("Sending...")
        return started

    def _phone_tick(self):
        """Every PHONE_CHECK_MS: if the schedule differs from what was last sent (or it is a new day, or 12 hours passed), send it."""
        self._phone_after_id = None
        try:
            if (self.settings.get("phone_enabled") and not self._phone_busy
                    and parse_phone_code(self.settings.get("phone_code", ""))):
                now = datetime.datetime.now().timestamp()
                if now >= self._phone_next_try:
                    sig = payload_signature(self._phone_payload())
                    if sig != self._phone_last_sig or now - self._phone_last_ok > PHONE_HEARTBEAT_S:
                        self._phone_push(manual=False)
        except Exception:
            pass     # the sender must never disturb the program
        try:
            self._phone_after_id = self.root.after(PHONE_CHECK_MS, self._phone_tick)
        except Exception:
            pass

    def _phone_final_push(self):
        """On close: if the schedule changed since the last send, send once more, but wait at most 4 seconds."""
        try:
            parsed = parse_phone_code(self.settings.get("phone_code", ""))
            if not (self.settings.get("phone_enabled") and parsed):
                return
            payload = self._phone_payload()
            if payload_signature(payload) == self._phone_last_sig:
                return
            body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
            phone_request("PUT", parsed[0] + "api/data", parsed[1], body, timeout=4)
        except Exception:
            pass

    def _build_phone_page_box(self, parent):
        box = tk.LabelFrame(parent, text="Phone page", bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                            font=FONT_MAIN, padx=10, pady=10)
        box.pack(fill="x", pady=(12, 0))
        tk.Label(box, bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM, font=FONT_SMALL, wraplength=760, justify="left",
                 text="Shows your schedule on the phone, read only: the fixed weekly schedule with every temporary change "
                      "already applied. Changes are always made here on the PC. While TutorCal is open it sends the new copy by "
                      "itself a few seconds after something changes. Paste the code that the server installer made "
                      "(it starts with TCAL1:), press 'Save code', then open the phone link on the phone once.").pack(anchor="w", pady=(0, 8))
        row = tk.Frame(box, bg=COLOR_BG_PANEL)
        row.pack(fill="x")
        tk.Label(row, text="Code:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.phone_code_var = tk.StringVar(value=self.settings.get("phone_code", ""))
        make_entry(row, textvariable=self.phone_code_var, width=62, font=FONT_MAIN, show="*").pack(side="left", padx=(6, 0))
        self.phone_enabled_var = tk.BooleanVar(value=bool(self.settings.get("phone_enabled")))
        tk.Checkbutton(box, text="Keep the phone page up to date automatically", variable=self.phone_enabled_var,
                       command=self._phone_save_settings, bg=COLOR_BG_PANEL, font=FONT_MAIN,
                       activebackground=COLOR_BG_PANEL).pack(anchor="w", pady=(8, 0))
        btns = tk.Frame(box, bg=COLOR_BG_PANEL)
        btns.pack(fill="x", pady=(8, 0))
        styled_button(btns, "Save code", self._phone_save_code, COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left")
        styled_button(btns, "Test connection", self._phone_test, COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(btns, "Send now", lambda: self._phone_push(manual=True), COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left")
        styled_button(btns, "Copy phone link", self._phone_copy_link, COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        tk.Label(box, textvariable=self.phone_status_var, bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN, font=FONT_SMALL,
                 anchor="w", justify="left", width=110, height=2, wraplength=760).pack(anchor="w", pady=(8, 0))

    def _phone_save_settings(self):
        self.settings["phone_enabled"] = bool(self.phone_enabled_var.get())
        save_settings(self.settings)

    def _phone_save_code(self):
        text = self.phone_code_var.get().strip()
        if text and not parse_phone_code(text):
            messagebox.showwarning("Phone page", "That is not a TutorCal phone code.\nIt starts with TCAL1: and comes from the "
                                   "server installer (file tcal_code.txt).", parent=self.root)
            return
        self.settings["phone_code"] = text
        self._phone_last_sig = ""            # a new code means a new server: send again
        self._phone_next_try = 0.0
        save_settings(self.settings)
        self._phone_say("Code saved." if text else "Code removed.")

    def _phone_test(self):
        parsed = parse_phone_code(self.phone_code_var.get().strip())
        if not parsed:
            self._phone_say("Paste a code that starts with TCAL1: first.")
            return
        base, key = parsed

        def done(status, text):
            self._phone_say("Connection works - the server accepted the key." if status == 200 else phone_error_text(status, text))

        if self._phone_run(lambda: phone_request("GET", base + "api/ping", key), done):
            self._phone_say("Testing...")

    def _phone_copy_link(self):
        link = phone_link_for(self.phone_code_var.get().strip())
        if not link:
            self._phone_say("Paste a code that starts with TCAL1: first.")
            return
        self.root.clipboard_clear()
        self.root.clipboard_append(link)
        self._phone_say("Phone link copied. Send it to yourself (it holds the key) and open it once on the phone.")

    def _restore_from_backup(self):
        """Put back the data files from one of the dated folders
        make_daily_backup() writes (DEL 04b). A backup nobody can restore
        is only half a safety net - doing it by hand means closing the
        program, finding the folder and copying five files over the live
        ones in the right places.

        Two things this must get right: the *current* files are copied
        aside first (a restore is itself something you might regret), and
        afterwards the program closes WITHOUT saving - everything in
        memory belongs to the data we just replaced, and _on_close would
        cheerfully write it straight back over the restored files."""
        folders = []
        if os.path.isdir(DIR_BACKUPS):
            folders = sorted((name for name in os.listdir(DIR_BACKUPS)
                              if os.path.isdir(os.path.join(DIR_BACKUPS, name))), reverse=True)
        if not folders:
            messagebox.showinfo(
                "Restore from a backup",
                "There are no backups yet.\n\nOne is taken automatically each day "
                f"you start TutorCal, into:\n{DIR_BACKUPS}",
                parent=self.root)
            return

        top = tk.Toplevel(self.root)
        top.title("Restore from a backup")
        top.configure(bg=COLOR_BG_PANEL)
        top.transient(self.root)
        top.grab_set()
        top.bind("<Escape>", lambda _e: top.destroy())

        tk.Label(top, text="Restore from a backup", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                 font=("Segoe UI", 13, "bold")).pack(padx=18, pady=(14, 2))
        tk.Label(top, text="Pick the day to go back to. Everything currently in the program "
                           "is replaced by what it looked like on that day.",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM, font=FONT_SMALL,
                 wraplength=380, justify="left").pack(padx=18, pady=(0, 8))

        listbox = tk.Listbox(top, height=min(10, len(folders)), width=44, font=FONT_MAIN,
                             exportselection=False, activestyle="none",
                             highlightthickness=1, highlightbackground=COLOR_SEPARATOR)
        for name in folders:
            files = [f for f in os.listdir(os.path.join(DIR_BACKUPS, name)) if f.endswith(".json")]
            listbox.insert("end", f"{name}   ({len(files)} file{'' if len(files) == 1 else 's'})")
        listbox.selection_set(0)
        listbox.pack(padx=18, pady=(0, 10))

        def do_restore():
            selection = listbox.curselection()
            if not selection:
                return
            name = folders[selection[0]]
            source = os.path.join(DIR_BACKUPS, name)
            files = [f for f in os.listdir(source) if f.endswith(".json")]
            if not messagebox.askyesno(
                    "Restore from a backup",
                    f"Replace the current data with the backup from {name}?\n\n"
                    f"{len(files)} file(s) will be restored. What is in the program right now "
                    f"is copied aside first, into a 'before-restore' folder, so this can be "
                    f"undone.\n\nTutorCal will close afterwards - start it again to see the "
                    f"restored data.",
                    parent=top):
                return

            stamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
            safety = os.path.join(DIR_BACKUPS, f"before-restore-{stamp}")
            try:
                os.makedirs(safety, exist_ok=True)
                for path in BACKED_UP_DATA_FILES:
                    if os.path.isfile(path):
                        shutil.copy2(path, os.path.join(safety, os.path.basename(path)))
            except Exception as e:
                messagebox.showerror("Restore failed",
                                     f"Could not put the current data safely aside, so nothing "
                                     f"was restored:\n{e}", parent=top)
                return

            by_name = {os.path.basename(p): p for p in BACKED_UP_DATA_FILES}
            restored, problems = 0, []
            for filename in files:
                target = by_name.get(filename)
                if target is None:
                    continue        # a file from an older version - leave it alone
                try:
                    shutil.copy2(os.path.join(source, filename), target)
                    restored += 1
                except Exception as e:
                    problems.append(f"{filename}: {e}")

            top.destroy()
            if problems:
                messagebox.showwarning(
                    "Restored with problems",
                    f"{restored} file(s) restored, but some could not be:\n"
                    + "\n".join(problems) + f"\n\nThe previous data is in:\n{safety}",
                    parent=self.root)
            else:
                messagebox.showinfo(
                    "Restored",
                    f"{restored} file(s) restored from {name}.\n\nThe data from just before "
                    f"the restore is kept in:\n{safety}\n\nTutorCal will close now - start it "
                    f"again to work with the restored data.",
                    parent=self.root)
            self._quit_without_saving()

        btn_row = tk.Frame(top, bg=COLOR_BG_PANEL)
        btn_row.pack(pady=(0, 14))
        styled_button(btn_row, "Restore", do_restore, COLOR_BTN_DANGER,
                      COLOR_BTN_DANGER_FG).pack(side="left", padx=6)
        styled_button(btn_row, "Cancel (Esc)", top.destroy, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left", padx=6)
        _center_over(top, self.root)
        return top

    def _quit_without_saving(self):
        """Close the window WITHOUT writing the in-memory lists back out.
        Only used after a restore, where saving would undo the restore.
        Window geometry and the other UI settings are still remembered -
        they are not part of the restored data."""
        self.settings["geometry"] = self.root.geometry()
        save_settings(self.settings)
        self._stop_alarm_loop()
        remove_tray_icon()
        self.root.destroy()

    def _report_data_problems(self):
        """Tell the user which data files could not be read, what was done
        with them, and where the daily backups live - then clear the list
        so a later reload doesn't repeat the same message."""
        if not DATA_PROBLEMS:
            return
        detail = "\n".join(DATA_PROBLEMS)
        DATA_PROBLEMS.clear()
        messagebox.showwarning(
            "Some data could not be read",
            "TutorCal started, but one or more of its data files were damaged:\n\n"
            f"{detail}\n\n"
            "Nothing was thrown away - the damaged file was renamed rather than "
            "overwritten, and the newest working copy was used where one existed.\n\n"
            f"Daily backups are kept in:\n{DIR_BACKUPS}",
            parent=self.root,
        )

    # ---------------- menu ----------------
    def _build_menu(self):
        menubar = tk.Menu(self.root)
        file_menu = tk.Menu(menubar, tearoff=0)
        file_menu.add_command(label="Restore from a backup...", command=self._restore_from_backup)
        file_menu.add_separator()
        file_menu.add_command(label="Exit", command=self._on_close)
        menubar.add_cascade(label="File", menu=file_menu)

        help_menu = tk.Menu(menubar, tearoff=0)
        help_menu.add_command(label="Help", command=self._show_help)
        help_menu.add_command(label="About", command=self._show_about)
        menubar.add_cascade(label="Help", menu=help_menu)
        self.root.config(menu=menubar)

    # ---------------- tabs ----------------
    def _build_tabs(self):
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill="both", expand=True)

        self.tab_calendar = tk.Frame(self.notebook, bg=COLOR_BG_MAIN)
        self.tab_base_schedule = tk.Frame(self.notebook, bg=COLOR_BG_MAIN)
        self.tab_family = tk.Frame(self.notebook, bg=COLOR_BG_MAIN)
        self.tab_contacts = tk.Frame(self.notebook, bg=COLOR_BG_MAIN)
        self.tab_export = tk.Frame(self.notebook, bg=COLOR_BG_MAIN)
        self.tab_settings = tk.Frame(self.notebook, bg=COLOR_BG_MAIN)

        self.notebook.add(self.tab_calendar, text="Calendar")
        self.notebook.add(self.tab_base_schedule, text="Base Schedule")
        self.notebook.add(self.tab_family, text="Family Schedules")
        self.notebook.add(self.tab_contacts, text="Contacts")
        self.notebook.add(self.tab_export, text="Export")
        self.notebook.add(self.tab_settings, text="Settings")

        self._build_tab_calendar(self.tab_calendar)
        self._build_tab_base_schedule(self.tab_base_schedule)
        self._build_tab_family(self.tab_family)
        self._build_tab_contacts(self.tab_contacts)
        self._build_tab_export(self.tab_export)
        self._build_tab_settings(self.tab_settings)

        try:
            self.notebook.select(int(self.settings.get("last_tab", 0)))
        except Exception:
            pass

    def _header(self, parent, title, subtitle):
        head = tk.Frame(parent, bg=COLOR_BG_HEADER)
        head.pack(fill="x")
        tk.Label(head, text=title, bg=COLOR_BG_HEADER, fg=COLOR_TEXT_ON_HEADER,
                 font=FONT_HEADER, padx=14, pady=8).pack(anchor="w")
        tk.Label(head, text=subtitle, bg=COLOR_BG_HEADER, fg=COLOR_TEXT_ON_HEADER,
                 font=FONT_SMALL, padx=14, wraplength=900,
                 justify="left").pack(anchor="w", pady=(0, 8))

    # ---------------- Tab: Calendar ----------------
    def _build_tab_calendar(self, parent):
        self._header(
            parent, "Calendar & Notes",
            "Month View shows the base schedule, family schedules, one-off "
            "events, and overrides all merged together; Week View shows the "
            "same week as a real time grid, where each block is as tall as it "
            "is long; Day View zooms into one day at a time the same way. "
            "List View is where you add the one-off entries. Reminders "
            "set there ('Warn before') actually pop up while TutorCal is "
            "running - see Help for how the repeat behavior works.",
        )
        self.calendar_sub_notebook = ttk.Notebook(parent)
        self.calendar_sub_notebook.pack(fill="both", expand=True, padx=10, pady=10)

        self.tab_month_view = tk.Frame(self.calendar_sub_notebook, bg=COLOR_BG_MAIN)
        self.tab_week_view = tk.Frame(self.calendar_sub_notebook, bg=COLOR_BG_MAIN)
        self.tab_list_view = tk.Frame(self.calendar_sub_notebook, bg=COLOR_BG_MAIN)
        self.tab_day_view = tk.Frame(self.calendar_sub_notebook, bg=COLOR_BG_MAIN)
        self.calendar_sub_notebook.add(self.tab_month_view, text="Month View")
        self.calendar_sub_notebook.add(self.tab_week_view, text="Week View")
        self.calendar_sub_notebook.add(self.tab_list_view, text="List View")
        # Day View is appended LAST, after the three original tabs, on
        # purpose: last_calendar_tab (settings.json) is saved as a plain
        # notebook index (DEL 09), so a settings file from before Day View
        # existed still lands on the same tab it always did instead of
        # silently landing on a different one because the indices shifted.

        self.calendar_sub_notebook.add(self.tab_day_view, text="Day View")

        self._build_calendar_month_view(self.tab_month_view)
        self._build_calendar_week_view(self.tab_week_view)
        self._build_calendar_list_view(self.tab_list_view)
        self._build_calendar_day_view(self.tab_day_view)

        try:   # come back to the view she was last using, not always Month
            self.calendar_sub_notebook.select(int(self.settings.get("last_calendar_tab", 0)))
        except Exception:
            pass

    # ---------------- Tab: Calendar -> Month View ----------------
    def _build_calendar_month_view(self, parent):
        nav = tk.Frame(parent, bg=COLOR_BG_MAIN)
        nav.pack(fill="x", padx=4, pady=(4, 2))
        styled_button(nav, "< Prev", self._month_prev, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left")
        styled_button(nav, "Today", self._month_today, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(nav, "Next >", self._month_next, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left")

        # Today's full date, spelled out right next to the navigation
        # buttons - the month title alone ("August 2026") never said which
        # day it actually is (DEL 08b). Kept in the same orange as the
        # highlighted day cell so the two obviously belong together.
        self.today_lbl = tk.Label(nav, text="", bg=COLOR_BG_MAIN, fg=COLOR_TODAY_OUTLINE,
                                   font=("Segoe UI", 11, "bold"))
        self.today_lbl.pack(side="left", padx=(14, 0))

        self.month_title_lbl = tk.Label(nav, text="", bg=COLOR_BG_MAIN, fg=COLOR_TEXT_MAIN,
                                         font=("Segoe UI", 13, "bold"))
        self.month_title_lbl.pack(side="left", padx=18)

        layers = tk.Frame(parent, bg=COLOR_BG_MAIN)
        layers.pack(fill="x", padx=4, pady=(0, 6))
        tk.Label(layers, text="Show:", bg=COLOR_BG_MAIN, font=FONT_MAIN).pack(side="left")
        # The checkboxes live in their own frame so the whole row can be
        # rebuilt when the user adds/renames/deletes a schedule.
        self.month_layer_box = tk.Frame(layers, bg=COLOR_BG_MAIN)
        self.month_layer_box.pack(side="left")
        tk.Label(layers, text="(events/notes/overrides always shown)", bg=COLOR_BG_MAIN,
                 fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left", padx=(4, 0))
        self._rebuild_month_layer_row()

        self.month_grid_frame = tk.Frame(parent, bg=COLOR_SEPARATOR)
        self.month_grid_frame.pack(fill="both", expand=True, padx=4, pady=(0, 6))

        self._refresh_month_view()

    def _rebuild_month_layer_row(self):
        """(Re)draw the 'Show:' layer checkboxes from the current schedule
        definitions - one per schedule, in the user's own order, with the
        schedule's own colour as the checkbox indicator."""
        if not hasattr(self, "month_layer_box"):
            return      # Month View not built yet
        for w in self.month_layer_box.winfo_children():
            w.destroy()
        for d in SCHEDULE_DEFS:
            key = d["key"]
            if key not in self.month_layer_vars:
                continue
            tk.Checkbutton(
                self.month_layer_box, text=d["name"], variable=self.month_layer_vars[key],
                bg=COLOR_BG_MAIN, activebackground=COLOR_BG_MAIN, selectcolor=d["color"],
                font=FONT_SMALL, command=self._refresh_month_view,
            ).pack(side="left", padx=(0, 10))

    def _month_prev(self):
        y, m = self.month_view_year, self.month_view_month - 1
        if m < 1:
            m, y = 12, y - 1
        self.month_view_year, self.month_view_month = y, m
        self._refresh_month_view()

    def _month_next(self):
        y, m = self.month_view_year, self.month_view_month + 1
        if m > 12:
            m, y = 1, y + 1
        self.month_view_year, self.month_view_month = y, m
        self._refresh_month_view()

    def _month_today(self):
        today = datetime.date.today()
        self.month_view_year, self.month_view_month = today.year, today.month
        self._refresh_month_view()

    def _refresh_month_view(self):
        for w in self.month_grid_frame.winfo_children():
            w.destroy()

        year, month = self.month_view_year, self.month_view_month
        self.month_title_lbl.configure(text=datetime.date(year, month, 1).strftime("%B %Y"))
        _t = datetime.date.today()
        # str(_t.day) rather than %d - no misleading leading zero ("05 August").
        self.today_lbl.configure(
            text=f"Today: {_t.strftime('%A')}, {_t.day} {_t.strftime('%B %Y')}")

        layers = {key: var.get() for key, var in self.month_layer_vars.items()}
        occurrences = generate_month_occurrences(
            year, month, self.base_schedule, self.temp_overrides,
            self.personal_schedules, self.calendar_events, layers,
        )
        weeks = month_grid_weeks(year, month)
        today_iso = datetime.date.today().isoformat()

        for c in range(7):
            self.month_grid_frame.grid_columnconfigure(c, weight=1, uniform="day")
            tk.Label(self.month_grid_frame, text=WEEKDAYS[c][:3], bg=COLOR_BG_HEADER,
                     fg=COLOR_TEXT_ON_HEADER, font=FONT_SMALL, pady=3).grid(
                row=0, column=c, sticky="nsew", padx=1, pady=(0, 1))

        for r, week in enumerate(weeks, start=1):
            self.month_grid_frame.grid_rowconfigure(r, weight=1)
            for c, d in enumerate(week):
                iso = d.isoformat()
                in_month = (d.month == month)
                is_today = (iso == today_iso)
                # Today used to be a 1-pixel orange line that was easy to
                # miss: it now gets a thick outline, a tinted background,
                # and its day number in a filled orange badge (DEL 08b).
                cell_bg = COLOR_TODAY_CELL_BG if is_today else (
                    COLOR_BG_PANEL if in_month else "#efece5")
                cell = tk.Frame(
                    self.month_grid_frame, bg=cell_bg, padx=3, pady=2,
                    highlightthickness=(TODAY_OUTLINE_THICKNESS if is_today else 1),
                    highlightbackground=(COLOR_TODAY_OUTLINE if is_today else COLOR_SEPARATOR),
                    highlightcolor=(COLOR_TODAY_OUTLINE if is_today else COLOR_SEPARATOR),
                )
                cell.grid(row=r, column=c, sticky="nsew", padx=1, pady=1)

                if is_today:
                    tk.Label(cell, text=f" {d.day} ", bg=COLOR_TODAY_OUTLINE, fg="#ffffff",
                             font=("Segoe UI", 10, "bold"), padx=4).pack(anchor="ne")
                else:
                    num_fg = COLOR_TEXT_MAIN if in_month else COLOR_TEXT_DIM
                    tk.Label(cell, text=str(d.day), bg=cell_bg, fg=num_fg,
                             font=("Segoe UI", 9, "bold")).pack(anchor="ne")

                day_occ = occurrences.get(iso, [])
                for occ in day_occ[:4]:
                    _label, chip_bg, chip_fg = CATEGORY_STYLES.get(occ["category"], ("?", "#999", "#fff"))
                    text = occ["title"]
                    if occ.get("start"):
                        text = f"{occ['start']} {text}"
                    tk.Label(cell, text=text[:26], bg=chip_bg, fg=chip_fg, font=FONT_TINY,
                             anchor="w", padx=3).pack(fill="x", pady=1)
                if len(day_occ) > 4:
                    tk.Label(cell, text=f"+{len(day_occ) - 4} more", bg=cell_bg,
                             fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(anchor="w")

                cell.bind("<Button-1>", lambda _e, dd=d, oo=day_occ: self._show_day_popup(dd, oo))
                for child in cell.winfo_children():
                    child.bind("<Button-1>", lambda _e, dd=d, oo=day_occ: self._show_day_popup(dd, oo))

        # The Week View and Day View draw from the same data, so both are
        # redrawn from here rather than from every single caller (DEL 08d/e).
        self._refresh_week_view()
        self._refresh_day_view()

    # ---------------- Tab: Calendar -> Week View (DEL 08d) ----------------
    # The Month View answers "what is happening this month"; this answers
    # "what does Tuesday actually look like" - a real time grid where a
    # 17:00-18:00 lesson is drawn twice as tall as a half-hour bus ride,
    # overlapping items sit side by side, and the same layer checkboxes
    # decide what is shown. It reads the very same occurrence data the
    # Month View and the exports do, so the three can never disagree.

    def _build_calendar_week_view(self, parent):
        nav = tk.Frame(parent, bg=COLOR_BG_MAIN)
        nav.pack(fill="x", padx=4, pady=(4, 2))
        styled_button(nav, "< Prev week", lambda: self._week_step(-1),
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left")
        styled_button(nav, "This week", self._week_today,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(nav, "Next week >", lambda: self._week_step(1),
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left")
        self.week_today_lbl = tk.Label(nav, text="", bg=COLOR_BG_MAIN, fg=COLOR_TODAY_OUTLINE,
                                        font=("Segoe UI", 11, "bold"))
        self.week_today_lbl.pack(side="left", padx=(14, 0))
        self.week_title_lbl = tk.Label(nav, text="", bg=COLOR_BG_MAIN, fg=COLOR_TEXT_MAIN,
                                        font=("Segoe UI", 13, "bold"))
        self.week_title_lbl.pack(side="left", padx=18)

        layers = tk.Frame(parent, bg=COLOR_BG_MAIN)
        layers.pack(fill="x", padx=4, pady=(0, 4))
        tk.Label(layers, text="Show:", bg=COLOR_BG_MAIN, font=FONT_MAIN).pack(side="left")
        # Same BooleanVars as the Month View - one set of layer choices for
        # the whole Calendar tab, so ticking a layer here ticks it there.
        self.week_layer_box = tk.Frame(layers, bg=COLOR_BG_MAIN)
        self.week_layer_box.pack(side="left")
        tk.Label(layers, text="(click a date to see the day - double-click a block to edit it, "
                              "drag a block to move it or its bottom edge to resize it, or "
                              "double-click empty space to add an entry there)",
                 bg=COLOR_BG_MAIN, fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left", padx=(4, 0))

        holder = tk.Frame(parent, bg=COLOR_BG_PANEL)
        holder.pack(fill="both", expand=True, padx=4, pady=(0, 6))
        # Scrollbar packed BEFORE the expanding canvas - the other way
        # round it silently ends up one pixel wide.
        vsb = ttk.Scrollbar(holder, orient="vertical")
        vsb.pack(side="right", fill="y")
        self.week_canvas = tk.Canvas(holder, bg=COLOR_BG_PANEL, highlightthickness=0,
                                     yscrollcommand=vsb.set)
        self.week_canvas.pack(side="left", fill="both", expand=True)
        vsb.configure(command=self.week_canvas.yview)

        self.week_canvas.bind("<Configure>", self._week_on_resize)
        self.week_canvas.bind("<Enter>", lambda _e: self.week_canvas.bind_all(
            "<MouseWheel>", self._week_on_wheel))
        self.week_canvas.bind("<Leave>", lambda _e: self.week_canvas.unbind_all("<MouseWheel>"))
        self.week_canvas.bind("<Double-Button-1>", self._week_on_double_click)
        # Drag-to-move/resize (DEL 08f - the last piece of master ToDo #1):
        # a plain press-drag-release on a block, handled separately from
        # the double-click above (see _week_on_press for how the two tell
        # a genuine drag apart from the two clicks that make up a
        # double-click).
        self.week_canvas.bind("<ButtonPress-1>", self._week_on_press)
        self.week_canvas.bind("<B1-Motion>", self._week_on_drag_motion)
        self.week_canvas.bind("<ButtonRelease-1>", self._week_on_release)
        self.week_canvas.bind("<Motion>", self._week_on_hover_motion)

        self._week_last_width = 0
        self._week_blocks = []      # [(x1, y1, x2, y2, date, occurrence), ...]
        self._week_day_columns = []  # [(x1, x2, date), ...] - for empty-space clicks
        self._rebuild_week_layer_row()
        self._refresh_week_view()

    def _rebuild_week_layer_row(self):
        if not hasattr(self, "week_layer_box"):
            return
        for w in self.week_layer_box.winfo_children():
            w.destroy()
        for d in SCHEDULE_DEFS:
            key = d["key"]
            if key not in self.month_layer_vars:
                continue
            tk.Checkbutton(
                self.week_layer_box, text=d["name"], variable=self.month_layer_vars[key],
                bg=COLOR_BG_MAIN, activebackground=COLOR_BG_MAIN, selectcolor=d["color"],
                font=FONT_SMALL, command=self._refresh_month_view,
            ).pack(side="left", padx=(0, 10))

    def _week_on_wheel(self, event):
        self.week_canvas.yview_scroll(-1 if event.delta > 0 else 1, "units")

    def _week_on_resize(self, event):
        # Only redraw when the width actually changed - a Configure event
        # fires for every scroll and would otherwise redraw constantly.
        if abs(event.width - self._week_last_width) > 2:
            self._week_last_width = event.width
            self._refresh_week_view()

    def _week_step(self, weeks):
        self.week_view_start += datetime.timedelta(weeks=weeks)
        self._refresh_week_view()

    def _week_today(self):
        self.week_view_start = week_start_for(datetime.date.today())
        self._refresh_week_view()

    def _week_dates(self):
        return [self.week_view_start + datetime.timedelta(days=i) for i in range(7)]

    def _refresh_week_view(self):
        if not hasattr(self, "week_canvas"):
            return      # Week View not built yet
        canvas = self.week_canvas
        canvas.delete("all")
        self._week_blocks = []
        self._week_day_columns = []

        dates = self._week_dates()
        today = datetime.date.today()
        first, last = dates[0], dates[-1]
        span = (f"{first.day} {first.strftime('%B')} - {last.day} {last.strftime('%B %Y')}"
                if first.month != last.month
                else f"{first.day} - {last.day} {last.strftime('%B %Y')}")
        self.week_title_lbl.configure(text=f"Week {first.isocalendar()[1]}  ({span})")
        self.week_today_lbl.configure(
            text=f"Today: {today.strftime('%A')}, {today.day} {today.strftime('%B %Y')}")

        layers = {key: var.get() for key, var in self.month_layer_vars.items()}
        occurrences = generate_occurrences_for_dates(
            dates, self.base_schedule, self.temp_overrides, self.personal_schedules,
            self.calendar_events, layers,
        )
        start_hour, end_hour = week_view_hour_range(occurrences, dates)
        self._week_start_hour = start_hour

        width = max(canvas.winfo_width(), 560)
        col_w = (width - WEEK_VIEW_GUTTER_WIDTH) / 7.0
        # All-day strip: anything without a usable start time (plain notes,
        # override notes, entries saved with no clock time).
        untimed = {d.isoformat(): [o for o in occurrences.get(d.isoformat(), [])
                                   if occurrence_span(o) is None] for d in dates}
        allday_rows = max((len(v) for v in untimed.values()), default=0)
        allday_h = allday_rows * 18 + (6 if allday_rows else 0)
        grid_top = WEEK_VIEW_HEADER_HEIGHT + allday_h
        self._week_grid_top_px = grid_top      # remembered for click -> time mapping
        grid_h = (end_hour - start_hour) * WEEK_VIEW_HOUR_HEIGHT

        def y_for(minute):
            return grid_top + (minute - start_hour * 60) / 60.0 * WEEK_VIEW_HOUR_HEIGHT

        # --- day columns, headers, today highlight
        for i, d in enumerate(dates):
            x1 = WEEK_VIEW_GUTTER_WIDTH + i * col_w
            x2 = x1 + col_w
            self._week_day_columns.append((x1, x2, d))
            if d == today:
                canvas.create_rectangle(x1, grid_top, x2, grid_top + grid_h,
                                        fill=COLOR_WEEK_TODAY_COLUMN, outline="")
            head_bg = COLOR_TODAY_OUTLINE if d == today else COLOR_BG_HEADER
            canvas.create_rectangle(x1, 0, x2, WEEK_VIEW_HEADER_HEIGHT - 2,
                                    fill=head_bg, outline="")
            head = canvas.create_text(
                (x1 + x2) / 2, (WEEK_VIEW_HEADER_HEIGHT - 2) / 2,
                text=f"{WEEKDAYS[d.weekday()][:3]} {d.day}",
                fill=COLOR_TEXT_ON_HEADER, font=("Segoe UI", 9, "bold"))
            canvas.tag_bind(head, "<Button-1>",
                            lambda _e, dd=d: self._show_day_popup(
                                dd, occurrences.get(dd.isoformat(), [])))

            for row_i, occ in enumerate(untimed.get(d.isoformat(), [])):
                _label, chip_bg, chip_fg = CATEGORY_STYLES.get(
                    occ["category"], ("?", "#999999", "#ffffff"))
                ay1 = WEEK_VIEW_HEADER_HEIGHT + 2 + row_i * 18
                canvas.create_rectangle(x1 + 2, ay1, x2 - 2, ay1 + 16,
                                        fill=chip_bg, outline="")
                canvas.create_text(x1 + 6, ay1 + 8, anchor="w", fill=chip_fg, font=FONT_TINY,
                                   width=max(int(col_w - 12), 20),
                                   text=self._week_block_text(occ, col_w - 12, one_line=True))
                self._week_blocks.append((x1 + 2, ay1, x2 - 2, ay1 + 16, d, occ))

        # --- hour lines + labels
        for hour in range(start_hour, end_hour + 1):
            y = y_for(hour * 60)
            canvas.create_line(WEEK_VIEW_GUTTER_WIDTH, y, width, y, fill=COLOR_WEEK_GRID_LINE)
            if hour < end_hour:
                canvas.create_line(WEEK_VIEW_GUTTER_WIDTH, y + WEEK_VIEW_HOUR_HEIGHT / 2,
                                   width, y + WEEK_VIEW_HOUR_HEIGHT / 2,
                                   fill=COLOR_WEEK_HALFHOUR_LINE)
                canvas.create_text(WEEK_VIEW_GUTTER_WIDTH - 8, y + 2, anchor="ne",
                                   text=f"{hour:02d}:00", fill=COLOR_TEXT_DIM, font=FONT_SMALL)
        for i in range(8):
            x = WEEK_VIEW_GUTTER_WIDTH + i * col_w
            canvas.create_line(x, grid_top, x, grid_top + grid_h, fill=COLOR_WEEK_GRID_LINE)

        # --- the blocks themselves
        for i, d in enumerate(dates):
            iso = d.isoformat()
            timed = []
            for occ in occurrences.get(iso, []):
                sp = occurrence_span(occ)
                if sp is not None:
                    timed.append((sp[0], sp[1], occ))
            col_x1 = WEEK_VIEW_GUTTER_WIDTH + i * col_w
            for start, end, occ, col_i, col_n in layout_overlapping_blocks(timed):
                label, chip_bg, chip_fg = CATEGORY_STYLES.get(
                    occ["category"], ("?", "#999999", "#ffffff"))
                inner_w = (col_w - 4) / col_n
                x1 = col_x1 + 2 + col_i * inner_w
                x2 = x1 + inner_w - 2
                y1 = y_for(start)
                y2 = max(y_for(end), y1 + WEEK_VIEW_MIN_BLOCK_HEIGHT)
                canvas.create_rectangle(x1, y1, x2, y2, fill=chip_bg,
                                        outline=COLOR_BG_PANEL, width=1)
                canvas.create_text(x1 + 4, y1 + 3, anchor="nw", fill=chip_fg, font=FONT_TINY,
                                   width=max(int(x2 - x1 - 8), 20),
                                   text=self._week_block_text(occ, x2 - x1 - 8,
                                                              one_line=(y2 - y1) < 30))
                self._week_blocks.append((x1, y1, x2, y2, d, occ))

        # "You are here": a thin line across today's column at the current
        # time, so a glance at the timetable answers "what's next?" without
        # counting hour rows. Redrawn on its own once a minute (see
        # _tick_now_line) - the grid itself is never redrawn for it.
        self._week_now_geom = None
        if dates[0] <= today <= dates[-1]:
            column = next(((cx1, cx2) for cx1, cx2, d in self._week_day_columns if d == today), None)
            if column is not None:
                self._week_now_geom = (canvas, column[0], column[1], grid_top,
                                       start_hour, end_hour)
                self._draw_now_line(*self._week_now_geom)

        total_h = grid_top + grid_h + 8
        canvas.configure(scrollregion=(0, 0, width, total_h))

    @staticmethod
    def _draw_now_line(canvas, x1, x2, grid_top, start_hour, end_hour):
        """(Re)draw the current-time marker on a time grid. Everything it
        draws carries the "now_line" tag, so refreshing it is a delete of
        that tag plus three small items - no flicker, and nothing else on
        the canvas is touched. Draws nothing when the clock is outside the
        hours the grid covers."""
        canvas.delete("now_line")
        now = datetime.datetime.now()
        minute = now.hour * 60 + now.minute
        if not (start_hour * 60 <= minute <= end_hour * 60):
            return None
        y = grid_top + (minute - start_hour * 60) / 60.0 * WEEK_VIEW_HOUR_HEIGHT
        canvas.create_line(x1, y, x2, y, fill=COLOR_NOW_LINE, width=2, tags="now_line")
        canvas.create_oval(x1 - 3, y - 3, x1 + 3, y + 3, fill=COLOR_NOW_LINE,
                           outline="", tags="now_line")
        canvas.create_text(x2 - 3, y - 7, anchor="e", text=now.strftime("%H:%M"),
                           fill=COLOR_NOW_LINE, font=FONT_TINY, tags="now_line")
        return y

    def _tick_now_line(self):
        """Move the current-time marker along, once a minute, without
        rebuilding either grid."""
        for geometry in (getattr(self, "_week_now_geom", None), getattr(self, "_day_now_geom", None)):
            if geometry is None:
                continue
            try:
                if geometry[0].winfo_exists():
                    self._draw_now_line(*geometry)
            except Exception:
                pass
        self._now_after_id = self.root.after(NOW_LINE_TICK_MS, self._tick_now_line)

    @staticmethod
    def _week_block_text(occ, pixel_width, one_line=False):
        time_part = occ.get("start", "")
        if occ.get("end"):
            time_part = f"{time_part}-{occ['end']}"
        title = occ.get("title", "") or CATEGORY_STYLES.get(occ.get("category"), ("", "", ""))[0]
        if one_line or pixel_width < 90:
            return f"{time_part} {title}".strip()
        return f"{time_part}\n{title}".strip()

    def _week_hit_test(self, x, y):
        for x1, y1, x2, y2, date_obj, occ in reversed(self._week_blocks):
            if x1 <= x <= x2 and y1 <= y <= y2:
                return date_obj, occ
        return None, None

    def _week_on_double_click(self, event):
        canvas = self.week_canvas
        x, y = canvas.canvasx(event.x), canvas.canvasy(event.y)
        date_obj, occ = self._week_hit_test(x, y)
        if occ is not None:
            self._open_editor_for_occurrence(occ)
            return
        # Empty space: start a new entry on that day, at the clicked time
        # rounded down to the half hour.
        for x1, x2, d in self._week_day_columns:
            if x1 <= x <= x2:
                minute = int(self._week_start_hour * 60 +
                             (y - self._week_grid_top_px) / WEEK_VIEW_HOUR_HEIGHT * 60)
                if minute < 0:
                    return
                minute -= minute % 30
                self._jump_to_list_add(d, None)
                self.cal_start.delete(0, "end")
                self.cal_start.insert(0, f"{minute // 60:02d}:{minute % 60:02d}")
                self.cal_end.delete(0, "end")
                end_minute = min(minute + 60, 24 * 60 - 1)
                self.cal_end.insert(0, f"{end_minute // 60:02d}:{end_minute % 60:02d}")
                return

    def _open_editor_for_occurrence(self, occ):
        """Double-clicking a block opens the editor for whatever produced
        it - the one-off entry, the recurring slot, or the override."""
        kind = occ.get("source_kind")
        if kind == "event":
            eid = occ.get("source_id")
            if self.tree_calendar.exists(eid):
                self.tree_calendar.selection_set(eid)
                self._edit_calendar_event()
            return
        if kind == "override":
            index = occ.get("source_id", -1)
            children = self.tree_overrides.get_children()
            if 0 <= index < len(children):
                self.notebook.select(self.tab_base_schedule)
                self.tree_overrides.selection_set(children[index])
                self._edit_override()
            return
        if kind == "row":
            key, row_id = occ.get("source_key"), occ.get("source_id")
            if key == "lesson":
                for item in self.tree_base.get_children():
                    if self.base_schedule[self.tree_base.index(item)].get("id") == row_id:
                        self.notebook.select(self.tab_base_schedule)
                        self.tree_base.selection_set(item)
                        self._edit_base_slot()
                        return
                return
            tree = self.family_trees.get(key)
            editor = self.family_editors.get(key)
            if tree is None or editor is None:
                return
            rows = self.personal_schedules.get(key, [])
            for item in tree.get_children():
                index = tree.index(item)
                if index < len(rows) and rows[index].get("id") == row_id:
                    self.notebook.select(self.tab_family)
                    tree.selection_set(item)
                    editor()
                    return

    # ---------------- Drag-to-move/resize (DEL 08f) ----------------
    # The last piece of master ToDo #1. Shared groundwork used by both the
    # Week View (this section) and the Day View (its own section below):
    # which occurrences are even draggable, turning a drop into the right
    # underlying change, and the quarter-hour snapping both grids use.

    @staticmethod
    def _occ_is_draggable(occ):
        """A one-off List View entry or a recurring schedule slot can be
        dragged; so can an occurrence that was already moved once (drag it
        again to fine-tune where it landed). A cancelled slot or a plain
        note has nothing sensible to drag it *to*, so those are left
        double-click-only."""
        kind = occ.get("source_kind")
        if kind in ("event", "row"):
            return True
        if kind == "override":
            return occ.get("category") == "moved"
        return False

    @staticmethod
    def _snap_minutes(minute):
        return int(round(minute / WEEK_VIEW_DRAG_SNAP_MINUTES)) * WEEK_VIEW_DRAG_SNAP_MINUTES

    def _apply_occurrence_drag(self, occ, orig_date, new_date, new_start_min, new_end_min):
        """Write a dropped drag back to whatever actually produced the
        occurrence (see _open_editor_for_occurrence for the same
        source_kind switch used to *open* a block instead of *move* it):
        a one-off entry is edited directly; a recurring row is left alone
        and gets a new Move override instead (exactly what dragging one
        by hand in the Base Schedule / Family Schedules override form
        already does - see _add_override), since editing the row itself
        would shift every future week, not just this one; an occurrence
        that was already a Move override gets that same override's
        new_date/new_start/new_end updated in place, so re-dragging an
        already-moved block fine-tunes it rather than stacking up a
        second override on top of the first."""
        new_start = minutes_to_hhmm(new_start_min)
        new_end = minutes_to_hhmm(new_end_min, allow_24=True)
        kind = occ.get("source_kind")

        if kind == "event":
            eid = occ.get("source_id")
            ev = next((e for e in self.calendar_events if e.get("id") == eid), None)
            if ev is None:
                return
            changed_time = (ev.get("date") != new_date.isoformat()
                            or ev.get("start") != new_start or ev.get("end") != new_end)
            ev["date"], ev["start"], ev["end"] = new_date.isoformat(), new_start, new_end
            if changed_time:      # dropped at a new date/time - old fired/dismissed state is stale
                self.alarm_state.pop(eid, None)
                save_json_dict(ALARM_STATE_PATH, self.alarm_state)
            save_json_list(EVENTS_PATH, self.calendar_events)
            self._reload_tree_calendar()
            self._refresh_contact_link_choices()   # its label in "Linked event" may have changed

        elif kind == "row":
            category = occ.get("source_key", "lesson")
            override = {
                "target_date": orig_date.isoformat(),
                "category": category,
                "weekday": WEEKDAYS[orig_date.weekday()],
                "slot_start": occ.get("start", ""), "slot_end": occ.get("end", ""),
                "action": "move",
                "new_date": new_date.isoformat(),
                "new_start": new_start, "new_end": new_end,
                "note": "",
            }
            self.temp_overrides.append(override)
            save_json_list(OVERRIDES_PATH, self.temp_overrides)
            # The occurrence now happens at a different time, so whatever
            # "already reminded / already dismissed" state it had belongs
            # to a time that no longer exists (see
            # _purge_alarm_state_for_override for why a same-day move
            # would otherwise go unremindered).
            self._purge_alarm_state_for_override(override, orig_date)
            self._reload_tree_overrides()

        elif kind == "override":
            index = occ.get("source_id", -1)
            if not (0 <= index < len(self.temp_overrides)):
                return
            ov = self.temp_overrides[index]
            old_new_date = ov.get("new_date", "")
            ov["new_date"], ov["new_start"], ov["new_end"] = new_date.isoformat(), new_start, new_end
            save_json_list(OVERRIDES_PATH, self.temp_overrides)
            self._purge_alarm_state_for_override(ov, old_new_date)
            self._reload_tree_overrides()
        else:
            return

        # The Week View and Day View draw from the same occurrence data as
        # the Month View, so one refresh keeps all three in sync no matter
        # which grid the drag happened on (see _refresh_month_view).
        self._refresh_month_view()
        show_auto_popup(self.root, f"Moved to {new_date.strftime('%a %d %b')}, {new_start}.")

    # ---- Week View drag ----

    def _week_block_at(self, x, y):
        """Like _week_hit_test, but returns the exact block rectangle too
        (needed to tell a resize-grab on the bottom edge from a move-grab
        anywhere else in the same block)."""
        for x1, y1, x2, y2, date_obj, occ in reversed(self._week_blocks):
            if x1 <= x <= x2 and y1 <= y <= y2:
                return x1, y1, x2, y2, date_obj, occ
        return None

    def _week_minute_for_y(self, y):
        return self._week_start_hour * 60 + (y - self._week_grid_top_px) / WEEK_VIEW_HOUR_HEIGHT * 60

    def _week_on_press(self, event):
        canvas = self.week_canvas
        x, y = canvas.canvasx(event.x), canvas.canvasy(event.y)
        hit = self._week_block_at(x, y)
        self._drag_state = None
        if hit is None:
            return
        x1, y1, x2, y2, date_obj, occ = hit
        span = occurrence_span(occ)
        # Untimed (all-day strip) chips have no real start/end to drag, and
        # some occurrence kinds (cancelled/note) aren't draggable at all.
        if span is None or not self._occ_is_draggable(occ):
            return
        near_bottom_edge = (y2 - y) <= WEEK_VIEW_DRAG_EDGE_PX and (y2 - y1) > 2 * WEEK_VIEW_DRAG_EDGE_PX
        self._drag_state = {
            "view": "week", "mode": "resize" if near_bottom_edge else "move",
            "occ": occ, "orig_date": date_obj,
            "orig_start": span[0], "orig_end": span[1],
            "block_x1": x1, "block_x2": x2,
            "press_x": x, "press_y": y, "moved": False,
            "preview_date": date_obj, "preview_start": span[0], "preview_end": span[1],
        }

    def _week_on_drag_motion(self, event):
        st = self._drag_state
        if st is None or st["view"] != "week":
            return
        canvas = self.week_canvas
        x, y = canvas.canvasx(event.x), canvas.canvasy(event.y)
        if not st["moved"] and (abs(x - st["press_x"]) > WEEK_VIEW_DRAG_THRESHOLD_PX
                                or abs(y - st["press_y"]) > WEEK_VIEW_DRAG_THRESHOLD_PX):
            st["moved"] = True
        if not st["moved"]:
            return
        duration = st["orig_end"] - st["orig_start"]
        if st["mode"] == "resize":
            new_start, new_date = st["orig_start"], st["orig_date"]
            new_end = self._snap_minutes(self._week_minute_for_y(y))
            new_end = max(new_end, new_start + WEEK_VIEW_DRAG_SNAP_MINUTES)
            new_end = min(new_end, 24 * 60)
        else:
            delta_min = self._snap_minutes((y - st["press_y"]) / WEEK_VIEW_HOUR_HEIGHT * 60)
            new_start = st["orig_start"] + delta_min
            if new_start < 0:
                new_start = 0
            if new_start + duration > 24 * 60:
                new_start = 24 * 60 - duration
            new_end = new_start + duration
            new_date = st["orig_date"]
            for cx1, cx2, d in self._week_day_columns:
                if cx1 <= x <= cx2:
                    new_date = d
                    break
        st["preview_date"], st["preview_start"], st["preview_end"] = new_date, new_start, new_end
        self._week_draw_drag_ghost(new_date, new_start, new_end)
        canvas.configure(cursor="sb_v_double_arrow" if st["mode"] == "resize" else "fleur")

    def _week_draw_drag_ghost(self, date_obj, start_min, end_min):
        canvas = self.week_canvas
        canvas.delete("drag_ghost")
        col = next(((cx1, cx2) for cx1, cx2, d in self._week_day_columns if d == date_obj), None)
        if col is None:
            return
        x1, x2 = col[0] + 2, col[1] - 2
        y1 = self._week_grid_top_px + (start_min - self._week_start_hour * 60) / 60.0 * WEEK_VIEW_HOUR_HEIGHT
        y2 = self._week_grid_top_px + (end_min - self._week_start_hour * 60) / 60.0 * WEEK_VIEW_HOUR_HEIGHT
        y2 = max(y2, y1 + WEEK_VIEW_MIN_BLOCK_HEIGHT)
        canvas.create_rectangle(x1, y1, x2, y2, outline=COLOR_TODAY_OUTLINE, width=2,
                                dash=(4, 2), tags="drag_ghost")
        label = f"{minutes_to_hhmm(start_min)}-{minutes_to_hhmm(end_min, allow_24=True)}"
        canvas.create_text((x1 + x2) / 2, max(y1 - 9, 8), text=label, fill=COLOR_TODAY_OUTLINE,
                           font=FONT_SMALL, tags="drag_ghost")

    def _week_on_release(self, _event):
        st = self._drag_state
        self._drag_state = None
        if st is None or st["view"] != "week":
            return
        self.week_canvas.delete("drag_ghost")
        self.week_canvas.configure(cursor="")
        if not st["moved"]:
            return   # just a click (or the first half of a double-click) - nothing to do
        new_date, new_start, new_end = st["preview_date"], st["preview_start"], st["preview_end"]
        if new_date == st["orig_date"] and new_start == st["orig_start"] and new_end == st["orig_end"]:
            return   # dragged and released back on its own original slot
        self._apply_occurrence_drag(st["occ"], st["orig_date"], new_date, new_start, new_end)

    def _week_on_hover_motion(self, event):
        if self._drag_state is not None:
            return   # a real drag is in progress - _week_on_drag_motion owns the cursor
        canvas = self.week_canvas
        x, y = canvas.canvasx(event.x), canvas.canvasy(event.y)
        hit = self._week_block_at(x, y)
        if hit is None or occurrence_span(hit[5]) is None or not self._occ_is_draggable(hit[5]):
            canvas.configure(cursor="")
            return
        x1, y1, x2, y2, _d, _occ = hit
        near_bottom_edge = (y2 - y) <= WEEK_VIEW_DRAG_EDGE_PX and (y2 - y1) > 2 * WEEK_VIEW_DRAG_EDGE_PX
        canvas.configure(cursor="sb_v_double_arrow" if near_bottom_edge else "fleur")

    def _show_day_popup(self, date_obj, day_occurrences):
        top = tk.Toplevel(self.root)
        top.title(date_obj.strftime("%A, %d %B %Y"))
        top.configure(bg=COLOR_BG_PANEL)
        top.transient(self.root)
        top.grab_set()
        top.bind("<Escape>", lambda _e: top.destroy())

        tk.Label(top, text=date_obj.strftime("%A, %d %B %Y"), bg=COLOR_BG_PANEL,
                 fg=COLOR_BG_HEADER, font=("Segoe UI", 13, "bold")).pack(padx=16, pady=(14, 8))

        if not day_occurrences:
            tk.Label(top, text="Nothing scheduled.", bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM,
                     font=FONT_MAIN).pack(padx=16, pady=(0, 10))
        else:
            editable = False
            for occ in day_occurrences:
                label, chip_bg, chip_fg = CATEGORY_STYLES.get(occ["category"], ("?", "#999", "#fff"))
                row = tk.Frame(top, bg=COLOR_BG_PANEL)
                row.pack(fill="x", padx=16, pady=2)
                tk.Label(row, text=label, bg=chip_bg, fg=chip_fg, font=FONT_TINY,
                         padx=6, pady=2).pack(side="left")
                time_str = f"{occ.get('start','')}-{occ.get('end','')}".strip("-")
                title_str = f"  {time_str}  {occ.get('title','')}".rstrip()
                tk.Label(row, text=title_str, bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                         font=FONT_MAIN).pack(side="left", padx=(8, 0))
                # Double-click a line to edit whatever produced it - the same
                # dispatch the Week View uses, so the Month View gets editing
                # too (its own cells can't take a double-click: the first
                # click has already opened this popup). Safe here because a
                # single click on these rows does nothing.
                if occ.get("source_kind"):
                    editable = True
                    row.configure(cursor="hand2")
                    for widget in (row, *row.winfo_children()):
                        widget.configure(cursor="hand2")
                        widget.bind("<Double-Button-1>",
                                    lambda _e, o=occ: self._edit_from_day_popup(o, top))
                # A recurring row's title *is* its note, so printing both just
                # said everything twice ("Anna - maths" / "Anna - maths").
                if occ.get("note") and occ["note"] != occ.get("title"):
                    tk.Label(top, text=occ["note"], bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM,
                             font=FONT_SMALL, wraplength=340, justify="left").pack(
                        anchor="w", padx=40, pady=(0, 4))
            if editable:
                tk.Label(top, text="(double-click a line to edit it)", bg=COLOR_BG_PANEL,
                         fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(anchor="w", padx=16, pady=(6, 0))

        btn_row = tk.Frame(top, bg=COLOR_BG_PANEL)
        btn_row.pack(fill="x", padx=16, pady=(10, 14))
        styled_button(
            btn_row, "Add entry for this date", lambda: self._jump_to_list_add(date_obj, top),
            COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG,
        ).pack(side="left")
        styled_button(
            btn_row, "Open Day View", lambda: self._open_day_view(date_obj, top),
            COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG,
        ).pack(side="left", padx=8)
        styled_button(btn_row, "Close", top.destroy, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        _center_over(top, self.root)

    def _edit_from_day_popup(self, occ, popup):
        # The popup holds a grab, so it has to go before the editor opens -
        # otherwise the edit dialog would be unclickable behind it.
        popup.destroy()
        self._open_editor_for_occurrence(occ)

    def _jump_to_list_add(self, date_obj, popup):
        if popup is not None:      # called with None from the Week View
            popup.destroy()
        self.calendar_sub_notebook.select(self.tab_list_view)
        self.cal_date.delete(0, "end")
        self.cal_date.insert(0, date_obj.isoformat())
        self.cal_title.focus_set()

    def _open_day_view(self, date_obj, popup=None):
        """Zoom into a single date - reached from the "Open Day View"
        button in the shared day popup (DEL 08d), itself opened from
        either a Month View cell or a Week View day header, so both grids
        get this for free."""
        if popup is not None:
            popup.destroy()
        self.day_view_date = date_obj
        self.calendar_sub_notebook.select(self.tab_day_view)
        self._refresh_day_view()

    # ---------------- Tab: Calendar -> Day View (DEL 08e) ----------------
    # The single-day zoom the master ToDo #1 still listed as missing: same
    # time-grid drawing approach as the Week View (DEL 08d) - hour lines,
    # a block whose height is its real duration, overlapping items tiled
    # side by side, untimed ones in an all-day strip - just one column
    # instead of seven, so a busy day is easier to read at a glance than
    # squinting at its Week View sliver. Reads the exact same occurrence
    # data (generate_occurrences_for_dates) as Month View, Week View and
    # the exports, so all four can never disagree with each other.
    #
    # Reached either from its own tab, or by zooming in from the "Open Day
    # View" button in the day popup that a Month View cell or a Week View
    # day header already opens (_open_day_view above) - so no new entry
    # point had to be invented, the existing one just grew a button.
    #
    # DONE (last piece of master ToDo #1, DEL 08f): dragging a block to
    # move or resize it directly on this grid (and the Week View one) -
    # see that section below for the drag handlers themselves, and
    # _apply_occurrence_drag for how a drop is turned into a saved change.

    def _build_calendar_day_view(self, parent):
        nav = tk.Frame(parent, bg=COLOR_BG_MAIN)
        nav.pack(fill="x", padx=4, pady=(4, 2))
        styled_button(nav, "< Prev day", lambda: self._day_step(-1),
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left")
        styled_button(nav, "Today", self._day_today,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(nav, "Next day >", lambda: self._day_step(1),
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left")
        self.day_title_lbl = tk.Label(nav, text="", bg=COLOR_BG_MAIN, fg=COLOR_TEXT_MAIN,
                                       font=("Segoe UI", 13, "bold"))
        self.day_title_lbl.pack(side="left", padx=18)

        layers = tk.Frame(parent, bg=COLOR_BG_MAIN)
        layers.pack(fill="x", padx=4, pady=(0, 4))
        tk.Label(layers, text="Show:", bg=COLOR_BG_MAIN, font=FONT_MAIN).pack(side="left")
        # Same shared BooleanVars as Month/Week View - one set of layer
        # choices for the whole Calendar tab.
        self.day_layer_box = tk.Frame(layers, bg=COLOR_BG_MAIN)
        self.day_layer_box.pack(side="left")
        tk.Label(layers, text="(double-click a block to edit it, drag it to move it or its "
                              "bottom edge to resize it, or double-click empty space to add "
                              "an entry at that time)",
                 bg=COLOR_BG_MAIN, fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left", padx=(4, 0))

        holder = tk.Frame(parent, bg=COLOR_BG_PANEL)
        holder.pack(fill="both", expand=True, padx=4, pady=(0, 6))
        vsb = ttk.Scrollbar(holder, orient="vertical")
        vsb.pack(side="right", fill="y")
        self.day_canvas = tk.Canvas(holder, bg=COLOR_BG_PANEL, highlightthickness=0,
                                    yscrollcommand=vsb.set)
        self.day_canvas.pack(side="left", fill="both", expand=True)
        vsb.configure(command=self.day_canvas.yview)

        self.day_canvas.bind("<Configure>", self._day_on_resize)
        self.day_canvas.bind("<Enter>", lambda _e: self.day_canvas.bind_all(
            "<MouseWheel>", self._day_on_wheel))
        self.day_canvas.bind("<Leave>", lambda _e: self.day_canvas.unbind_all("<MouseWheel>"))
        self.day_canvas.bind("<Double-Button-1>", self._day_on_double_click)
        # Drag-to-move/resize (DEL 08f) - see _week_on_press's docstring
        # for how a genuine drag is told apart from a double-click; the
        # Day View only ever has one column, so a drag only ever changes
        # the time, never the date.
        self.day_canvas.bind("<ButtonPress-1>", self._day_on_press)
        self.day_canvas.bind("<B1-Motion>", self._day_on_drag_motion)
        self.day_canvas.bind("<ButtonRelease-1>", self._day_on_release)
        self.day_canvas.bind("<Motion>", self._day_on_hover_motion)

        self._day_last_width = 0
        self._day_blocks = []   # [(x1, y1, x2, y2, occurrence), ...] - for hit-testing clicks
        self._rebuild_day_layer_row()
        self._refresh_day_view()

    def _rebuild_day_layer_row(self):
        if not hasattr(self, "day_layer_box"):
            return
        for w in self.day_layer_box.winfo_children():
            w.destroy()
        for d in SCHEDULE_DEFS:
            key = d["key"]
            if key not in self.month_layer_vars:
                continue
            tk.Checkbutton(
                self.day_layer_box, text=d["name"], variable=self.month_layer_vars[key],
                bg=COLOR_BG_MAIN, activebackground=COLOR_BG_MAIN, selectcolor=d["color"],
                font=FONT_SMALL, command=self._refresh_month_view,
            ).pack(side="left", padx=(0, 10))

    def _day_on_wheel(self, event):
        self.day_canvas.yview_scroll(-1 if event.delta > 0 else 1, "units")

    def _day_on_resize(self, event):
        if abs(event.width - self._day_last_width) > 2:
            self._day_last_width = event.width
            self._refresh_day_view()

    def _day_step(self, days):
        self.day_view_date += datetime.timedelta(days=days)
        self._refresh_day_view()

    def _day_today(self):
        self.day_view_date = datetime.date.today()
        self._refresh_day_view()

    def _refresh_day_view(self):
        if not hasattr(self, "day_canvas"):
            return      # Day View not built yet
        canvas = self.day_canvas
        canvas.delete("all")
        self._day_blocks = []

        d = self.day_view_date
        today = datetime.date.today()
        self.day_title_lbl.configure(
            text=("Today - " if d == today else "") + d.strftime("%A, %d %B %Y"))

        layers = {key: var.get() for key, var in self.month_layer_vars.items()}
        occurrences = generate_occurrences_for_dates(
            [d], self.base_schedule, self.temp_overrides, self.personal_schedules,
            self.calendar_events, layers,
        )
        day_occ = occurrences.get(d.isoformat(), [])
        start_hour, end_hour = week_view_hour_range(occurrences, [d])
        self._day_start_hour = start_hour

        width = max(canvas.winfo_width(), 360)
        # A single wide column - the left gutter holds the hour labels
        # exactly like the Week View, the rest of the width is the block
        # area (day_view_date only, so no per-column division needed).
        untimed = [o for o in day_occ if occurrence_span(o) is None]
        allday_rows = len(untimed)
        allday_h = allday_rows * 20 + (6 if allday_rows else 0)
        grid_top = allday_h + 4
        self._day_grid_top_px = grid_top
        grid_h = (end_hour - start_hour) * WEEK_VIEW_HOUR_HEIGHT

        def y_for(minute):
            return grid_top + (minute - start_hour * 60) / 60.0 * WEEK_VIEW_HOUR_HEIGHT

        # --- all-day strip
        for row_i, occ in enumerate(untimed):
            _label, chip_bg, chip_fg = CATEGORY_STYLES.get(
                occ["category"], ("?", "#999999", "#ffffff"))
            ay1 = 4 + row_i * 20
            canvas.create_rectangle(WEEK_VIEW_GUTTER_WIDTH, ay1, width, ay1 + 18,
                                    fill=chip_bg, outline="")
            canvas.create_text(WEEK_VIEW_GUTTER_WIDTH + 6, ay1 + 9, anchor="w", fill=chip_fg,
                               font=FONT_SMALL, width=max(int(width - WEEK_VIEW_GUTTER_WIDTH - 12), 20),
                               text=self._week_block_text(occ, width - WEEK_VIEW_GUTTER_WIDTH - 12,
                                                          one_line=True))
            self._day_blocks.append((WEEK_VIEW_GUTTER_WIDTH, ay1, width, ay1 + 18, occ))

        # --- hour lines + labels
        for hour in range(start_hour, end_hour + 1):
            y = y_for(hour * 60)
            canvas.create_line(WEEK_VIEW_GUTTER_WIDTH, y, width, y, fill=COLOR_WEEK_GRID_LINE)
            if hour < end_hour:
                canvas.create_line(WEEK_VIEW_GUTTER_WIDTH, y + WEEK_VIEW_HOUR_HEIGHT / 2,
                                   width, y + WEEK_VIEW_HOUR_HEIGHT / 2,
                                   fill=COLOR_WEEK_HALFHOUR_LINE)
                canvas.create_text(WEEK_VIEW_GUTTER_WIDTH - 8, y + 2, anchor="ne",
                                   text=f"{hour:02d}:00", fill=COLOR_TEXT_DIM, font=FONT_SMALL)
        canvas.create_line(WEEK_VIEW_GUTTER_WIDTH, grid_top, WEEK_VIEW_GUTTER_WIDTH,
                           grid_top + grid_h, fill=COLOR_WEEK_GRID_LINE)

        if d == today:
            canvas.create_rectangle(WEEK_VIEW_GUTTER_WIDTH, grid_top, width, grid_top + grid_h,
                                    fill=COLOR_WEEK_TODAY_COLUMN, outline="")
            # redraw the hour grid lines over the tint so they stay visible
            for hour in range(start_hour, end_hour + 1):
                y = y_for(hour * 60)
                canvas.create_line(WEEK_VIEW_GUTTER_WIDTH, y, width, y, fill=COLOR_WEEK_GRID_LINE)

        # --- the blocks themselves, wide since there's only one column
        timed = []
        for occ in day_occ:
            sp = occurrence_span(occ)
            if sp is not None:
                timed.append((sp[0], sp[1], occ))
        for start, end, occ, col_i, col_n in layout_overlapping_blocks(timed):
            label, chip_bg, chip_fg = CATEGORY_STYLES.get(
                occ["category"], ("?", "#999999", "#ffffff"))
            inner_w = (width - WEEK_VIEW_GUTTER_WIDTH - 6) / col_n
            x1 = WEEK_VIEW_GUTTER_WIDTH + 3 + col_i * inner_w
            x2 = x1 + inner_w - 3
            y1 = y_for(start)
            y2 = max(y_for(end), y1 + WEEK_VIEW_MIN_BLOCK_HEIGHT)
            canvas.create_rectangle(x1, y1, x2, y2, fill=chip_bg,
                                    outline=COLOR_BG_PANEL, width=1)
            canvas.create_text(x1 + 6, y1 + 4, anchor="nw", fill=chip_fg, font=FONT_MAIN,
                               width=max(int(x2 - x1 - 12), 30),
                               text=self._week_block_text(occ, x2 - x1 - 12,
                                                          one_line=(y2 - y1) < 34))
            self._day_blocks.append((x1, y1, x2, y2, occ))

        # Same current-time marker as the Week View, full width here since
        # this grid only shows one day.
        self._day_now_geom = None
        if d == today:
            self._day_now_geom = (canvas, WEEK_VIEW_GUTTER_WIDTH, width, grid_top,
                                  start_hour, end_hour)
            self._draw_now_line(*self._day_now_geom)

        total_h = grid_top + grid_h + 8
        canvas.configure(scrollregion=(0, 0, width, total_h))

    def _day_hit_test(self, x, y):
        for x1, y1, x2, y2, occ in reversed(self._day_blocks):
            if x1 <= x <= x2 and y1 <= y <= y2:
                return occ
        return None

    def _day_on_double_click(self, event):
        canvas = self.day_canvas
        x, y = canvas.canvasx(event.x), canvas.canvasy(event.y)
        occ = self._day_hit_test(x, y)
        if occ is not None:
            self._open_editor_for_occurrence(occ)
            return
        if x < WEEK_VIEW_GUTTER_WIDTH:
            return   # clicked in the hour-label gutter, not the grid itself
        minute = int(self._day_start_hour * 60 +
                     (y - self._day_grid_top_px) / WEEK_VIEW_HOUR_HEIGHT * 60)
        if minute < 0:
            return
        minute -= minute % 30
        self._jump_to_list_add(self.day_view_date, None)
        self.cal_start.delete(0, "end")
        self.cal_start.insert(0, f"{minute // 60:02d}:{minute % 60:02d}")
        self.cal_end.delete(0, "end")
        end_minute = min(minute + 60, 24 * 60 - 1)
        self.cal_end.insert(0, f"{end_minute // 60:02d}:{end_minute % 60:02d}")

    # ---- Day View drag (DEL 08f) ----
    # Same approach as the Week View's, minus the day-column lookup: the
    # Day View only ever shows self.day_view_date, so a drag can only ever
    # change the time, never which day it lands on.

    def _day_block_at(self, x, y):
        for x1, y1, x2, y2, occ in reversed(self._day_blocks):
            if x1 <= x <= x2 and y1 <= y <= y2:
                return x1, y1, x2, y2, occ
        return None

    def _day_minute_for_y(self, y):
        return self._day_start_hour * 60 + (y - self._day_grid_top_px) / WEEK_VIEW_HOUR_HEIGHT * 60

    def _day_on_press(self, event):
        canvas = self.day_canvas
        x, y = canvas.canvasx(event.x), canvas.canvasy(event.y)
        hit = self._day_block_at(x, y)
        self._drag_state = None
        if hit is None:
            return
        x1, y1, x2, y2, occ = hit
        span = occurrence_span(occ)
        if span is None or not self._occ_is_draggable(occ):
            return
        near_bottom_edge = (y2 - y) <= WEEK_VIEW_DRAG_EDGE_PX and (y2 - y1) > 2 * WEEK_VIEW_DRAG_EDGE_PX
        self._drag_state = {
            "view": "day", "mode": "resize" if near_bottom_edge else "move",
            "occ": occ, "orig_date": self.day_view_date,
            "orig_start": span[0], "orig_end": span[1],
            "block_x1": x1, "block_x2": x2,
            "press_x": x, "press_y": y, "moved": False,
            "preview_start": span[0], "preview_end": span[1],
        }

    def _day_on_drag_motion(self, event):
        st = self._drag_state
        if st is None or st["view"] != "day":
            return
        canvas = self.day_canvas
        x, y = canvas.canvasx(event.x), canvas.canvasy(event.y)
        if not st["moved"] and (abs(x - st["press_x"]) > WEEK_VIEW_DRAG_THRESHOLD_PX
                                or abs(y - st["press_y"]) > WEEK_VIEW_DRAG_THRESHOLD_PX):
            st["moved"] = True
        if not st["moved"]:
            return
        duration = st["orig_end"] - st["orig_start"]
        if st["mode"] == "resize":
            new_start = st["orig_start"]
            new_end = self._snap_minutes(self._day_minute_for_y(y))
            new_end = max(new_end, new_start + WEEK_VIEW_DRAG_SNAP_MINUTES)
            new_end = min(new_end, 24 * 60)
        else:
            delta_min = self._snap_minutes((y - st["press_y"]) / WEEK_VIEW_HOUR_HEIGHT * 60)
            new_start = st["orig_start"] + delta_min
            if new_start < 0:
                new_start = 0
            if new_start + duration > 24 * 60:
                new_start = 24 * 60 - duration
            new_end = new_start + duration
        st["preview_start"], st["preview_end"] = new_start, new_end
        self._day_draw_drag_ghost(new_start, new_end, st["block_x1"], st["block_x2"])
        canvas.configure(cursor="sb_v_double_arrow" if st["mode"] == "resize" else "fleur")

    def _day_draw_drag_ghost(self, start_min, end_min, x1, x2):
        canvas = self.day_canvas
        canvas.delete("drag_ghost")
        y1 = self._day_grid_top_px + (start_min - self._day_start_hour * 60) / 60.0 * WEEK_VIEW_HOUR_HEIGHT
        y2 = self._day_grid_top_px + (end_min - self._day_start_hour * 60) / 60.0 * WEEK_VIEW_HOUR_HEIGHT
        y2 = max(y2, y1 + WEEK_VIEW_MIN_BLOCK_HEIGHT)
        canvas.create_rectangle(x1, y1, x2, y2, outline=COLOR_TODAY_OUTLINE, width=2,
                                dash=(4, 2), tags="drag_ghost")
        label = f"{minutes_to_hhmm(start_min)}-{minutes_to_hhmm(end_min, allow_24=True)}"
        canvas.create_text((x1 + x2) / 2, max(y1 - 9, 8), text=label, fill=COLOR_TODAY_OUTLINE,
                           font=FONT_SMALL, tags="drag_ghost")

    def _day_on_release(self, _event):
        st = self._drag_state
        self._drag_state = None
        if st is None or st["view"] != "day":
            return
        self.day_canvas.delete("drag_ghost")
        self.day_canvas.configure(cursor="")
        if not st["moved"]:
            return
        new_start, new_end = st["preview_start"], st["preview_end"]
        if new_start == st["orig_start"] and new_end == st["orig_end"]:
            return
        self._apply_occurrence_drag(st["occ"], st["orig_date"], st["orig_date"], new_start, new_end)

    def _day_on_hover_motion(self, event):
        if self._drag_state is not None:
            return
        canvas = self.day_canvas
        x, y = canvas.canvasx(event.x), canvas.canvasy(event.y)
        hit = self._day_block_at(x, y)
        if hit is None or occurrence_span(hit[4]) is None or not self._occ_is_draggable(hit[4]):
            canvas.configure(cursor="")
            return
        x1, y1, x2, y2, _occ = hit
        near_bottom_edge = (y2 - y) <= WEEK_VIEW_DRAG_EDGE_PX and (y2 - y1) > 2 * WEEK_VIEW_DRAG_EDGE_PX
        canvas.configure(cursor="sb_v_double_arrow" if near_bottom_edge else "fleur")

    # ---------------- Tab: Calendar -> List View ----------------
    def _build_calendar_list_view(self, parent):
        outer, inner = make_scrollable_frame(parent, bg=COLOR_BG_MAIN)
        outer.pack(fill="both", expand=True, padx=10, pady=10)

        # Same live search the Contacts tab has - after a year of lessons
        # this list is long, and there was no way to find anything in it.
        search_row = tk.Frame(inner, bg=COLOR_BG_MAIN)
        search_row.pack(fill="x", pady=(0, 6))
        tk.Label(search_row, text="Search:", bg=COLOR_BG_MAIN, font=FONT_MAIN).pack(side="left")
        self.calendar_search_var = tk.StringVar(value="")
        search_entry = make_entry(search_row, width=30, font=FONT_MAIN,
                                   textvariable=self.calendar_search_var)
        search_entry.pack(side="left", padx=(4, 8))
        search_entry.bind("<KeyRelease>", lambda _e: self._reload_tree_calendar())
        tk.Label(search_row, text="(matches date, time, title, note - or type 'today' / a "
                                  "weekday / a month)",
                 bg=COLOR_BG_MAIN, fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left")
        styled_button(search_row, "Clear", self._clear_calendar_search,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=(8, 0))
        self.calendar_count_lbl = tk.Label(search_row, text="", bg=COLOR_BG_MAIN,
                                            fg=COLOR_TEXT_DIM, font=FONT_TINY)
        self.calendar_count_lbl.pack(side="right")

        cols = ("date", "start", "end", "title", "lead", "repeat", "note")
        headers = ("Date", "Start", "End", "Title", "Warn before", "Repeat", "Note")
        self.tree_calendar = ttk.Treeview(inner, columns=cols, show="headings", height=10)
        for c, h in zip(cols, headers):
            self.tree_calendar.heading(c, text=h)
            self.tree_calendar.column(c, width=110 if c != "note" else 220, anchor="w")
        self.tree_calendar.pack(fill="x", expand=True, pady=(0, 10))

        form = tk.LabelFrame(inner, text="Add entry", bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                              font=FONT_MAIN, padx=10, pady=10)
        form.pack(fill="x", pady=(0, 10))

        r1 = tk.Frame(form, bg=COLOR_BG_PANEL)
        r1.pack(fill="x", pady=3)
        tk.Label(r1, text="Date (YYYY-MM-DD):", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.cal_date = make_entry(r1, width=12, font=FONT_MAIN)
        self.cal_date.insert(0, datetime.date.today().isoformat())
        self.cal_date.pack(side="left", padx=(4, 0))
        date_picker_button(r1, self.root, entry=self.cal_date,
                           title="Date for this entry").pack(side="left", padx=(2, 16))

        tk.Label(r1, text="Start (HH:MM):", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.cal_start = make_entry(r1, width=7, font=FONT_MAIN)
        self.cal_start.insert(0, "17:00")
        self.cal_start.pack(side="left", padx=(4, 16))

        tk.Label(r1, text="End (HH:MM):", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.cal_end = make_entry(r1, width=7, font=FONT_MAIN)
        self.cal_end.insert(0, "18:00")
        self.cal_end.pack(side="left", padx=(4, 0))

        r2 = tk.Frame(form, bg=COLOR_BG_PANEL)
        r2.pack(fill="x", pady=3)
        tk.Label(r2, text="Title:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.cal_title = make_entry(r2, width=30, font=FONT_MAIN)
        self.cal_title.pack(side="left", padx=(4, 16))

        tk.Label(r2, text="Warn before:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.cal_lead_var = tk.StringVar(value=ALARM_LEAD_CHOICES[0][0])
        lead_box = ttk.Combobox(
            r2, textvariable=self.cal_lead_var, state="readonly", width=16,
            values=[c[0] for c in ALARM_LEAD_CHOICES],
        )
        lead_box.pack(side="left", padx=(4, 16))
        lead_box.bind("<<ComboboxSelected>>", self._on_lead_changed)

        tk.Label(r2, text="Repeat reminder:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.cal_repeat_var = tk.StringVar(value="(no repeat)")
        self.repeat_box = ttk.Combobox(
            r2, textvariable=self.cal_repeat_var, state="readonly", width=16,
            values=["(no repeat)"],
        )
        self.repeat_box.pack(side="left", padx=(4, 0))

        r3 = tk.Frame(form, bg=COLOR_BG_PANEL)
        r3.pack(fill="x", pady=3)
        tk.Label(r3, text="Note:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left", anchor="n")
        self.cal_note = make_text(r3, width=60, height=2, font=FONT_MAIN)
        self.cal_note.pack(side="left", padx=(4, 0))

        btn_row = tk.Frame(inner, bg=COLOR_BG_MAIN)
        btn_row.pack(fill="x", pady=(0, 4))
        styled_button(btn_row, "Add entry (Enter)", self._add_calendar_event,
                      COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left")
        styled_button(btn_row, "Edit selected...", self._edit_calendar_event,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(btn_row, "Delete selected", self._delete_calendar_event,
                      COLOR_BTN_DANGER, COLOR_BTN_DANGER_FG).pack(side="left")

        self.tree_calendar.bind("<Double-Button-1>", lambda _e: self._edit_calendar_event())
        bind_enter_to(self.cal_title, self._add_calendar_event)

    def _on_lead_changed(self, _event=None):
        sync_repeat_choices_to_lead(self.cal_lead_var.get(), self.repeat_box, self.cal_repeat_var)

    def _add_calendar_event(self):
        date = self.cal_date.get().strip()
        start = self.cal_start.get().strip()
        end = self.cal_end.get().strip()
        title = self.cal_title.get().strip()
        note = self.cal_note.get("1.0", "end").strip()
        if not date or not title:
            messagebox.showwarning("Missing info", "Date and Title are required.", parent=self.root)
            return
        event = {
            "id": uuid.uuid4().hex,
            "date": date, "start": start, "end": end, "title": title,
            "lead": self.cal_lead_var.get(), "repeat": self.cal_repeat_var.get(),
            "note": note,
        }
        self.calendar_events.append(event)
        save_json_list(EVENTS_PATH, self.calendar_events)
        # Drop any active filter first - otherwise a brand-new entry that
        # doesn't match it would look like it was never added.
        self.calendar_search_var.set("")
        self._reload_tree_calendar()
        self._refresh_month_view()
        self._refresh_contact_link_choices()   # this event can now be picked in Contacts > "Linked event"
        self.cal_title.delete(0, "end")
        self.cal_note.delete("1.0", "end")
        show_auto_popup(self.root, "Entry added.")

    def _delete_calendar_event(self):
        sel = self.tree_calendar.selection()
        if not sel:
            return
        eid = sel[0]  # tree_calendar uses the event's own id as its iid (see below)
        self.calendar_events = [e for e in self.calendar_events if e.get("id") != eid]
        save_json_list(EVENTS_PATH, self.calendar_events)
        if eid in self.alarm_state:   # no point keeping reminder state for a deleted event
            del self.alarm_state[eid]
            save_json_dict(ALARM_STATE_PATH, self.alarm_state)
        self._reload_tree_calendar()
        self._refresh_month_view()
        self._refresh_contact_link_choices()   # any contact linked to this event now shows "(deleted)"

    def _clear_calendar_search(self):
        self.calendar_search_var.set("")
        self._reload_tree_calendar()

    @staticmethod
    def _calendar_search_haystack(ev):
        """Everything a List View row can be searched by. The weekday and
        month name of its date are folded in too, so "tuesday" or
        "october" find entries even though neither word is stored."""
        parts = [ev.get("date", ""), ev.get("start", ""), ev.get("end", ""),
                 ev.get("title", ""), ev.get("note", ""), ev.get("lead", ""),
                 ev.get("repeat", "")]
        d = safe_parse_date(ev.get("date", ""))
        if d is not None:
            parts += [d.strftime("%A"), d.strftime("%B"), str(d.day)]
            if d == datetime.date.today():
                parts.append("today")
        return " ".join(parts).lower()

    def _reload_tree_calendar(self):
        self.tree_calendar.delete(*self.tree_calendar.get_children())
        query = (self.calendar_search_var.get().strip().lower()
                 if hasattr(self, "calendar_search_var") else "")
        shown = 0
        for ev in sorted(self.calendar_events, key=lambda e: (e.get("date", ""), e.get("start", ""))):
            if query and query not in self._calendar_search_haystack(ev):
                continue
            shown += 1
            # iid = the event's own id, not the display position, so a
            # selection always maps back to the right event even though
            # this list is shown sorted by date rather than insertion order.
            self.tree_calendar.insert("", "end", iid=ev.get("id"), values=(
                ev.get("date", ""), ev.get("start", ""), ev.get("end", ""),
                ev.get("title", ""), ev.get("lead", ""), ev.get("repeat", ""),
                ev.get("note", "")[:60],
            ))

        if hasattr(self, "calendar_count_lbl"):
            total = len(self.calendar_events)
            self.calendar_count_lbl.configure(
                text=(f"{shown} of {total} shown" if query else
                      f"{total} entr{'y' if total == 1 else 'ies'}"))

        if not query:
            self._scroll_calendar_to_today()

    def _scroll_calendar_to_today(self):
        """Open the list where the useful end of it is. The rows are
        sorted oldest-first, so after a year of lessons the visible top of
        the list is ancient history and everything that hasn't happened
        yet is somewhere far below. Scroll to the first entry that is
        today or later (or, if every entry is in the past, to the last
        one). A row the user has selected wins over this - that means she
        just did something with it and shouldn't be dragged elsewhere."""
        if self.tree_calendar.selection():
            return
        children = self.tree_calendar.get_children()
        if not children:
            return
        today_iso = datetime.date.today().isoformat()
        for item in children:
            values = self.tree_calendar.item(item, "values")
            if values and str(values[0]) >= today_iso:
                self.tree_calendar.see(item)
                return
        self.tree_calendar.see(children[-1])

    # ---------------- Alarm engine ----------------
    # Fires reminders for Calendar > List View entries (the ones with a
    # "Warn before" / "Repeat reminder" configured). Runs on a repeating
    # Tk `after()` timer rather than a background thread - Tkinter isn't
    # thread-safe, so touching widgets from anywhere but the main loop is
    # asking for trouble, and a same-thread poll every
    # ALARM_CHECK_INTERVAL_MS is more than responsive enough for this.
    #
    # Base Schedule (recurring lessons) and Family Schedule entries now
    # carry their own lead/repeat fields too (see generate_recurring_
    # alarm_instances, DEL 07b) - the loop below handles those the same
    # way as one-off List View events, just from a different source list.
    def _check_alarms(self):
        now = datetime.datetime.now()
        state_changed = False

        # First tick after startup: say what was missed while the program
        # was closed, before going back to only looking forward.
        if not getattr(self, "_missed_checked", False):
            self._missed_checked = True
            try:
                self._report_missed_reminders(now)
            except Exception:
                pass      # a catch-up summary is never worth breaking the engine over

        # Midnight rollover: if the app was left open overnight, redraw the
        # Month View so "Today:" and the highlighted cell move on with it.
        if now.date() != getattr(self, "_last_seen_date", now.date()):
            self._last_seen_date = now.date()
            try:
                self._refresh_month_view()
            except Exception:
                pass

        for ev in self.calendar_events:
            eid = ev.get("id")
            if not eid:
                continue

            lead_seconds = dict(ALARM_LEAD_CHOICES).get(ev.get("lead", "None"))
            if not lead_seconds:
                continue  # "Warn before: None" - this event has no alarm configured

            dt = event_datetime(ev)
            if dt is None or now >= dt:
                continue  # unparsable date, or the event has already started/passed
            if now < dt - datetime.timedelta(seconds=lead_seconds):
                continue  # not inside the warning window yet

            entry = self.alarm_state.get(eid, {})
            if entry.get("dismissed"):
                continue

            repeat_seconds = ALARM_REPEAT_SECONDS.get(ev.get("repeat", "(no repeat)"))
            last_fired = entry.get("last_fired")
            due = False
            if not last_fired:
                due = True   # never fired - either brand new, or was overdue while app was closed
            elif repeat_seconds:
                try:
                    due = (now - datetime.datetime.fromisoformat(last_fired)).total_seconds() >= repeat_seconds
                except Exception:
                    due = True

            if due:
                entry["last_fired"] = now.isoformat()
                self.alarm_state[eid] = entry
                state_changed = True
                self._fire_alarm(ev, eid, dt)

        # --- recurring Base Schedule / Family Schedule occurrences -----
        # A rolling 9-day window is plenty: the longest "Warn before" lead
        # choice is 1 week, so anything further out can't be inside its
        # warning window yet anyway, and this list gets rebuilt fresh
        # every check so a newly-added/edited slot or override is picked
        # up within one poll interval without needing its own refresh call.
        today = datetime.date.today()
        window_dates = [today + datetime.timedelta(days=i) for i in range(9)]
        recurring_instances = generate_recurring_alarm_instances(
            window_dates, self.base_schedule, self.personal_schedules, self.temp_overrides
        )
        for inst in recurring_instances:
            key = inst["key"]
            lead_seconds = dict(ALARM_LEAD_CHOICES).get(inst.get("lead", "None"))
            if not lead_seconds:
                continue

            dt = event_datetime(inst)   # inst has "date"/"start" fields, same shape as a calendar event
            if dt is None or now >= dt:
                continue
            if now < dt - datetime.timedelta(seconds=lead_seconds):
                continue

            entry = self.alarm_state.get(key, {})
            if entry.get("dismissed"):
                continue

            repeat_seconds = ALARM_REPEAT_SECONDS.get(inst.get("repeat", "(no repeat)"))
            last_fired = entry.get("last_fired")
            due = False
            if not last_fired:
                due = True
            elif repeat_seconds:
                try:
                    due = (now - datetime.datetime.fromisoformat(last_fired)).total_seconds() >= repeat_seconds
                except Exception:
                    due = True

            if due:
                entry["last_fired"] = now.isoformat()
                self.alarm_state[key] = entry
                state_changed = True
                self._fire_alarm(inst, key, dt)   # inst looks enough like an "ev" dict to reuse this as-is

        if self._prune_old_alarm_state():
            state_changed = True
        if state_changed:
            save_json_dict(ALARM_STATE_PATH, self.alarm_state)

        self._alarm_after_id = self.root.after(ALARM_CHECK_INTERVAL_MS, self._check_alarms)

    def _report_missed_reminders(self, now):
        """One quiet summary window listing reminders that fell due while
        TutorCal was closed (see find_missed_reminders). Non-modal, like
        the reminder popup itself, and dismissing it marks every listed
        occurrence as handled so the same list doesn't greet her again at
        the next start."""
        window_dates = [now.date() - datetime.timedelta(days=1), now.date()]
        instances = generate_recurring_alarm_instances(
            window_dates, self.base_schedule, self.personal_schedules, self.temp_overrides)
        missed = find_missed_reminders(now, self.calendar_events, instances, self.alarm_state)
        if not missed:
            return

        top = tk.Toplevel(self.root)
        top.title("While TutorCal was closed")
        top.configure(bg=COLOR_BG_PANEL)
        top.resizable(False, False)
        top.bind("<Escape>", lambda _e: top.destroy())

        tk.Label(top, text="Reminders you didn't get", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                 font=("Segoe UI", 13, "bold")).pack(padx=18, pady=(16, 2))
        tk.Label(top, text="These came due while the program wasn't running.",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM, font=FONT_SMALL).pack(padx=18, pady=(0, 10))

        for _key, item, dt in missed[:12]:      # a longer list than this is a wall of text
            row = tk.Frame(top, bg=COLOR_BG_PANEL)
            row.pack(fill="x", padx=18, pady=1)
            tk.Label(row, text=dt.strftime("%a %d %b, %H:%M"), bg=COLOR_BG_PANEL,
                     fg=COLOR_TEXT_DIM, font=FONT_SMALL, width=18, anchor="w").pack(side="left")
            tk.Label(row, text=item.get("title", ""), bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                     font=FONT_MAIN, anchor="w").pack(side="left")
        if len(missed) > 12:
            tk.Label(top, text=f"...and {len(missed) - 12} more", bg=COLOR_BG_PANEL,
                     fg=COLOR_TEXT_DIM, font=FONT_SMALL).pack(padx=18, pady=(4, 0))

        def _acknowledge():
            for key, _item, _dt in missed:
                entry = self.alarm_state.get(key, {})
                entry["dismissed"] = True
                self.alarm_state[key] = entry
            save_json_dict(ALARM_STATE_PATH, self.alarm_state)
            top.destroy()

        styled_button(top, "Got it", _acknowledge, COLOR_BTN_ACCENT,
                      COLOR_BTN_ACCENT_FG).pack(pady=(12, 16))
        top.update_idletasks()
        _center_over(top, self.root)
        self._missed_popup = top      # kept reachable for the tests, and so it isn't GC'd early
        return top

    def _stop_alarm_loop(self):
        """Cancel the pending clock timers (the alarm poll and the
        current-time line), if any. Called on the way out so neither can
        fire into a half-destroyed window - and by tests that drive the
        reminder popup by hand and don't want the engine popping its own
        window into the middle of their assertions."""
        for attribute in ("_alarm_after_id", "_now_after_id", "_phone_after_id", "_phone_poll_id"):
            after_id = getattr(self, attribute, None)
            setattr(self, attribute, None)
            if after_id:
                try:
                    self.root.after_cancel(after_id)
                except Exception:
                    pass

    def _prune_old_alarm_state(self):
        """Recurring-slot alarm keys look like '<row id>:<date>' and a
        fresh one is produced every time that weekday comes around (see
        generate_recurring_alarm_instances), so old entries would
        otherwise just pile up in alarm_state.json forever. Drop any
        recurring-style key (identified by the ':' - one-off Calendar >
        List View event ids are plain uuid hex with no ':') whose date is
        more than a few days in the past; those events' own keys are
        already cleaned up individually when the event is deleted (see
        _delete_calendar_event), so they're left alone here. Returns True
        if anything was removed, so the caller knows to save."""
        cutoff = datetime.date.today() - datetime.timedelta(days=3)
        stale_keys = []
        for key in self.alarm_state:
            if ":" not in key:
                continue
            _row_id, _, date_part = key.rpartition(":")
            d = safe_parse_date(date_part)
            if d and d < cutoff:
                stale_keys.append(key)
        for key in stale_keys:
            del self.alarm_state[key]
        return bool(stale_keys)

    def _fire_alarm(self, ev, eid, event_dt):
        self._play_alarm_sound()
        self._show_alarm_popup(ev, eid, event_dt)
        self._send_os_notification_for(ev, event_dt)

    def _send_os_notification_for(self, ev, event_dt):
        """Additive native OS toast alongside the in-app popup above -
        see DEL 07f for why this can never block or replace it."""
        when = event_dt.strftime("%a %d %b, %H:%M") if (ev.get("start") or "").strip() \
            else event_dt.strftime("%a %d %b")
        title = (ev.get("title") or "Reminder").strip() or "Reminder"
        message = when
        if ev.get("note"):
            message = f"{when} - {ev['note']}"
        try:
            send_os_notification(self.root, title, message)
        except Exception:
            pass

    def _play_alarm_sound(self):
        if winsound is not None:
            try:
                winsound.MessageBeep(winsound.MB_ICONASTERISK)
                return
            except Exception:
                pass
        try:
            self.root.bell()
        except Exception:
            pass

    def _show_alarm_popup(self, ev, eid, event_dt):
        """Non-modal (no grab_set) so a reminder never blocks whatever
        else the user is doing in the app - it just appears on top."""
        top = tk.Toplevel(self.root)
        top.title("Reminder")
        top.configure(bg=COLOR_BG_PANEL)
        top.resizable(False, False)
        try:
            top.attributes("-topmost", True)
        except Exception:
            pass
        top.bind("<Escape>", lambda _e: top.destroy())

        tk.Label(top, text="\u23f0  Reminder", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                 font=("Segoe UI", 13, "bold")).pack(padx=18, pady=(16, 4))

        when = event_dt.strftime("%a %d %b, %H:%M") if (ev.get("start") or "").strip() \
            else event_dt.strftime("%a %d %b")
        tk.Label(top, text=ev.get("title", ""), bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                 font=("Segoe UI", 11, "bold"), wraplength=320, justify="left").pack(padx=18)
        tk.Label(top, text=when, bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM,
                 font=FONT_MAIN).pack(padx=18, pady=(2, 8))
        if ev.get("note"):
            tk.Label(top, text=ev["note"], bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                     font=FONT_SMALL, wraplength=320, justify="left").pack(padx=18, pady=(0, 8))

        btn_row = tk.Frame(top, bg=COLOR_BG_PANEL)
        btn_row.pack(pady=(4, 16), padx=18)
        styled_button(
            btn_row, "Dismiss (stop reminding)", lambda: self._dismiss_alarm(eid, top),
            COLOR_BTN_DANGER, COLOR_BTN_DANGER_FG,
        ).pack(side="left", padx=(0, 8))
        styled_button(btn_row, "OK", top.destroy, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left")

        top.update_idletasks()
        _center_over(top, self.root)
        # Being topmost is not enough on its own - if TutorCal is minimised
        # or behind another program, nothing tells her a reminder arrived.
        # Blink the taskbar button (without stealing focus) and raise the
        # popup above the other windows. The OS toast in _fire_alarm covers
        # the same ground, but this one works even where the toast doesn't
        # (Focus assist, notifications turned off for the app, no Action
        # Center at all), so both are kept.
        flash_taskbar(self.root)
        try:
            top.lift()
        except Exception:
            pass

    def _dismiss_alarm(self, eid, popup):
        entry = self.alarm_state.get(eid, {})
        entry["dismissed"] = True
        self.alarm_state[eid] = entry
        save_json_dict(ALARM_STATE_PATH, self.alarm_state)
        popup.destroy()

    # ---------------- Tab: Base Schedule ----------------
    def _build_tab_base_schedule(self, parent):
        self._header(
            parent, "Base Weekly Schedule & Temporary Moves",
            "Set up the recurring weekly lesson slots (typically 17-18 / 18-19 / "
            "19-20 on weekdays and Sundays, but any time is allowed) - these now "
            "auto-generate onto the Calendar tab's Month View. Optionally pick a "
            "'Warn before' / 'Repeat reminder' for a slot so it alarms the same "
            "way a Calendar > List View entry does. Record one-off cancellations "
            "or moves below for a specific date; use the 'Schedule' dropdown to "
            "target the lesson schedule or any family schedule, and pick the "
            "exact slot when that day has more than one.",
        )
        outer, inner = make_scrollable_frame(parent, bg=COLOR_BG_MAIN)
        outer.pack(fill="both", expand=True, padx=10, pady=10)

        cols = ("weekday", "start", "end", "lead", "repeat", "note")
        headers = ("Weekday", "Start", "End", "Warn before", "Repeat", "Note")
        self.tree_base = ttk.Treeview(inner, columns=cols, show="headings", height=8)
        for c, h in zip(cols, headers):
            self.tree_base.heading(c, text=h)
            width = 110 if c in ("lead", "repeat") else (130 if c != "note" else 220)
            self.tree_base.column(c, width=width, anchor="w")
        self.tree_base.pack(fill="x", pady=(0, 10))

        form = tk.LabelFrame(inner, text="Add recurring slot", bg=COLOR_BG_PANEL,
                              fg=COLOR_TEXT_MAIN, font=FONT_MAIN, padx=10, pady=10)
        form.pack(fill="x", pady=(0, 10))

        row = tk.Frame(form, bg=COLOR_BG_PANEL)
        row.pack(fill="x", pady=3)
        tk.Label(row, text="Weekday:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.base_weekday_var = tk.StringVar(value="Monday")
        ttk.Combobox(
            row, textvariable=self.base_weekday_var, state="readonly", width=11,
            values=WEEKDAYS,
        ).pack(side="left", padx=(4, 16))

        tk.Label(row, text="Start:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.base_start = make_entry(row, width=7, font=FONT_MAIN)
        self.base_start.insert(0, "17:00")
        self.base_start.pack(side="left", padx=(4, 16))

        tk.Label(row, text="End:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.base_end = make_entry(row, width=7, font=FONT_MAIN)
        self.base_end.insert(0, "18:00")
        self.base_end.pack(side="left", padx=(4, 16))

        preset_row = tk.Frame(form, bg=COLOR_BG_PANEL)
        preset_row.pack(fill="x", pady=3)
        tk.Label(preset_row, text="Quick presets:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        for lbl, s, e in (("17-18", "17:00", "18:00"), ("18-19", "18:00", "19:00"), ("19-20", "19:00", "20:00")):
            styled_button(preset_row, lbl, lambda s=s, e=e: self._fill_base_preset(s, e),
                          COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=4)

        lead_row = tk.Frame(form, bg=COLOR_BG_PANEL)
        lead_row.pack(fill="x", pady=3)
        tk.Label(lead_row, text="Warn before:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.base_lead_var = tk.StringVar(value=ALARM_LEAD_CHOICES[0][0])
        base_lead_box = ttk.Combobox(
            lead_row, textvariable=self.base_lead_var, state="readonly", width=16,
            values=[c[0] for c in ALARM_LEAD_CHOICES],
        )
        base_lead_box.pack(side="left", padx=(4, 16))
        base_lead_box.bind("<<ComboboxSelected>>", lambda _e: sync_repeat_choices_to_lead(
            self.base_lead_var.get(), self.base_repeat_box, self.base_repeat_var))

        tk.Label(lead_row, text="Repeat reminder:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.base_repeat_var = tk.StringVar(value="(no repeat)")
        self.base_repeat_box = ttk.Combobox(
            lead_row, textvariable=self.base_repeat_var, state="readonly", width=16,
            values=["(no repeat)"],
        )
        self.base_repeat_box.pack(side="left", padx=(4, 0))

        note_row = tk.Frame(form, bg=COLOR_BG_PANEL)
        note_row.pack(fill="x", pady=3)
        tk.Label(note_row, text="Note:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.base_note = make_entry(note_row, width=40, font=FONT_MAIN)
        self.base_note.pack(side="left", padx=(4, 0))
        bind_enter_to(self.base_note, self._add_base_slot)

        btn_row = tk.Frame(inner, bg=COLOR_BG_MAIN)
        btn_row.pack(fill="x", pady=(0, 14))
        styled_button(btn_row, "Add slot (Enter)", self._add_base_slot,
                      COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left")
        styled_button(btn_row, "Edit selected...", self._edit_base_slot,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(btn_row, "Delete selected", self._delete_base_slot,
                      COLOR_BTN_DANGER, COLOR_BTN_DANGER_FG).pack(side="left")
        self.tree_base.bind("<Double-Button-1>", lambda _e: self._edit_base_slot())

        tk.Frame(inner, bg=COLOR_SEPARATOR, height=1).pack(fill="x", pady=10)

        tk.Label(inner, text="Temporary moves / cancellations", bg=COLOR_BG_MAIN,
                 fg=COLOR_TEXT_MAIN, font=("Segoe UI", 11, "bold")).pack(anchor="w")
        tk.Label(inner, text="These now actually suppress or relocate the matching Month "
                             "View occurrence (not just a side note) - pick which schedule "
                             "(lessons, or any of the schedules you defined on the Settings "
                             "tab) the override applies to.",
                 bg=COLOR_BG_MAIN, fg=COLOR_TEXT_DIM, font=FONT_SMALL,
                 wraplength=640, justify="left").pack(anchor="w", pady=(0, 4))

        cols2 = ("date", "schedule", "weekday", "slot", "action", "details", "note")
        headers2 = ("Date", "Schedule", "Weekday", "Slot affected", "Action", "Details", "Note")
        self.tree_overrides = ttk.Treeview(inner, columns=cols2, show="headings", height=6)
        for c, h in zip(cols2, headers2):
            self.tree_overrides.heading(c, text=h)
            self.tree_overrides.column(c, width=150 if c == "note" else 110, anchor="w")
        self.tree_overrides.pack(fill="x", pady=(6, 10))

        ov_form = tk.LabelFrame(inner, text="Add override", bg=COLOR_BG_PANEL,
                                 fg=COLOR_TEXT_MAIN, font=FONT_MAIN, padx=10, pady=10)
        ov_form.pack(fill="x")

        ov_r0 = tk.Frame(ov_form, bg=COLOR_BG_PANEL)
        ov_r0.pack(fill="x", pady=3)
        tk.Label(ov_r0, text="Schedule:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.override_category_var = tk.StringVar(value=OVERRIDE_CATEGORY_CHOICES[0][1])
        self.override_category_box = ttk.Combobox(
            ov_r0, textvariable=self.override_category_var, state="readonly", width=22,
            values=[label for _key, label in OVERRIDE_CATEGORY_CHOICES],
        )
        self.override_category_box.pack(side="left", padx=(4, 0))
        self.override_category_box.bind("<<ComboboxSelected>>", self._refresh_override_slot_choices)

        ov_r1 = tk.Frame(ov_form, bg=COLOR_BG_PANEL)
        ov_r1.pack(fill="x", pady=3)
        tk.Label(ov_r1, text="Date affected:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.override_date = make_entry(ov_r1, width=12, font=FONT_MAIN)
        self.override_date.insert(0, datetime.date.today().isoformat())
        self.override_date.pack(side="left", padx=(4, 0))

        # The Slot dropdown and the weekday label are derived from this
        # date, so the picker has to nudge them itself (see on_pick).
        date_picker_button(ov_r1, self.root, entry=self.override_date, title="Date affected",
                           on_pick=self._refresh_override_slot_choices).pack(side="left",
                                                                             padx=(2, 16))
        self.override_date.bind("<KeyRelease>", self._refresh_override_slot_choices)
        self.override_date.bind("<FocusOut>", self._refresh_override_slot_choices)

        tk.Label(ov_r1, text="Weekday:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.override_weekday_lbl = tk.Label(ov_r1, text="-", bg=COLOR_BG_PANEL,
                                              fg=COLOR_TEXT_DIM, font=FONT_MAIN, width=10, anchor="w")
        self.override_weekday_lbl.pack(side="left", padx=(4, 16))

        tk.Label(ov_r1, text="Slot:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.override_slot_var = tk.StringVar(value="All slots that day")
        self.override_slot_box = ttk.Combobox(
            ov_r1, textvariable=self.override_slot_var, state="readonly", width=20,
            values=["All slots that day"],
        )
        self.override_slot_box.pack(side="left", padx=(4, 0))

        ov_r2 = tk.Frame(ov_form, bg=COLOR_BG_PANEL)
        ov_r2.pack(fill="x", pady=3)
        tk.Label(ov_r2, text="Action:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.override_action_var = tk.StringVar(value="Cancel")
        ttk.Combobox(
            ov_r2, textvariable=self.override_action_var, state="readonly", width=12,
            values=["Cancel", "Move", "Note only"],
        ).pack(side="left", padx=(4, 16))

        tk.Label(ov_r2, text="If Move - new date:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.override_new_date = make_entry(ov_r2, width=12, font=FONT_MAIN)
        self.override_new_date.pack(side="left", padx=(4, 0))
        date_picker_button(ov_r2, self.root, entry=self.override_new_date,
                           title="Move it to which date?").pack(side="left", padx=(2, 16))
        tk.Label(ov_r2, text="new start:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.override_new_start = make_entry(ov_r2, width=7, font=FONT_MAIN)
        self.override_new_start.pack(side="left", padx=(4, 16))
        tk.Label(ov_r2, text="new end:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.override_new_end = make_entry(ov_r2, width=7, font=FONT_MAIN)
        self.override_new_end.pack(side="left", padx=(4, 0))

        ov_r3 = tk.Frame(ov_form, bg=COLOR_BG_PANEL)
        ov_r3.pack(fill="x", pady=3)
        tk.Label(ov_r3, text="Note / reason:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.override_note = make_entry(ov_r3, width=50, font=FONT_MAIN)
        self.override_note.pack(side="left", padx=(4, 0))
        bind_enter_to(self.override_note, self._add_override)

        ov_btn_row = tk.Frame(inner, bg=COLOR_BG_MAIN)
        ov_btn_row.pack(fill="x", pady=(8, 0))
        styled_button(ov_btn_row, "Add override (Enter)", self._add_override,
                      COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left")
        styled_button(ov_btn_row, "Edit selected...", self._edit_override,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(ov_btn_row, "Delete selected", self._delete_override,
                      COLOR_BTN_DANGER, COLOR_BTN_DANGER_FG).pack(side="left")
        self.tree_overrides.bind("<Double-Button-1>", lambda _e: self._edit_override())

        self._refresh_override_slot_choices()

    def _fill_base_preset(self, start, end):
        self.base_start.delete(0, "end")
        self.base_start.insert(0, start)
        self.base_end.delete(0, "end")
        self.base_end.insert(0, end)

    def _add_base_slot(self):
        slot = {
            "id": uuid.uuid4().hex,
            "weekday": self.base_weekday_var.get(),
            "start": self.base_start.get().strip(),
            "end": self.base_end.get().strip(),
            "lead": self.base_lead_var.get(),
            "repeat": self.base_repeat_var.get(),
            "note": self.base_note.get().strip(),
        }
        self.base_schedule.append(slot)
        save_json_list(BASE_SCHEDULE_PATH, self.base_schedule)
        self._reload_tree_base()
        self._refresh_override_slot_choices()
        self._refresh_month_view()
        self.base_note.delete(0, "end")
        self.base_lead_var.set(ALARM_LEAD_CHOICES[0][0])
        sync_repeat_choices_to_lead(self.base_lead_var.get(), self.base_repeat_box, self.base_repeat_var)
        show_auto_popup(self.root, "Recurring slot added.")

    def _delete_base_slot(self):
        sel = self.tree_base.selection()
        if not sel:
            return
        idx = self.tree_base.index(sel[0])
        row_id = self.base_schedule[idx].get("id")
        del self.base_schedule[idx]
        save_json_list(BASE_SCHEDULE_PATH, self.base_schedule)
        self._purge_alarm_state_for_row(row_id)
        self._reload_tree_base()
        self._refresh_override_slot_choices()
        self._refresh_month_view()

    def _refresh_override_schedule_choices(self):
        """Repopulate the override form's 'Schedule' dropdown after the
        user has added/renamed/deleted a schedule on the Settings tab."""
        if not hasattr(self, "override_category_box"):
            return
        labels = [label for _key, label in OVERRIDE_CATEGORY_CHOICES]
        self.override_category_box.configure(values=labels)
        if self.override_category_var.get() not in labels:
            self.override_category_var.set(labels[0] if labels else "")
        self._refresh_override_slot_choices()

    def _override_category_key(self):
        """Map the 'Schedule' dropdown's current human label back to its
        internal category key (see OVERRIDE_CATEGORY_CHOICES)."""
        label = self.override_category_var.get()
        for key, lbl in OVERRIDE_CATEGORY_CHOICES:
            if lbl == label:
                return key
        return "lesson"

    def _override_source_rows(self, category):
        """Rows + (start_field, end_field) for whichever schedule is
        currently selected in the override form - the base schedule for
        'lesson', or the matching family schedule list otherwise."""
        if category == "lesson":
            return self.base_schedule, "start", "end"
        start_field, end_field = FAMILY_SCHEDULE_FIELDS.get(category, ("start", "end"))
        return self.personal_schedules.get(category, []), start_field, end_field

    def _refresh_override_slot_choices(self, _event=None):
        """Recompute which slots are offered in the override form's
        'Slot' dropdown, based on the selected Schedule and the weekday
        of the typed date."""
        d = safe_parse_date(self.override_date.get())
        if d is None:
            self.override_weekday_lbl.configure(text="-")
            self.override_slot_box.configure(values=["All slots that day"])
            self.override_slot_var.set("All slots that day")
            return
        weekday = WEEKDAYS[d.weekday()]
        self.override_weekday_lbl.configure(text=weekday)
        category = self._override_category_key()
        rows, start_field, end_field = self._override_source_rows(category)
        matching = [r for r in rows if r.get("weekday") == weekday]
        choices = ["All slots that day"] + [
            f"{r.get(start_field,'')}-{r.get(end_field,'')}" for r in matching
        ]
        self.override_slot_box.configure(values=choices)
        if self.override_slot_var.get() not in choices:
            self.override_slot_var.set(choices[0])

    def _add_override(self):
        date = self.override_date.get().strip()
        if not safe_parse_date(date):
            messagebox.showwarning("Invalid date", "Date affected must be YYYY-MM-DD.", parent=self.root)
            return
        action_label = self.override_action_var.get()
        action = {"Cancel": "cancel", "Move": "move", "Note only": "note_only"}[action_label]

        slot_choice = self.override_slot_var.get()
        slot_start, slot_end = "", ""
        if slot_choice and slot_choice != "All slots that day" and "-" in slot_choice:
            slot_start, slot_end = slot_choice.split("-", 1)

        if action == "move" and not safe_parse_date(self.override_new_date.get()):
            messagebox.showwarning("Missing info", "Move needs a valid new date (YYYY-MM-DD).",
                                    parent=self.root)
            return

        override = {
            "target_date": date,
            "category": self._override_category_key(),
            "weekday": self.override_weekday_lbl.cget("text"),
            "slot_start": slot_start, "slot_end": slot_end,
            "action": action,
            "new_date": self.override_new_date.get().strip() if action == "move" else "",
            "new_start": self.override_new_start.get().strip() if action == "move" else "",
            "new_end": self.override_new_end.get().strip() if action == "move" else "",
            "note": self.override_note.get().strip(),
        }
        self.temp_overrides.append(override)
        save_json_list(OVERRIDES_PATH, self.temp_overrides)
        # Same reasoning as the drag path: this override changes when (or
        # whether) an occurrence happens, so its old reminder state is
        # stale - see _purge_alarm_state_for_override.
        self._purge_alarm_state_for_override(override)
        self._reload_tree_overrides()
        self._refresh_month_view()
        self.override_note.delete(0, "end")
        self.override_new_date.delete(0, "end")
        self.override_new_start.delete(0, "end")
        self.override_new_end.delete(0, "end")
        show_auto_popup(self.root, "Override added.")

    def _delete_override(self):
        sel = self.tree_overrides.selection()
        if not sel:
            return
        idx = self.tree_overrides.index(sel[0])
        removed = self.temp_overrides[idx]
        del self.temp_overrides[idx]
        save_json_list(OVERRIDES_PATH, self.temp_overrides)
        # Removing a Move/Cancel puts the occurrence back at its original
        # time (or back on the calendar at all), so it has to be allowed
        # to remind again even if the moved/cancelled version had already
        # been dismissed.
        self._purge_alarm_state_for_override(removed)
        self._reload_tree_overrides()
        self._refresh_month_view()

    def _reload_tree_base(self):
        self.tree_base.delete(*self.tree_base.get_children())
        for s in self.base_schedule:
            self.tree_base.insert("", "end", values=(
                s.get("weekday", ""), s.get("start", ""), s.get("end", ""),
                s.get("lead") or "None", s.get("repeat") or "(no repeat)", s.get("note", ""),
            ))

    def _purge_alarm_state_for_row(self, row_id):
        """Drop every alarm_state entry belonging to a deleted Base
        Schedule / Family Schedule row (keys are '<row id>:<date>' - see
        generate_recurring_alarm_instances, DEL 07b), the same cleanup
        _delete_calendar_event already does for one-off events. Safe to
        call with row_id=None (e.g. a row saved before ids existed and
        never got one back-filled) - it's just a no-op then."""
        if not row_id:
            return
        prefix = f"{row_id}:"
        stale = [k for k in self.alarm_state if k.startswith(prefix)]
        if not stale:
            return
        for k in stale:
            del self.alarm_state[k]
        save_json_dict(ALARM_STATE_PATH, self.alarm_state)

    def _rows_matching_override(self, ov):
        """Every recurring row a given override actually applies to - the
        reverse of slot_is_overridden(): that asks "is this slot covered
        by an override?", this asks "which slots does this override
        cover?". A blank slot_start/slot_end is the same blanket "all
        slots that day" it means everywhere else. Needed because an
        override only remembers its date and slot times, while alarm
        state is keyed by the *row's* id (see
        generate_recurring_alarm_instances)."""
        if not isinstance(ov, dict):
            return []
        category = ov.get("category", "lesson")
        rows, start_field, end_field = self._override_source_rows(category)
        target = safe_parse_date(ov.get("target_date", ""))
        weekday = WEEKDAYS[target.weekday()] if target else ov.get("weekday", "")
        s_start, s_end = ov.get("slot_start", ""), ov.get("slot_end", "")
        out = []
        for row in rows:
            if weekday and row.get("weekday") != weekday:
                continue
            if (s_start or s_end) and not (row.get(start_field, "") == s_start
                                           and row.get(end_field, "") == s_end):
                continue
            out.append(row)
        return out

    def _purge_alarm_state_for_override(self, ov, *extra_dates):
        """Drop the fired/dismissed state of every occurrence an override
        moves, cancels or un-cancels, so the reminder can fire again at
        the time it now actually happens.

        This matters most for a move *within the same day*: the alarm key
        is '<row id>:<the date the occurrence falls on>', so shifting a
        17:00 lesson to 19:00 on the same date leaves the key unchanged -
        and without this, the 18:00 reminder never comes, because the
        state saying "already fired/dismissed" from the 17:00 version is
        still sitting there. Deleting a move override has the same problem
        in reverse (back at the original time, state already spent), which
        is why the delete path calls this too. Note-only overrides don't
        change when anything happens, so they're skipped - they'd
        otherwise match every row that day and reset reminders that had
        nothing to do with them."""
        if not isinstance(ov, dict) or ov.get("action") not in ("cancel", "move"):
            return
        dates = {ov.get("target_date", ""), ov.get("new_date", "")}
        for d in extra_dates:
            dates.add(d.isoformat() if hasattr(d, "isoformat") else str(d))
        dates.discard("")
        stale = [f"{row.get('id')}:{d}" for row in self._rows_matching_override(ov)
                 if row.get("id") for d in dates]
        stale = [k for k in stale if k in self.alarm_state]
        if not stale:
            return
        for k in stale:
            del self.alarm_state[k]
        save_json_dict(ALARM_STATE_PATH, self.alarm_state)

    def _reload_tree_overrides(self):
        self.tree_overrides.delete(*self.tree_overrides.get_children())
        action_labels = {"cancel": "Cancel", "move": "Move", "note_only": "Note only"}
        schedule_labels = dict(OVERRIDE_CATEGORY_CHOICES)
        for o in self.temp_overrides:
            slot = "All" if not o.get("slot_start") else f"{o.get('slot_start')}-{o.get('slot_end')}"
            details = "-"
            if o.get("action") == "move":
                details = f"-> {o.get('new_date','')} {o.get('new_start','')}-{o.get('new_end','')}"
            self.tree_overrides.insert("", "end", values=(
                o.get("target_date", ""),
                schedule_labels.get(o.get("category", "lesson"), o.get("category", "lesson")),
                o.get("weekday", ""), slot,
                action_labels.get(o.get("action", "note_only"), "Note only"),
                details, o.get("note", ""),
            ))

    # ---------------- Tab: Family Schedules ----------------
    def _build_tab_family(self, parent):
        self._header(
            parent, "Family Schedules",
            "One sub-tab per schedule you defined on the Settings tab (her own "
            "schedule, the son's school, bus, daycare - and anything else you "
            "add there; the names and colours are yours to choose). These show "
            "up as optional layers on the Calendar tab's Month View (toggle "
            "them with the checkboxes there), each row can have its own 'Warn "
            "before' / 'Repeat reminder' so it alarms like a Calendar > List "
            "View entry, and a one-off cancellation or move for any of them is "
            "recorded on the Base Schedule tab - pick the right schedule from "
            "the 'Schedule' dropdown there.",
        )
        sub = ttk.Notebook(parent)
        sub.pack(fill="both", expand=True, padx=10, pady=10)

        self.family_trees = {}
        self.family_editors = {}     # key -> that section's edit_row(), for the Week View
        self.family_reloaders = {}   # key -> that section's reload(), see _reload_all_treeviews
        # One sub-tab per user-defined schedule, in her own order. "lesson"
        # is skipped - the base tutoring schedule has its own tab and its
        # rows live in base_schedule.json, not personal_schedules.json.
        specs = []
        for d in SCHEDULE_DEFS:
            if d["key"] == "lesson":
                continue
            start_field = d.get("start_field", "start")
            end_field = d.get("end_field", "end")
            specs.append((
                d["key"], d["name"],
                ("weekday", start_field, end_field, "lead", "repeat", "note"),
                ("Weekday", d.get("start_label", "Start"), d.get("end_label", "End"),
                 "Warn before", "Repeat", "Note"),
            ))

        if not specs:
            empty = tk.Frame(sub, bg=COLOR_BG_MAIN)
            sub.add(empty, text="(no schedules yet)")
            tk.Label(empty, text="No family schedules defined yet.\n\n"
                                 "Go to the Settings tab and add one - give it a name "
                                 "and a colour, and it appears here as its own sub-tab.",
                     bg=COLOR_BG_MAIN, fg=COLOR_TEXT_DIM, font=FONT_MAIN,
                     justify="left").pack(anchor="w", padx=20, pady=20)
            return

        for key, label, cols, headers in specs:
            frame = tk.Frame(sub, bg=COLOR_BG_MAIN)
            sub.add(frame, text=label)
            self._build_family_section(frame, key, cols, headers)

    def _rebuild_family_tab(self):
        """Throw away and redraw the whole Family Schedules tab - used when
        the schedule list itself changed (added / renamed / recoloured /
        reordered / deleted on the Settings tab)."""
        for w in self.tab_family.winfo_children():
            w.destroy()
        self._build_tab_family(self.tab_family)

    def _build_family_section(self, parent, key, cols, headers):
        outer, inner = make_scrollable_frame(parent, bg=COLOR_BG_MAIN)
        outer.pack(fill="both", expand=True, padx=10, pady=10)

        def row_values(row):
            # "lead"/"repeat" get a readable fallback ("None" / "(no
            # repeat)") for rows saved before those fields existed,
            # instead of showing a blank cell.
            out = []
            for c in cols:
                if c == "lead":
                    out.append(row.get("lead") or "None")
                elif c == "repeat":
                    out.append(row.get("repeat") or "(no repeat)")
                else:
                    out.append(row.get(c, ""))
            return tuple(out)

        tree = ttk.Treeview(inner, columns=cols, show="headings", height=8)
        for c, h in zip(cols, headers):
            tree.heading(c, text=h)
            width = 110 if c in ("lead", "repeat") else (150 if c != "note" else 220)
            tree.column(c, width=width, anchor="w")
        tree.pack(fill="x", pady=(0, 10))
        self.family_trees[key] = tree

        form = tk.Frame(inner, bg=COLOR_BG_MAIN)
        form.pack(fill="x")
        entries = {}
        for c, h in zip(cols, headers):
            tk.Label(form, text=f"{h}:", bg=COLOR_BG_MAIN, font=FONT_MAIN).pack(side="left")
            if c == "weekday":
                # Locked to WEEKDAYS (not free text) so it reliably matches the
                # Month View's day-of-week lookup - a typo here used to mean
                # the row just silently never showed up anywhere.
                wd_var = tk.StringVar(value=WEEKDAYS[0])
                ent = ttk.Combobox(form, textvariable=wd_var, state="readonly",
                                    width=11, values=WEEKDAYS)
                ent._wd_var = wd_var  # keep a reference so add_row/reset can use it
            elif c == "lead":
                lead_var = tk.StringVar(value=ALARM_LEAD_CHOICES[0][0])
                ent = ttk.Combobox(form, textvariable=lead_var, state="readonly",
                                    width=14, values=[choice[0] for choice in ALARM_LEAD_CHOICES])
                ent._lead_var = lead_var
            elif c == "repeat":
                repeat_var = tk.StringVar(value="(no repeat)")
                ent = ttk.Combobox(form, textvariable=repeat_var, state="readonly",
                                    width=14, values=["(no repeat)"])
                ent._repeat_var = repeat_var
            else:
                ent = make_entry(form, width=12 if c != "note" else 30, font=FONT_MAIN)
            ent.pack(side="left", padx=(4, 14))
            entries[c] = ent

        # Narrow "Repeat" to choices that make sense for the picked "Warn
        # before" value - same lead->repeat relationship as the Calendar
        # tab and the Base Schedule tab (see sync_repeat_choices_to_lead).
        if "lead" in entries and "repeat" in entries:
            entries["lead"].bind("<<ComboboxSelected>>", lambda _e: sync_repeat_choices_to_lead(
                entries["lead"]._lead_var.get(), entries["repeat"], entries["repeat"]._repeat_var))

        def add_row():
            row = {c: entries[c].get().strip() for c in cols}
            row["id"] = uuid.uuid4().hex
            self.personal_schedules.setdefault(key, []).append(row)
            save_json_list(PERSONAL_SCHEDULES_PATH, self.personal_schedules)
            tree.insert("", "end", values=row_values(row))
            for c, ent in entries.items():
                if c == "weekday":
                    ent._wd_var.set(WEEKDAYS[0])
                elif c == "lead":
                    ent._lead_var.set(ALARM_LEAD_CHOICES[0][0])
                elif c == "repeat":
                    ent._repeat_var.set("(no repeat)")
                else:
                    ent.delete(0, "end")
            self._refresh_month_view()
            self._refresh_override_slot_choices()  # in case the override form has this schedule selected

        def edit_row():
            sel = tree.selection()
            if not sel:
                messagebox.showinfo("Edit row", "Pick a row in the list first.", parent=self.root)
                return
            idx = tree.index(sel[0])
            row = self.personal_schedules.setdefault(key, [])[idx]
            # Built from the same `cols`/`headers` this section was drawn
            # with, so a schedule using "departs"/"arrives" edits those
            # rather than a hard-coded "start"/"end".
            fields = []
            for c, h in zip(cols, headers):
                if c == "weekday":
                    fields.append({"key": c, "label": h, "kind": "combo",
                                   "values": WEEKDAYS, "width": 14})
                elif c in ("lead", "repeat"):
                    fields.append({"key": c, "label": h, "kind": c, "width": 18})
                else:
                    fields.append({"key": c, "label": h,
                                   "width": 34 if c == "note" else 8})
            new = self._edit_record_dialog("Edit row", fields, row)
            if new is None:
                return
            if any(new.get(k) != row.get(k) for k in ("weekday", cols[1], "lead", "repeat")):
                self._purge_alarm_state_for_row(row.get("id"))
            row.update(new)
            save_json_list(PERSONAL_SCHEDULES_PATH, self.personal_schedules)
            tree.item(sel[0], values=row_values(row))
            self._refresh_month_view()
            self._refresh_override_slot_choices()
            show_auto_popup(self.root, "Row updated.")

        def delete_row():
            sel = tree.selection()
            if not sel:
                return
            idx = tree.index(sel[0])
            row_id = self.personal_schedules.setdefault(key, [])[idx].get("id")
            del self.personal_schedules[key][idx]
            save_json_list(PERSONAL_SCHEDULES_PATH, self.personal_schedules)
            self._purge_alarm_state_for_row(row_id)
            tree.delete(sel[0])
            self._refresh_month_view()
            self._refresh_override_slot_choices()

        def reload_tree():
            """Redraw this section's list from personal_schedules. add_row /
            delete_row keep the tree in step themselves, but anything that
            changes the data another way (an import, an edit from the Week
            View, a schedule being rebuilt) goes through here."""
            tree.delete(*tree.get_children())
            for r in self.personal_schedules.get(key, []):
                tree.insert("", "end", values=row_values(r))

        self.family_reloaders[key] = reload_tree

        bind_enter_to(list(entries.values())[-1], add_row)
        btns = tk.Frame(inner, bg=COLOR_BG_MAIN)
        btns.pack(fill="x", pady=(8, 0))
        styled_button(btns, "Add (Enter)", add_row, COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left")
        styled_button(btns, "Edit selected...", edit_row, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(btns, "Delete selected", delete_row, COLOR_BTN_DANGER,
                      COLOR_BTN_DANGER_FG).pack(side="left")
        tree.bind("<Double-Button-1>", lambda _e: edit_row())
        # Registered so a double-click on a Week View block can open this
        # very editor for the right schedule (DEL 08d).
        self.family_editors[key] = edit_row

        for row in self.personal_schedules.get(key, []):
            tree.insert("", "end", values=row_values(row))

    # ---------------- Tab: Contacts ----------------
    def _build_tab_contacts(self, parent):
        self._header(
            parent, "Contacts",
            "School, daycare, and student contacts. 'App' and 'Role' are picked "
            "from dropdowns you fill in yourself on the Settings tab - App "
            "starts out blank and stays blank until you add your apps there. "
            "Use Search to filter the list, and optionally link a contact to a "
            "specific Student contact and/or a specific Calendar event (e.g. "
            "link a Guardian to their Student, or a School contact to a "
            "particular meeting).",
        )
        outer, inner = make_scrollable_frame(parent, bg=COLOR_BG_MAIN)
        outer.pack(fill="both", expand=True, padx=10, pady=10)

        search_row = tk.Frame(inner, bg=COLOR_BG_MAIN)
        search_row.pack(fill="x", pady=(0, 6))
        tk.Label(search_row, text="Search:", bg=COLOR_BG_MAIN, font=FONT_MAIN).pack(side="left")
        self.contact_search_var = tk.StringVar(value="")
        search_entry = make_entry(search_row, width=30, font=FONT_MAIN,
                                   textvariable=self.contact_search_var)
        search_entry.pack(side="left", padx=(4, 8))
        search_entry.bind("<KeyRelease>", lambda _e: self._reload_tree_contacts())
        tk.Label(search_row, text="(matches name, role, app, contact value, note, or linked student/event)",
                 bg=COLOR_BG_MAIN, fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left")
        styled_button(search_row, "Clear", self._clear_contact_search,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=(8, 0))

        cols = ("name", "role", "app", "value", "note", "linked")
        headers = ("Name", "Role", "App", "Contact value", "Note", "Linked to")
        self.tree_contacts = ttk.Treeview(inner, columns=cols, show="headings", height=10)
        for c, h in zip(cols, headers):
            self.tree_contacts.heading(c, text=h)
            self.tree_contacts.column(c, width=140 if c not in ("note", "linked") else 200, anchor="w")
        self.tree_contacts.pack(fill="x", pady=(0, 10))

        form = tk.LabelFrame(inner, text="Add contact", bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                              font=FONT_MAIN, padx=10, pady=10)
        form.pack(fill="x")

        row1 = tk.Frame(form, bg=COLOR_BG_PANEL)
        row1.pack(fill="x", pady=3)
        tk.Label(row1, text="Name:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.contact_name = make_entry(row1, width=22, font=FONT_MAIN)
        self.contact_name.pack(side="left", padx=(4, 16))

        tk.Label(row1, text="Role:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        # Roles come from the user's own list (Settings tab), not a fixed
        # set - see _refresh_contact_choice_lists().
        self.contact_role_var = tk.StringVar(value=(self.contact_roles[0] if self.contact_roles else ""))
        self.contact_role_box = ttk.Combobox(
            row1, textvariable=self.contact_role_var, state="readonly", width=14,
            values=list(self.contact_roles),
        )
        self.contact_role_box.pack(side="left", padx=(4, 16))
        self.contact_role_box.bind("<<ComboboxSelected>>", lambda _e: self._refresh_contact_link_choices())

        tk.Label(row1, text="(App / Role lists are edited on the Settings tab)",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left")

        row2 = tk.Frame(form, bg=COLOR_BG_PANEL)
        row2.pack(fill="x", pady=3)
        tk.Label(row2, text="App:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        # Blank by default, always - the first entry in the dropdown is an
        # empty line, so a contact with no app stays honestly empty rather
        # than silently defaulting to "WhatsApp" the way it used to.
        self.contact_app_var = tk.StringVar(value="")
        self.contact_app_box = ttk.Combobox(
            row2, textvariable=self.contact_app_var, state="readonly", width=16,
            values=[""] + list(self.contact_apps),
        )
        self.contact_app_box.pack(side="left", padx=(4, 16))

        tk.Label(row2, text="Contact value:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.contact_value = make_entry(row2, width=24, font=FONT_MAIN)
        self.contact_value.pack(side="left", padx=(4, 16))

        tk.Label(row2, text="Note:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.contact_note = make_entry(row2, width=24, font=FONT_MAIN)
        self.contact_note.pack(side="left", padx=(4, 0))

        row3 = tk.Frame(form, bg=COLOR_BG_PANEL)
        row3.pack(fill="x", pady=3)
        tk.Label(row3, text="Linked student:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.contact_link_student_var = tk.StringVar(value="(none)")
        self.contact_link_student_box = ttk.Combobox(
            row3, textvariable=self.contact_link_student_var, state="readonly", width=26,
            values=["(none)"],
        )
        self.contact_link_student_box.pack(side="left", padx=(4, 16))

        tk.Label(row3, text="Linked event:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.contact_link_event_var = tk.StringVar(value="(none)")
        self.contact_link_event_box = ttk.Combobox(
            row3, textvariable=self.contact_link_event_var, state="readonly", width=32,
            values=["(none)"],
        )
        self.contact_link_event_box.pack(side="left", padx=(4, 0))
        bind_enter_to(self.contact_note, self._add_contact)

        btn_row = tk.Frame(inner, bg=COLOR_BG_MAIN)
        btn_row.pack(fill="x", pady=(10, 0))
        styled_button(btn_row, "Add contact (Enter)", self._add_contact,
                      COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left")
        styled_button(btn_row, "Edit selected...", self._edit_contact,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(btn_row, "Contact selected", self._open_contact,
                      COLOR_BTN_SUCCESS, COLOR_BTN_SUCCESS_FG).pack(side="left", padx=(0, 8))
        styled_button(btn_row, "Delete selected", self._delete_contact,
                      COLOR_BTN_DANGER, COLOR_BTN_DANGER_FG).pack(side="left")
        self.tree_contacts.bind("<Double-Button-1>", lambda _e: self._edit_contact())

        self._refresh_contact_link_choices()

    def _refresh_contact_choice_lists(self):
        """Repoint the Contacts tab's App / Role dropdowns at the current
        Settings-tab lists. Any value already typed stays selected if it is
        still on the list; otherwise App falls back to blank and Role to the
        first entry."""
        if not hasattr(self, "contact_app_box"):
            return      # Contacts tab not built yet
        app_values = [""] + list(self.contact_apps)
        self.contact_app_box.configure(values=app_values)
        if self.contact_app_var.get() not in app_values:
            self.contact_app_var.set("")

        role_values = list(self.contact_roles)
        self.contact_role_box.configure(values=role_values)
        if self.contact_role_var.get() not in role_values:
            self.contact_role_var.set(role_values[0] if role_values else "")

    def _clear_contact_search(self):
        self.contact_search_var.set("")
        self._reload_tree_contacts()

    # -- linking helpers --------------------------------------------------
    def _contact_display_name(self, c):
        return f"{c.get('name', '')} ({c.get('role', '')})"

    def _event_display_label(self, ev):
        when = f"{ev.get('date', '')} {ev.get('start', '')}".strip()
        return f"{when} - {ev.get('title', '')}" if when else ev.get("title", "")

    def _contact_role_student_map(self):
        """label -> id for every contact whose role is 'Student' - powers
        the 'Linked student' dropdown on the Add contact form."""
        return {
            self._contact_display_name(c): c.get("id", "")
            for c in sorted(self.contacts, key=lambda c: c.get("name", ""))
            if c.get("role") == "Student" and c.get("id")
        }

    def _calendar_event_map(self):
        """label -> id for every one-off Calendar List View event - powers
        the 'Linked event' dropdown on the Add contact form."""
        return {
            self._event_display_label(ev): ev.get("id", "")
            for ev in sorted(self.calendar_events, key=lambda e: (e.get("date", ""), e.get("start", "")))
            if ev.get("id")
        }

    def _refresh_contact_link_choices(self):
        """Recompute the 'Linked student' / 'Linked event' dropdown values
        from the current contacts / calendar_events. Called on startup and
        whenever a contact, base slot, or calendar event is added/removed
        elsewhere, so the choices never go stale while the app is open."""
        if not hasattr(self, "contact_link_student_box"):
            return  # Contacts tab not built yet (e.g. still inside __init__)

        student_values = ["(none)"] + list(self._contact_role_student_map().keys())
        self.contact_link_student_box.configure(values=student_values)
        if self.contact_link_student_var.get() not in student_values:
            self.contact_link_student_var.set("(none)")

        event_values = ["(none)"] + list(self._calendar_event_map().keys())
        self.contact_link_event_box.configure(values=event_values)
        if self.contact_link_event_var.get() not in event_values:
            self.contact_link_event_var.set("(none)")

    def _contact_linked_label(self, c):
        """Human-readable 'Linked to' text for the Contacts treeview -
        resolved live so it always reflects the current name/title, and
        shows '(deleted)' if the linked contact/event no longer exists."""
        parts = []
        sid = c.get("linked_student_id", "")
        if sid:
            student = next((x for x in self.contacts if x.get("id") == sid), None)
            parts.append(f"Student: {student.get('name', '')}" if student else "Student: (deleted)")
        eid = c.get("linked_event_id", "")
        if eid:
            ev = next((x for x in self.calendar_events if x.get("id") == eid), None)
            parts.append(f"Event: {ev.get('title', '')}" if ev else "Event: (deleted)")
        return "  |  ".join(parts) if parts else "-"

    def _add_contact(self):
        name = self.contact_name.get().strip()
        if not name:
            return
        student_map = self._contact_role_student_map()
        event_map = self._calendar_event_map()
        c = {
            "id": uuid.uuid4().hex,
            "name": name, "role": self.contact_role_var.get(),
            "app": self.contact_app_var.get().strip(), "value": self.contact_value.get().strip(),
            "note": self.contact_note.get().strip(),
            "linked_student_id": student_map.get(self.contact_link_student_var.get(), ""),
            "linked_event_id": event_map.get(self.contact_link_event_var.get(), ""),
        }
        self.contacts.append(c)
        save_json_list(CONTACTS_PATH, self.contacts)
        self._reload_tree_contacts()
        self._refresh_contact_link_choices()   # a new Student contact becomes linkable too
        for w in (self.contact_name, self.contact_value, self.contact_note):
            w.delete(0, "end")
        self.contact_app_var.set("")          # next contact starts blank again
        self.contact_link_student_var.set("(none)")
        self.contact_link_event_var.set("(none)")
        show_auto_popup(self.root, "Contact added.")

    def _open_contact(self):
        """'Contact selected' - open the picked contact in whatever their
        App field implies: an email draft, a WhatsApp chat, the phone
        dialler, an SMS. When there's no link format that can be trusted
        (Signal, Telegram, a handle rather than a number) the value goes
        on the clipboard instead of opening something wrong."""
        sel = self.tree_contacts.selection()
        if not sel:
            messagebox.showinfo("Contact", "Pick a contact in the list first.", parent=self.root)
            return
        c = next((x for x in self.contacts if x.get("id") == sel[0]), None)
        if c is None:
            return
        kind, payload = contact_link_for(c.get("app", ""), c.get("value", ""))

        if kind == "clipboard":
            if not payload:
                messagebox.showinfo("Contact",
                                    f"{c.get('name', 'This contact')} has no contact value saved yet.",
                                    parent=self.root)
                return
            self.root.clipboard_clear()
            self.root.clipboard_append(payload)
            show_auto_popup(self.root, f"Copied: {payload}", ms=1400)
            return

        if kind == "whatsapp" and not messagebox.askyesno(
                "WhatsApp",
                f"WhatsApp needs the number in international form "
                f"(+46 70 123 45 67), and {c.get('value', '')} isn't.\n\n"
                f"Open it anyway?", parent=self.root):
            return
        open_url(payload)

    def _delete_contact(self):
        sel = self.tree_contacts.selection()
        if not sel:
            return
        cid = sel[0]  # tree_contacts uses the contact's own id as its iid
        self.contacts = [c for c in self.contacts if c.get("id") != cid]
        save_json_list(CONTACTS_PATH, self.contacts)
        self._reload_tree_contacts()
        self._refresh_contact_link_choices()   # other contacts linking to this one now show "(deleted)"

    def _reload_tree_contacts(self):
        self.tree_contacts.delete(*self.tree_contacts.get_children())
        query = self.contact_search_var.get().strip().lower() if hasattr(self, "contact_search_var") else ""
        for c in self.contacts:
            linked_label = self._contact_linked_label(c)
            if query:
                haystack = " ".join([
                    c.get("name", ""), c.get("role", ""), c.get("app", ""),
                    c.get("value", ""), c.get("note", ""), linked_label,
                ]).lower()
                if query not in haystack:
                    continue
            self.tree_contacts.insert("", "end", iid=c.get("id"), values=(
                c.get("name", ""), c.get("role", ""), c.get("app", ""),
                c.get("value", ""), c.get("note", ""), linked_label,
            ))

    # ---------------- Tab: Export ----------------
    def _build_tab_export(self, parent):
        self._header(
            parent, "Export",
            "Build a merged agenda (base schedule + overrides + family layers + "
            "one-off events, same as the Month View) for a date range, and save "
            "it as a phone-friendly .txt, .png, or .pdf file to send on, or send "
            "the agenda straight into WhatsApp or an email draft as text. Saved "
            "files go under Helpfiles/Export and open automatically once done.",
        )
        outer, inner = make_scrollable_frame(parent, bg=COLOR_BG_MAIN)
        outer.pack(fill="both", expand=True, padx=10, pady=10)

        form = tk.LabelFrame(inner, text="What to include", bg=COLOR_BG_PANEL,
                              fg=COLOR_TEXT_MAIN, font=FONT_MAIN, padx=10, pady=10)
        form.pack(fill="x", pady=(0, 10))

        range_row = tk.Frame(form, bg=COLOR_BG_PANEL)
        range_row.pack(fill="x", pady=3)
        tk.Label(range_row, text="Date range:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.export_range_box = ttk.Combobox(
            range_row, textvariable=self.export_range_var, state="readonly", width=16,
            values=list(EXPORT_RANGE_CHOICES),
        )
        self.export_range_box.pack(side="left", padx=(4, 16))
        self.export_range_box.bind("<<ComboboxSelected>>",
                                   lambda _e: self._export_toggle_custom_fields())

        tk.Label(range_row, text="Custom from:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.export_from_entry = make_entry(range_row, width=11, font=FONT_MAIN,
                                             textvariable=self.export_from_var, state="disabled")
        self.export_from_entry.pack(side="left", padx=(4, 0))
        self.export_from_btn = date_picker_button(range_row, self.root, var=self.export_from_var,
                                                   title="Export from which date?")
        self.export_from_btn.pack(side="left", padx=(2, 16))
        tk.Label(range_row, text="to:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        self.export_to_entry = make_entry(range_row, width=11, font=FONT_MAIN,
                                           textvariable=self.export_to_var, state="disabled")
        self.export_to_entry.pack(side="left", padx=(4, 0))
        self.export_to_btn = date_picker_button(range_row, self.root, var=self.export_to_var,
                                                 title="Export up to which date?")
        self.export_to_btn.pack(side="left", padx=(2, 0))

        layers_row = tk.Frame(form, bg=COLOR_BG_PANEL)
        layers_row.pack(fill="x", pady=(8, 3))
        tk.Label(layers_row, text="Include:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        # Own frame so the whole set can be redrawn when the user edits her
        # schedule list on the Settings tab.
        self.export_layer_box = tk.Frame(layers_row, bg=COLOR_BG_PANEL)
        self.export_layer_box.pack(side="left")
        self._rebuild_export_layer_row()
        all_lbl = tk.Label(layers_row, text="All", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                            font=("Segoe UI", 8, "underline"), cursor="hand2")
        all_lbl.pack(side="left", padx=(6, 2))
        all_lbl.bind("<Button-1>", lambda _e: self._export_set_all_layers(True))
        tk.Label(layers_row, text="/", bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM,
                 font=FONT_SMALL).pack(side="left")
        none_lbl = tk.Label(layers_row, text="None", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                             font=("Segoe UI", 8, "underline"), cursor="hand2")
        none_lbl.pack(side="left", padx=(2, 0))
        none_lbl.bind("<Button-1>", lambda _e: self._export_set_all_layers(False))
        tk.Label(layers_row, text="(one-off events/notes/overrides are always included)",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left", padx=(10, 0))

        btn_row = tk.Frame(inner, bg=COLOR_BG_MAIN)
        btn_row.pack(fill="x")
        styled_button(btn_row, "Preview Agenda", self._export_preview,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=(0, 8))
        styled_button(btn_row, "Hours summary", self._show_hours_summary,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=(0, 8))
        styled_button(btn_row, "Export as Text", self._export_text,
                      COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left", padx=(0, 8))
        styled_button(btn_row, "Export as Image", self._export_image,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(btn_row, "Export as PDF", self._export_pdf,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        # The only export that becomes real calendar entries rather than a
        # picture of them - highlighted for that reason (DEL 07c).
        styled_button(btn_row, "Export to Calendar (.ics)", self._export_ics,
                      COLOR_BTN_SUCCESS, COLOR_BTN_SUCCESS_FG).pack(side="left", padx=8)
        if Image is None:
            tk.Label(btn_row, text="(Image needs: pip install pillow)", bg=COLOR_BG_MAIN,
                     fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left", padx=(10, 0))
        if FPDF is None:
            tk.Label(btn_row, text="(PDF needs: pip install fpdf2)", bg=COLOR_BG_MAIN,
                     fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left", padx=(10, 0))

        share_row = tk.Frame(inner, bg=COLOR_BG_MAIN)
        share_row.pack(fill="x", pady=(8, 0))
        tk.Label(share_row, text="Send as text:", bg=COLOR_BG_MAIN,
                 fg=COLOR_TEXT_DIM, font=FONT_SMALL).pack(side="left", padx=(0, 8))
        styled_button(share_row, "Copy to Clipboard", self._share_copy_clipboard,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(share_row, "Share as WhatsApp Message", self._share_whatsapp,
                      COLOR_BTN_SUCCESS, COLOR_BTN_SUCCESS_FG).pack(side="left", padx=8)
        styled_button(share_row, "Share as Email", self._share_email,
                      COLOR_BTN_SUCCESS, COLOR_BTN_SUCCESS_FG).pack(side="left", padx=8)
        tk.Label(share_row, text="(Clipboard has no length limit and pastes into any app - "
                                  "WhatsApp/Email pre-fill a message but may cut off long agendas)",
                 bg=COLOR_BG_MAIN, fg=COLOR_TEXT_DIM, font=FONT_TINY).pack(side="left", padx=(6, 0))

        self.export_status_lbl = tk.Label(
            inner, text="", bg=COLOR_BG_MAIN, fg=COLOR_TEXT_DIM, font=FONT_SMALL,
            justify="left", wraplength=800, anchor="w",
        )
        self.export_status_lbl.pack(fill="x", pady=(10, 0))

        # If a prior session left "Custom range" selected (restored above
        # from settings.json), the from/to fields need to start enabled -
        # normally that only happens on a live combobox selection event.
        self._export_toggle_custom_fields()

    def _rebuild_export_layer_row(self):
        """(Re)draw the Export tab's 'Include:' checkboxes from the current
        schedule definitions - same idea as _rebuild_month_layer_row()."""
        if not hasattr(self, "export_layer_box"):
            return      # Export tab not built yet
        for w in self.export_layer_box.winfo_children():
            w.destroy()
        for d in SCHEDULE_DEFS:
            key = d["key"]
            if key not in self.export_layer_vars:
                continue
            tk.Checkbutton(
                self.export_layer_box, text=d["name"], variable=self.export_layer_vars[key],
                bg=COLOR_BG_PANEL, activebackground=COLOR_BG_PANEL, selectcolor=d["color"],
                font=FONT_SMALL,
            ).pack(side="left", padx=(0, 10))

    def _export_set_all_layers(self, value):
        """Wired to the 'All' / 'None' quick-toggle links above the layer
        checkboxes - flips every Export tab layer checkbox to the same
        state in one click instead of clicking each one by hand."""
        for var in self.export_layer_vars.values():
            var.set(value)

    def _export_toggle_custom_fields(self):
        state = "normal" if self.export_range_var.get() == "Custom range" else "disabled"
        self.export_from_entry.configure(state=state)
        self.export_to_entry.configure(state=state)
        # The calendar buttons follow their fields - offering a picker for
        # a field that is greyed out would just be a way to set a value
        # nothing reads.
        for button in (getattr(self, "export_from_btn", None), getattr(self, "export_to_btn", None)):
            if button is not None:
                button.configure(state=state)

    def _export_get_date_range(self):
        """Resolve the Export tab's current range choice into
        (start_date, end_date). Shows an error and returns None if a
        'Custom range' choice has missing/invalid/too-large dates."""
        today = datetime.date.today()
        choice = self.export_range_var.get()
        if choice == "Next 7 days":
            return today, today + datetime.timedelta(days=6)
        if choice == "This week":
            # The same Monday-to-Sunday week the Week View shows, not the
            # next seven days - what she wants when sending "the week" on.
            monday = week_start_for(today)
            return monday, monday + datetime.timedelta(days=6)
        if choice == "Next week":
            monday = week_start_for(today) + datetime.timedelta(days=7)
            return monday, monday + datetime.timedelta(days=6)
        if choice == "Next 30 days":
            return today, today + datetime.timedelta(days=29)
        if choice == "This month":
            if today.month == 12:
                next_first = datetime.date(today.year + 1, 1, 1)
            else:
                next_first = datetime.date(today.year, today.month + 1, 1)
            return today.replace(day=1), next_first - datetime.timedelta(days=1)

        start = safe_parse_date(self.export_from_var.get())
        end = safe_parse_date(self.export_to_var.get())
        if not start or not end:
            messagebox.showerror("Invalid range", "Enter both custom dates as YYYY-MM-DD.", parent=self.root)
            return None
        if (max(start, end) - min(start, end)).days > 366:
            messagebox.showerror("Range too large", "Please pick a custom range of one year or less.",
                                  parent=self.root)
            return None
        return start, end

    def _export_build_agenda_data(self, start_date, end_date):
        dates = date_range_inclusive(start_date, end_date)
        layers = {key: var.get() for key, var in self.export_layer_vars.items()}
        occurrences = generate_occurrences_for_dates(
            dates, self.base_schedule, self.temp_overrides, self.personal_schedules,
            self.calendar_events, layers,
        )
        return dates, occurrences

    def _export_preview(self):
        """Show the merged agenda text for the Export tab's current date
        range + layers in a read-only popup, with a character count -
        lets the user sanity-check the content (and see whether it's
        under SHARE_TEXT_SAFE_CHARS) before saving a file or firing off
        one of the Share buttons."""
        date_range = self._export_get_date_range()
        if not date_range:
            return
        start_date, end_date = date_range
        dates, occurrences = self._export_build_agenda_data(start_date, end_date)
        text = build_agenda_text(dates, occurrences)

        top = tk.Toplevel(self.root)
        top.title("Agenda Preview")
        top.configure(bg=COLOR_BG_PANEL)
        top.geometry("560x520")
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _e: top.destroy())

        tk.Label(top, text="Agenda Preview", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                 font=("Segoe UI", 14, "bold")).pack(pady=(14, 2))
        count_color = COLOR_TEXT_DIM if len(text) <= SHARE_TEXT_SAFE_CHARS else COLOR_BTN_DANGER
        count_note = "" if len(text) <= SHARE_TEXT_SAFE_CHARS else "  (long - WhatsApp/Email may cut this off)"
        tk.Label(top, text=f"{len(text)} characters{count_note}", bg=COLOR_BG_PANEL,
                 fg=count_color, font=FONT_SMALL).pack(pady=(0, 8))

        outer, inner = make_scrollable_frame(top, bg=COLOR_BG_PANEL)
        outer.pack(fill="both", expand=True, padx=14, pady=(0, 10))
        txt = make_text(inner, wrap="word", width=64, height=22, font=FONT_MAIN,
                        bg=COLOR_BG_PANEL, relief="flat")
        txt.insert("1.0", text)
        txt.configure(state="disabled")
        txt.pack(fill="both", expand=True)

        btn_row = tk.Frame(top, bg=COLOR_BG_PANEL)
        btn_row.pack(pady=10)
        styled_button(btn_row, "Copy to Clipboard", self._share_copy_clipboard,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=6)
        styled_button(btn_row, "Close (Esc)", top.destroy,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=6)
        _center_over(top, self.root)

    def _show_hours_summary(self):
        """How much of what, over the Export tab's current date range -
        the question an invoice starts with. Same occurrence data as the
        agenda, so a cancelled lesson isn't counted and a moved one is
        counted on the day it actually happened."""
        date_range = self._export_get_date_range()
        if not date_range:
            return
        start_date, end_date = date_range
        dates, occurrences = self._export_build_agenda_data(start_date, end_date)
        rows, totals = summarize_hours(dates, occurrences)

        top = tk.Toplevel(self.root)
        top.title("Hours summary")
        top.configure(bg=COLOR_BG_PANEL)
        top.geometry("560x460")
        top.transient(self.root)
        top.grab_set()
        top.bind("<Escape>", lambda _e: top.destroy())

        tk.Label(top, text="Hours summary", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                 font=("Segoe UI", 14, "bold")).pack(pady=(14, 2))
        tk.Label(top, text=f"{start_date.isoformat()} to {end_date.isoformat()}",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM, font=FONT_SMALL).pack(pady=(0, 8))

        columns = ("schedule", "title", "times", "hours")
        tree = ttk.Treeview(top, columns=columns, show="headings", height=12)
        for column, heading, width in (("schedule", "Schedule", 110), ("title", "Entry", 220),
                                       ("times", "Times", 60), ("hours", "Hours", 100)):
            tree.heading(column, text=heading)
            tree.column(column, width=width, anchor="w" if column != "times" else "center")
        tree.pack(fill="both", expand=True, padx=14)
        for label, title, count, minutes in rows:
            tree.insert("", "end", values=(label, title, count, format_hours(minutes)))
        if not rows:
            tree.insert("", "end", values=("", "(nothing in this range)", "", ""))

        count_all, minutes_all = totals[""]
        tk.Label(top, text=f"Total: {count_all} entries, {format_hours(minutes_all)}",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                 font=("Segoe UI", 11, "bold")).pack(pady=(8, 0))

        def copy_text():
            self.root.clipboard_clear()
            self.root.clipboard_append(build_hours_summary_text(dates, occurrences))
            show_auto_popup(self.root, "Hours summary copied.")

        btn_row = tk.Frame(top, bg=COLOR_BG_PANEL)
        btn_row.pack(pady=10)
        styled_button(btn_row, "Copy to Clipboard", copy_text,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=6)
        styled_button(btn_row, "Close (Esc)", top.destroy,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=6)
        _center_over(top, self.root)
        return top

    def _export_target_path(self, start_date, end_date, ext):
        return os.path.join(DIR_EXPORT, f"TutorCal_Agenda_{start_date.isoformat()}_to_{end_date.isoformat()}.{ext}")

    def _export_finish(self, path, image_copied=False):
        if image_copied:
            tip = ("Also copied to your clipboard - press Ctrl+V (Cmd+V on Mac) "
                   "directly inside WhatsApp Desktop, Telegram, Signal, or your "
                   "email compose box to attach it, no dragging needed.")
        else:
            tip = ("Tip: this file isn't auto-attached anywhere yet - drag it into "
                   "WhatsApp/your email once it opens, or use the 'Share as ...' "
                   "buttons above to send the same agenda as text instead.")
        self.export_status_lbl.configure(text=f"Saved: {path}\n{tip}")
        show_auto_popup(self.root, "Export saved - opening it now.", ms=1200)
        open_in_file_manager(path)

    def _export_text(self):
        date_range = self._export_get_date_range()
        if not date_range:
            return
        start_date, end_date = date_range
        dates, occurrences = self._export_build_agenda_data(start_date, end_date)
        path = self._export_target_path(start_date, end_date, "txt")
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(build_agenda_text(dates, occurrences))
        except Exception as e:
            messagebox.showerror("Export failed", f"Could not write the text file:\n{e}", parent=self.root)
            return
        self._export_finish(path)

    def _export_ics(self):
        """Write the same agenda as an .ics calendar file - the one export
        that ends up *in* her phone's calendar rather than as a picture of
        it. No extra package needed; it's plain text."""
        date_range = self._export_get_date_range()
        if not date_range:
            return
        start_date, end_date = date_range
        dates, occurrences = self._export_build_agenda_data(start_date, end_date)
        path = self._export_target_path(start_date, end_date, "ics")
        try:
            # newline="" so the CRLF line endings iCalendar requires are
            # written exactly as built, not translated again by Windows.
            with open(path, "w", encoding="utf-8", newline="") as f:
                f.write(build_agenda_ics(dates, occurrences))
        except Exception as e:
            messagebox.showerror("Export failed", f"Could not write the calendar file:\n{e}",
                                 parent=self.root)
            return
        self.export_status_lbl.configure(
            text=f"Saved: {path}\nTip: open this file on the phone (or import it in Google "
                 f"Calendar / Outlook) to put the whole range into the calendar app itself, "
                 f"reminders and all. Re-exporting the same range updates those entries "
                 f"instead of duplicating them.")
        show_auto_popup(self.root, "Calendar file saved - opening it now.", ms=1200)
        open_in_file_manager(path)

    def _export_image(self):
        if Image is None:
            messagebox.showerror(
                "Pillow not installed",
                "Export as Image needs the Pillow package, which isn't installed.\n\n"
                "Install it with:\n    pip install pillow\n\nthen try again.",
                parent=self.root,
            )
            return
        date_range = self._export_get_date_range()
        if not date_range:
            return
        start_date, end_date = date_range
        dates, occurrences = self._export_build_agenda_data(start_date, end_date)
        path = self._export_target_path(start_date, end_date, "png")
        try:
            build_agenda_image(dates, occurrences).save(path)
        except Exception as e:
            messagebox.showerror("Export failed", f"Could not render the image:\n{e}", parent=self.root)
            return
        copied = copy_image_to_clipboard(path)
        self._export_finish(path, image_copied=copied)

    def _export_pdf(self):
        if FPDF is None:
            messagebox.showerror(
                "fpdf2 not installed",
                "Export as PDF needs the fpdf2 package, which isn't installed.\n\n"
                "Install it with:\n    pip install fpdf2\n\nthen try again.",
                parent=self.root,
            )
            return
        date_range = self._export_get_date_range()
        if not date_range:
            return
        start_date, end_date = date_range
        dates, occurrences = self._export_build_agenda_data(start_date, end_date)
        path = self._export_target_path(start_date, end_date, "pdf")
        try:
            build_agenda_pdf(dates, occurrences).output(path)
        except Exception as e:
            messagebox.showerror("Export failed", f"Could not render the PDF:\n{e}", parent=self.root)
            return
        self._export_finish(path)

    def _share_copy_clipboard(self):
        """Build the agenda text for the Export tab's current date range +
        layers and put it straight on the OS clipboard - unlike the
        WhatsApp/Email buttons below this has no practical length limit
        and can be pasted into literally any app (SMS, Signal, Telegram,
        Messenger, a chat window, ...), not just the two with a built-in
        share button."""
        date_range = self._export_get_date_range()
        if not date_range:
            return
        start_date, end_date = date_range
        dates, occurrences = self._export_build_agenda_data(start_date, end_date)
        text = build_agenda_text(dates, occurrences)
        self.root.clipboard_clear()
        self.root.clipboard_append(text)
        self.export_status_lbl.configure(
            text=f"Copied the agenda ({len(text)} characters) to the clipboard - paste it anywhere you like."
        )
        show_auto_popup(self.root, "Agenda copied to clipboard.", ms=1200)

    def _share_whatsapp(self):
        """Build the agenda text for the Export tab's current date range +
        layers and send it straight into a WhatsApp click-to-chat link
        (see DEL 07d) - the user picks the recipient inside WhatsApp
        itself, nothing is sent automatically from here."""
        date_range = self._export_get_date_range()
        if not date_range:
            return
        start_date, end_date = date_range
        dates, occurrences = self._export_build_agenda_data(start_date, end_date)
        text = build_agenda_text(dates, occurrences)
        if share_text_via_whatsapp(self.root, text):
            self.export_status_lbl.configure(
                text="Opened WhatsApp with the agenda pre-filled - choose a chat and hit send there."
            )

    def _share_email(self):
        """Same as _share_whatsapp() but opens a mailto: draft instead."""
        date_range = self._export_get_date_range()
        if not date_range:
            return
        start_date, end_date = date_range
        dates, occurrences = self._export_build_agenda_data(start_date, end_date)
        text = build_agenda_text(dates, occurrences)
        subject = f"{APP_NAME} Agenda ({start_date.isoformat()} to {end_date.isoformat()})"
        if share_text_via_email(self.root, subject, text):
            self.export_status_lbl.configure(
                text="Opened a new email draft with the agenda pre-filled - address it and hit send there."
            )

    # ---------------- misc ----------------
    # ---------------- Editing existing rows (DEL 08c) ----------------
    # Every list in the program used to be add-and-delete only: a typo in a
    # lesson time meant deleting the row and typing the whole thing again
    # (and losing its reminder state with it). One shared modal dialog now
    # backs "Edit selected" on all five lists - Calendar > List View, Base
    # Schedule, its overrides, every Family Schedule, and Contacts - so
    # they all behave, look, and validate the same way. Double-clicking a
    # row opens the same dialog.

    def _edit_record_dialog(self, title, fields, record, validate=None, on_field_change=None):
        """Modal edit form built from a field spec. Returns a dict of the
        new values, or None if cancelled.

        fields: [{"key", "label", "kind", ...}, ...] where kind is
          "text" (default), "multiline", "combo" (needs "values"),
          "date" (a text field plus the calendar button - still plain
          YYYY-MM-DD text underneath), or "lead" / "repeat" (the linked
          reminder pair - "repeat" narrows itself to whatever the chosen
          "lead" allows, exactly like the add-forms do).
        validate(values) -> error message string, or None when it's fine.
        on_field_change(key, values, boxes) is called whenever a field
          changes, so a caller can repopulate a dependent dropdown (used
          by the override editor, where the slot list depends on the
          chosen schedule and date)."""
        top = tk.Toplevel(self.root)
        top.title(title)
        top.configure(bg=COLOR_BG_PANEL)
        top.resizable(False, False)
        top.transient(self.root)
        result = {"value": None}

        variables, boxes, text_widgets = {}, {}, {}
        enter_targets = []      # one-line fields where Enter should save
        body = tk.Frame(top, bg=COLOR_BG_PANEL)
        body.pack(fill="both", expand=True, padx=16, pady=(14, 4))
        first_widget = None

        def current_values():
            out = {key: var.get().strip() for key, var in variables.items()}
            for key, widget in text_widgets.items():
                out[key] = widget.get("1.0", "end").strip()
            return out

        def field_changed(key):
            if on_field_change:
                on_field_change(key, current_values(), boxes)

        for row_i, f in enumerate(fields):
            key, kind = f["key"], f.get("kind", "text")
            tk.Label(body, text=f["label"] + ":", bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                     font=FONT_MAIN).grid(row=row_i, column=0, sticky="nw", pady=3)
            value = str(record.get(key, "") or "")

            focus_widget = None      # set when the row's real input isn't `widget` itself
            if kind == "multiline":
                widget = make_text(body, width=f.get("width", 46), height=f.get("height", 3),
                                   font=FONT_MAIN)
                widget.insert("1.0", value)
                text_widgets[key] = widget
            elif kind == "date":
                # An entry plus the calendar button, wrapped in a frame -
                # so Enter/focus must be routed to the entry inside it,
                # not to the frame (a frame takes no keystrokes).
                var = tk.StringVar(value=value)
                widget = tk.Frame(body, bg=COLOR_BG_PANEL)
                entry = make_entry(widget, width=f.get("width", 14), font=FONT_MAIN,
                                   textvariable=var)
                entry.pack(side="left")
                entry.bind("<KeyRelease>", lambda _e, k=key: field_changed(k))
                date_picker_button(widget, top, var=var, title=f["label"],
                                   on_pick=lambda k=key: field_changed(k)).pack(side="left",
                                                                                 padx=(2, 0))
                variables[key] = var
                focus_widget = entry
            elif kind in ("combo", "lead", "repeat"):
                var = tk.StringVar(value=value)
                if kind == "lead":
                    values = [c[0] for c in ALARM_LEAD_CHOICES]
                elif kind == "repeat":
                    values = [value] if value else ["(no repeat)"]
                else:
                    values = list(f.get("values") or [])
                if kind != "repeat" and value and value not in values:
                    # Keep a value that is no longer on the list (a deleted
                    # app, a renamed role) instead of silently dropping it.
                    values = [value] + values
                widget = ttk.Combobox(body, textvariable=var, state="readonly",
                                      width=f.get("width", 22), values=values)
                widget.bind("<<ComboboxSelected>>", lambda _e, k=key: field_changed(k))
                variables[key] = var
                boxes[key] = widget
            else:
                var = tk.StringVar(value=value)
                widget = make_entry(body, width=f.get("width", 24), font=FONT_MAIN,
                                    textvariable=var)
                widget.bind("<KeyRelease>", lambda _e, k=key: field_changed(k))
                variables[key] = var
            if kind != "multiline":
                enter_targets.append(focus_widget or widget)
            widget.grid(row=row_i, column=1, sticky="w", padx=(8, 0), pady=3)
            if first_widget is None:
                first_widget = focus_widget or widget

        # The reminder pair behaves the same here as in the add-forms.
        if "lead" in variables and "repeat" in boxes:
            sync_repeat_choices_to_lead(variables["lead"].get(), boxes["repeat"],
                                        variables["repeat"])
            boxes["lead"].bind("<<ComboboxSelected>>", lambda _e: (
                sync_repeat_choices_to_lead(variables["lead"].get(), boxes["repeat"],
                                            variables["repeat"]),
                field_changed("lead"),
            ))

        def save():
            values = current_values()
            if validate:
                problem = validate(values)
                if problem:
                    messagebox.showwarning(title, problem, parent=top)
                    return
            result["value"] = values
            top.destroy()

        btns = tk.Frame(top, bg=COLOR_BG_PANEL)
        btns.pack(fill="x", padx=16, pady=(8, 14))
        styled_button(btns, "Save changes (Enter)", save, COLOR_BTN_SUCCESS,
                      COLOR_BTN_SUCCESS_FG).pack(side="left")
        styled_button(btns, "Cancel (Esc)", top.destroy, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)

        # Enter saves - but bound per one-line field rather than on the
        # window, so Enter inside a multi-line Note stays a line break.
        for widget in enter_targets:
            bind_enter_to(widget, save)
        top.bind("<Escape>", lambda _e: top.destroy())
        _center_over(top, self.root)
        top.grab_set()
        top.focus_force()
        if first_widget is not None:
            first_widget.focus_set()
        top.wait_window()
        return result["value"]

    @staticmethod
    def _reminder_fields():
        return [
            {"key": "lead", "label": "Warn before", "kind": "lead", "width": 18},
            {"key": "repeat", "label": "Repeat reminder", "kind": "repeat", "width": 18},
        ]

    def _edit_calendar_event(self):
        sel = self.tree_calendar.selection()
        if not sel:
            messagebox.showinfo("Edit entry", "Pick a row in the list first.", parent=self.root)
            return
        eid = sel[0]
        ev = next((e for e in self.calendar_events if e.get("id") == eid), None)
        if ev is None:
            return
        fields = [
            {"key": "date", "label": "Date (YYYY-MM-DD)", "kind": "date", "width": 14},
            {"key": "start", "label": "Start (HH:MM)", "width": 8},
            {"key": "end", "label": "End (HH:MM)", "width": 8},
            {"key": "title", "label": "Title", "width": 34},
        ] + self._reminder_fields() + [
            {"key": "note", "label": "Note", "kind": "multiline", "width": 40, "height": 3},
        ]

        def validate(v):
            if not v["title"]:
                return "Title is required."
            if not safe_parse_date(v["date"]):
                return "Date must be YYYY-MM-DD."
            return None

        new = self._edit_record_dialog("Edit entry", fields, ev, validate)
        if new is None:
            return
        # Anything that changes *when* the reminder is due invalidates the
        # "already fired / dismissed" state - otherwise moving an entry
        # later in the day would silently never alarm again.
        if any(new.get(k) != ev.get(k) for k in ("date", "start", "lead", "repeat")):
            self.alarm_state.pop(eid, None)
            save_json_dict(ALARM_STATE_PATH, self.alarm_state)
        ev.update(new)
        save_json_list(EVENTS_PATH, self.calendar_events)
        self._reload_tree_calendar()
        self._refresh_month_view()
        self._refresh_contact_link_choices()   # its label in "Linked event" changed
        if self.tree_calendar.exists(eid):      # an active search may filter it out now
            self.tree_calendar.selection_set(eid)
            self.tree_calendar.see(eid)         # a re-dated entry can land far down the list
        show_auto_popup(self.root, "Entry updated.")

    def _edit_base_slot(self):
        sel = self.tree_base.selection()
        if not sel:
            messagebox.showinfo("Edit slot", "Pick a row in the list first.", parent=self.root)
            return
        idx = self.tree_base.index(sel[0])
        slot = self.base_schedule[idx]
        fields = [
            {"key": "weekday", "label": "Weekday", "kind": "combo", "values": WEEKDAYS, "width": 14},
            {"key": "start", "label": "Start (HH:MM)", "width": 8},
            {"key": "end", "label": "End (HH:MM)", "width": 8},
        ] + self._reminder_fields() + [
            {"key": "note", "label": "Note", "width": 40},
        ]
        new = self._edit_record_dialog("Edit recurring slot", fields, slot)
        if new is None:
            return
        if any(new.get(k) != slot.get(k) for k in ("weekday", "start", "lead", "repeat")):
            self._purge_alarm_state_for_row(slot.get("id"))
        slot.update(new)
        save_json_list(BASE_SCHEDULE_PATH, self.base_schedule)
        self._reload_tree_base()
        self._refresh_override_slot_choices()
        self._refresh_month_view()
        show_auto_popup(self.root, "Slot updated.")

    def _edit_override(self):
        sel = self.tree_overrides.selection()
        if not sel:
            messagebox.showinfo("Edit override", "Pick a row in the list first.", parent=self.root)
            return
        idx = self.tree_overrides.index(sel[0])
        ov = self.temp_overrides[idx]
        labels = dict(OVERRIDE_CATEGORY_CHOICES)
        action_labels = {"cancel": "Cancel", "move": "Move", "note_only": "Note only"}

        def slot_choices(category_label, date_text):
            """Slots offered for the schedule/date currently chosen *in the
            dialog* - recomputed live, so switching schedule or date inside
            the dialog offers the right slots instead of stale ones."""
            key = next((k for k, lbl in OVERRIDE_CATEGORY_CHOICES if lbl == category_label), "lesson")
            d = safe_parse_date(date_text)
            if d is None:
                return ["All slots that day"]
            rows, start_field, end_field = self._override_source_rows(key)
            weekday = WEEKDAYS[d.weekday()]
            return ["All slots that day"] + [
                f"{r.get(start_field, '')}-{r.get(end_field, '')}"
                for r in rows if r.get("weekday") == weekday
            ]

        current_slot = ("All slots that day" if not ov.get("slot_start")
                        else f"{ov.get('slot_start')}-{ov.get('slot_end')}")
        record = {
            "schedule": labels.get(ov.get("category", "lesson"), ov.get("category", "lesson")),
            "target_date": ov.get("target_date", ""),
            "slot": current_slot,
            "action": action_labels.get(ov.get("action", "note_only"), "Note only"),
            "new_date": ov.get("new_date", ""), "new_start": ov.get("new_start", ""),
            "new_end": ov.get("new_end", ""), "note": ov.get("note", ""),
        }
        fields = [
            {"key": "schedule", "label": "Schedule", "kind": "combo",
             "values": [lbl for _k, lbl in OVERRIDE_CATEGORY_CHOICES], "width": 24},
            {"key": "target_date", "label": "Date affected (YYYY-MM-DD)", "kind": "date", "width": 14},
            {"key": "slot", "label": "Slot affected", "kind": "combo",
             "values": slot_choices(record["schedule"], record["target_date"]), "width": 24},
            {"key": "action", "label": "Action", "kind": "combo",
             "values": ["Cancel", "Move", "Note only"], "width": 14},
            {"key": "new_date", "label": "If Move - new date", "kind": "date", "width": 14},
            {"key": "new_start", "label": "If Move - new start", "width": 8},
            {"key": "new_end", "label": "If Move - new end", "width": 8},
            {"key": "note", "label": "Note / reason", "width": 40},
        ]

        def on_change(key, values, boxes):
            if key not in ("schedule", "target_date") or "slot" not in boxes:
                return
            choices = slot_choices(values["schedule"], values["target_date"])
            boxes["slot"].configure(values=choices)
            if values["slot"] not in choices:
                boxes["slot"].set(choices[0])

        def validate(v):
            if not safe_parse_date(v["target_date"]):
                return "Date affected must be YYYY-MM-DD."
            if v["action"] == "Move" and not safe_parse_date(v["new_date"]):
                return "Move needs a valid new date (YYYY-MM-DD)."
            return None

        new = self._edit_record_dialog("Edit override", fields, record, validate, on_change)
        if new is None:
            return
        before = dict(ov)   # ov is updated in place below; the old dates decide what to un-remind
        action = {"Cancel": "cancel", "Move": "move", "Note only": "note_only"}[new["action"]]
        slot_start, slot_end = "", ""
        if new["slot"] and new["slot"] != "All slots that day" and "-" in new["slot"]:
            slot_start, slot_end = new["slot"].split("-", 1)
        target = safe_parse_date(new["target_date"])
        ov.update({
            "category": next((k for k, lbl in OVERRIDE_CATEGORY_CHOICES
                              if lbl == new["schedule"]), "lesson"),
            "target_date": new["target_date"],
            "weekday": WEEKDAYS[target.weekday()] if target else ov.get("weekday", ""),
            "slot_start": slot_start, "slot_end": slot_end,
            "action": action,
            "new_date": new["new_date"] if action == "move" else "",
            "new_start": new["new_start"] if action == "move" else "",
            "new_end": new["new_end"] if action == "move" else "",
            "note": new["note"],
        })
        save_json_list(OVERRIDES_PATH, self.temp_overrides)
        # Both shapes matter: the occurrence may have been un-moved from
        # one date/time and moved to another, and either end can be
        # carrying spent reminder state.
        self._purge_alarm_state_for_override(before)
        self._purge_alarm_state_for_override(ov)
        self._reload_tree_overrides()
        self._refresh_month_view()
        show_auto_popup(self.root, "Override updated.")

    def _edit_contact(self):
        sel = self.tree_contacts.selection()
        if not sel:
            messagebox.showinfo("Edit contact", "Pick a row in the list first.", parent=self.root)
            return
        cid = sel[0]
        c = next((x for x in self.contacts if x.get("id") == cid), None)
        if c is None:
            return
        # A contact must not be offered as its own "linked student".
        student_map = {label: sid for label, sid in self._contact_role_student_map().items()
                       if sid != cid}
        event_map = self._calendar_event_map()
        reverse_student = {sid: label for label, sid in student_map.items()}
        reverse_event = {eid: label for label, eid in event_map.items()}
        record = dict(c)
        record["linked_student"] = reverse_student.get(c.get("linked_student_id", ""), "(none)")
        record["linked_event"] = reverse_event.get(c.get("linked_event_id", ""), "(none)")
        fields = [
            {"key": "name", "label": "Name", "width": 28},
            {"key": "role", "label": "Role", "kind": "combo",
             "values": list(self.contact_roles), "width": 18},
            {"key": "app", "label": "App", "kind": "combo",
             "values": [""] + list(self.contact_apps), "width": 18},
            {"key": "value", "label": "Contact value", "width": 28},
            {"key": "note", "label": "Note", "width": 34},
            {"key": "linked_student", "label": "Linked student", "kind": "combo",
             "values": ["(none)"] + list(student_map.keys()), "width": 30},
            {"key": "linked_event", "label": "Linked event", "kind": "combo",
             "values": ["(none)"] + list(event_map.keys()), "width": 36},
        ]

        def validate(v):
            return "Name is required." if not v["name"] else None

        new = self._edit_record_dialog("Edit contact", fields, record, validate)
        if new is None:
            return
        c.update({
            "name": new["name"], "role": new["role"], "app": new["app"],
            "value": new["value"], "note": new["note"],
            "linked_student_id": student_map.get(new["linked_student"], ""),
            "linked_event_id": event_map.get(new["linked_event"], ""),
        })
        save_json_list(CONTACTS_PATH, self.contacts)
        self._reload_tree_contacts()
        self._refresh_contact_link_choices()
        if self.tree_contacts.exists(cid):
            self.tree_contacts.selection_set(cid)
        show_auto_popup(self.root, "Contact updated.")

    # ---------------- Tab: Settings (DEL 08b) ----------------
    # Everything that used to be hard-coded in the source - which apps a
    # contact can be reached on, which roles exist, and which schedules
    # ("Son: school", "Son: bus", ...) the calendar knows about - is edited
    # here instead. Nothing on this tab is fixed at five entries: she names
    # them herself, colours them herself, and can add as many as she wants.

    def _sync_layer_vars(self):
        """Make sure there is exactly one Month View layer variable and one
        Export layer variable per defined schedule - adding vars for new
        schedules and dropping vars for deleted ones, while leaving the
        variables of surviving schedules (and their on/off state) alone."""
        keys = [d["key"] for d in SCHEDULE_DEFS]
        for key in keys:
            if key not in self.month_layer_vars:
                # Only the base lesson layer starts visible; a brand-new
                # schedule stays off until she ticks it, so adding one never
                # suddenly floods the month grid.
                self.month_layer_vars[key] = tk.BooleanVar(value=(key == "lesson"))
            if key not in self.export_layer_vars:
                self.export_layer_vars[key] = tk.BooleanVar(
                    value=self._saved_export_layers.get(key, True))
        for store in (self.month_layer_vars, self.export_layer_vars):
            for key in [k for k in store if k not in keys]:
                del store[key]

    def _build_tab_settings(self, parent):
        self._header(
            parent, "Settings",
            "The lists the rest of the program picks from. Apps and roles are "
            "yours to fill in (the App dropdown on the Contacts tab stays blank "
            "until you do), and so are the schedules: rename them, recolour "
            "them, reorder them, or add new ones - each becomes its own Family "
            "Schedules sub-tab, its own Month View layer, and its own choice in "
            "the override and export lists.",
        )
        outer, inner = make_scrollable_frame(parent, bg=COLOR_BG_MAIN)
        outer.pack(fill="both", expand=True, padx=10, pady=10)

        lists_row = tk.Frame(inner, bg=COLOR_BG_MAIN)
        lists_row.pack(fill="x")

        apps_box, self._apps_refresh = self._build_list_editor(
            lists_row, "Contact apps",
            "Shown in the Contacts tab's 'App' dropdown. Starts empty - the "
            "dropdown's first choice is always a blank line.",
            lambda: self.contact_apps, self._apps_changed,
            suggestions=SUGGESTED_CONTACT_APPS,
        )
        apps_box.pack(side="left", fill="both", expand=True, padx=(0, 8))

        roles_box, self._roles_refresh = self._build_list_editor(
            lists_row, "Contact roles",
            "Shown in the Contacts tab's 'Role' dropdown. 'Student' is kept "
            "because the 'Linked student' feature looks for it.",
            lambda: self.contact_roles, self._roles_changed,
            protected=PROTECTED_CONTACT_ROLES,
        )
        roles_box.pack(side="left", fill="both", expand=True, padx=(8, 0))

        sched_box = tk.LabelFrame(inner, text="Schedules & colours", bg=COLOR_BG_PANEL,
                                   fg=COLOR_TEXT_MAIN, font=FONT_MAIN, padx=10, pady=10)
        sched_box.pack(fill="both", expand=True, pady=(12, 0))
        tk.Label(sched_box,
                 text="Each row is one recurring schedule. The colour is the colour of its "
                      "chips on the Month View. 'Lesson' is the base tutoring schedule and "
                      "can be renamed and recoloured, but not deleted.",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM, font=FONT_SMALL,
                 wraplength=760, justify="left").pack(anchor="w", pady=(0, 6))

        cols = ("name", "kind", "color")
        self.tree_schedules = ttk.Treeview(sched_box, columns=cols, show="headings", height=8)
        for c, h, w in (("name", "Name", 240), ("kind", "Type", 260), ("color", "Colour", 100)):
            self.tree_schedules.heading(c, text=h)
            self.tree_schedules.column(c, width=w, anchor="w")
        self.tree_schedules.pack(fill="x")
        self.tree_schedules.bind("<Double-Button-1>", lambda _e: self._edit_schedule())

        sched_btns = tk.Frame(sched_box, bg=COLOR_BG_PANEL)
        sched_btns.pack(fill="x", pady=(8, 0))
        styled_button(sched_btns, "Add schedule...", self._add_schedule,
                      COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left")
        styled_button(sched_btns, "Edit selected...", self._edit_schedule,
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(sched_btns, "Move up", lambda: self._move_schedule(-1),
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left")
        styled_button(sched_btns, "Move down", lambda: self._move_schedule(1),
                      COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)
        styled_button(sched_btns, "Delete selected", self._delete_schedule,
                      COLOR_BTN_DANGER, COLOR_BTN_DANGER_FG).pack(side="left")

        self._reload_schedule_tree()
        self._build_phone_page_box(inner)

    # -- generic single-column list editor (apps / roles) -----------------
    def _build_list_editor(self, parent, title, hint, get_list, on_change,
                           protected=(), suggestions=None):
        """A small reusable 'list of words' editor. `get_list` returns the
        live list (mutated in place), `on_change` saves it and pushes the
        change out to whatever dropdowns use it. Returns (frame, refresh)."""
        box = tk.LabelFrame(parent, text=title, bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                             font=FONT_MAIN, padx=10, pady=10)
        tk.Label(box, text=hint, bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM, font=FONT_SMALL,
                 wraplength=360, justify="left").pack(anchor="w", pady=(0, 6))

        # exportselection=False - without it, clicking in the other list on
        # this same tab silently clears this one's selection.
        listbox = tk.Listbox(box, height=8, font=FONT_MAIN, bg="#ffffff",
                             fg=COLOR_TEXT_MAIN, exportselection=False,
                             highlightthickness=1, highlightbackground=COLOR_SEPARATOR)
        listbox.pack(fill="both", expand=True)

        add_row = tk.Frame(box, bg=COLOR_BG_PANEL)
        add_row.pack(fill="x", pady=(6, 0))
        tk.Label(add_row, text="New:", bg=COLOR_BG_PANEL, font=FONT_MAIN).pack(side="left")
        entry = make_entry(add_row, width=18, font=FONT_MAIN)
        entry.pack(side="left", padx=(4, 0))

        def refresh(select_index=None):
            listbox.delete(0, "end")
            for item in get_list():
                listbox.insert("end", item)
            if select_index is not None and 0 <= select_index < listbox.size():
                listbox.selection_set(select_index)
                listbox.see(select_index)

        def selected_index():
            sel = listbox.curselection()
            return sel[0] if sel else None

        def add_item():
            text = entry.get().strip()
            if not text:
                return
            items = get_list()
            if any(text.lower() == x.lower() for x in items):
                messagebox.showinfo(title, f'"{text}" is already on the list.', parent=self.root)
                return
            items.append(text)
            entry.delete(0, "end")
            on_change()
            refresh(len(items) - 1)

        def rename_item():
            idx = selected_index()
            if idx is None:
                return
            items = get_list()
            old = items[idx]
            if old in protected:
                messagebox.showinfo(title, f'"{old}" is needed by the program and cannot be renamed.',
                                    parent=self.root)
                return
            new = self._ask_text(f"Rename in {title}", "New name:", old)
            if not new or new == old:
                return
            if any(new.lower() == x.lower() for i, x in enumerate(items) if i != idx):
                messagebox.showinfo(title, f'"{new}" is already on the list.', parent=self.root)
                return
            items[idx] = new
            on_change()
            refresh(idx)

        def delete_item():
            idx = selected_index()
            if idx is None:
                return
            items = get_list()
            if items[idx] in protected:
                messagebox.showinfo(title, f'"{items[idx]}" is needed by the program and cannot be removed.',
                                    parent=self.root)
                return
            del items[idx]
            on_change()
            refresh(min(idx, len(items) - 1) if items else None)

        def move_item(step):
            idx = selected_index()
            if idx is None:
                return
            items = get_list()
            new_idx = idx + step
            if not (0 <= new_idx < len(items)):
                return
            items[idx], items[new_idx] = items[new_idx], items[idx]
            on_change()
            refresh(new_idx)

        bind_enter_to(entry, add_item)
        styled_button(add_row, "Add (Enter)", add_item,
                      COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left", padx=(6, 0))

        btns = tk.Frame(box, bg=COLOR_BG_PANEL)
        btns.pack(fill="x", pady=(6, 0))
        styled_button(btns, "Rename", rename_item, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left")
        styled_button(btns, "Up", lambda: move_item(-1), COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left", padx=(6, 0))
        styled_button(btns, "Down", lambda: move_item(1), COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left", padx=6)
        styled_button(btns, "Remove", delete_item, COLOR_BTN_DANGER,
                      COLOR_BTN_DANGER_FG).pack(side="left")

        if suggestions:
            def add_suggested():
                items = get_list()
                added = 0
                for s in suggestions:
                    if not any(s.lower() == x.lower() for x in items):
                        items.append(s)
                        added += 1
                if not added:
                    messagebox.showinfo(title, "They are all on the list already.", parent=self.root)
                    return
                on_change()
                refresh()
                show_auto_popup(self.root, f"Added {added} suggested app(s).")

            sugg = tk.Frame(box, bg=COLOR_BG_PANEL)
            sugg.pack(fill="x", pady=(6, 0))
            styled_button(sugg, "Add suggested apps", add_suggested,
                          COLOR_BTN_SUCCESS, COLOR_BTN_SUCCESS_FG).pack(side="left")

        refresh()
        return box, refresh

    def _ask_text(self, title, prompt, initial=""):
        """Tiny one-line text prompt - a local replacement for
        simpledialog.askstring so the caret stays non-blinking and Escape
        cancels, per the program's own dialog rules."""
        top = tk.Toplevel(self.root)
        top.title(title)
        top.configure(bg=COLOR_BG_PANEL)
        top.resizable(False, False)
        top.transient(self.root)
        result = {"value": None}

        tk.Label(top, text=prompt, bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN,
                 font=FONT_MAIN).pack(anchor="w", padx=16, pady=(14, 4))
        ent = make_entry(top, width=34, font=FONT_MAIN)
        ent.insert(0, initial)
        ent.select_range(0, "end")
        ent.pack(padx=16)

        def ok():
            result["value"] = ent.get().strip()
            top.destroy()

        btns = tk.Frame(top, bg=COLOR_BG_PANEL)
        btns.pack(fill="x", padx=16, pady=14)
        styled_button(btns, "OK (Enter)", ok, COLOR_BTN_ACCENT, COLOR_BTN_ACCENT_FG).pack(side="left")
        styled_button(btns, "Cancel (Esc)", top.destroy, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left", padx=8)

        bind_enter_to(ent, ok)
        top.bind("<Escape>", lambda _e: top.destroy())
        _center_over(top, self.root)
        top.grab_set()
        top.focus_force()
        ent.focus_set()
        top.wait_window()
        return result["value"]

    # -- schedule (category) editing --------------------------------------
    def _reload_schedule_tree(self):
        self.tree_schedules.delete(*self.tree_schedules.get_children())
        for d in SCHEDULE_DEFS:
            kind = ("Base tutoring schedule (built in)" if d["key"] == "lesson"
                    else f"Family schedule - {len(self.personal_schedules.get(d['key'], []))} row(s)")
            tag = f"col_{d['key']}"
            # The row itself is painted in the schedule's colour, so the
            # list doubles as the colour legend.
            self.tree_schedules.tag_configure(tag, background=d["color"],
                                              foreground=readable_fg(d["color"]))
            self.tree_schedules.insert("", "end", iid=d["key"], tags=(tag,),
                                       values=(d["name"], kind, d["color"]))

    def _selected_schedule_key(self):
        sel = self.tree_schedules.selection()
        return sel[0] if sel else None

    def _ask_schedule_details(self, title, name="", color=None):
        """Name + colour picker used by both 'Add schedule' and 'Edit'.
        Returns {"name":..., "color":...} or None if cancelled."""
        top = tk.Toplevel(self.root)
        top.title(title)
        top.configure(bg=COLOR_BG_PANEL)
        top.resizable(False, False)
        top.transient(self.root)
        chosen = {"color": color or SUGGESTED_COLORS[0]}
        result = {"value": None}

        tk.Label(top, text="Name (this is what you will see on the chips and tabs):",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_MAIN, font=FONT_MAIN).pack(
            anchor="w", padx=16, pady=(14, 4))
        ent = make_entry(top, width=34, font=FONT_MAIN)
        ent.insert(0, name)
        ent.select_range(0, "end")
        ent.pack(anchor="w", padx=16)

        preview = tk.Label(top, text=name or "Preview", bg=chosen["color"],
                           fg=readable_fg(chosen["color"]), font=FONT_MAIN,
                           padx=10, pady=6, width=28, anchor="w")
        preview.pack(anchor="w", padx=16, pady=(10, 4))

        def repaint():
            preview.configure(text=ent.get().strip() or "Preview", bg=chosen["color"],
                              fg=readable_fg(chosen["color"]))
            for sw, col in swatches:
                sw.configure(highlightbackground=(COLOR_TEXT_MAIN if col == chosen["color"]
                                                  else COLOR_SEPARATOR),
                             highlightthickness=(3 if col == chosen["color"] else 1))

        ent.bind("<KeyRelease>", lambda _e: repaint())

        tk.Label(top, text="Colour - pick a suggestion or make your own:", bg=COLOR_BG_PANEL,
                 fg=COLOR_TEXT_MAIN, font=FONT_MAIN).pack(anchor="w", padx=16, pady=(8, 4))
        grid = tk.Frame(top, bg=COLOR_BG_PANEL)
        grid.pack(anchor="w", padx=16)
        swatches = []
        for i, col in enumerate(SUGGESTED_COLORS):
            sw = tk.Frame(grid, bg=col, width=28, height=24, cursor="hand2",
                          highlightthickness=1, highlightbackground=COLOR_SEPARATOR)
            sw.grid(row=i // 8, column=i % 8, padx=2, pady=2)
            sw.pack_propagate(False)
            sw.bind("<Button-1>", lambda _e, c=col: (chosen.update(color=c), repaint()))
            swatches.append((sw, col))

        def pick_custom():
            rgb, hex_color = colorchooser.askcolor(color=chosen["color"], parent=top,
                                                    title="Pick a colour")
            if hex_color:
                chosen["color"] = hex_color
                repaint()

        def ok():
            typed = ent.get().strip()
            if not typed:
                messagebox.showwarning(title, "Please type a name first.", parent=top)
                return
            result["value"] = {"name": typed, "color": chosen["color"]}
            top.destroy()

        btns = tk.Frame(top, bg=COLOR_BG_PANEL)
        btns.pack(fill="x", padx=16, pady=(10, 14))
        styled_button(btns, "Custom colour...", pick_custom, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left")
        styled_button(btns, "OK (Enter)", ok, COLOR_BTN_ACCENT,
                      COLOR_BTN_ACCENT_FG).pack(side="left", padx=8)
        styled_button(btns, "Cancel (Esc)", top.destroy, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(side="left")

        bind_enter_to(ent, ok)
        top.bind("<Escape>", lambda _e: top.destroy())
        repaint()
        _center_over(top, self.root)
        top.grab_set()
        top.focus_force()
        ent.focus_set()
        top.wait_window()
        return result["value"]

    def _add_schedule(self):
        data = self._ask_schedule_details("Add schedule")
        if not data:
            return
        keys = {d["key"] for d in self.schedule_defs}
        self.schedule_defs.append({
            "key": new_schedule_key(data["name"], keys),
            "name": data["name"], "color": data["color"],
            "start_field": "start", "end_field": "end",
            "start_label": "Start", "end_label": "End", "builtin": False,
        })
        self._schedules_changed()
        show_auto_popup(self.root, f'"{data["name"]}" added.')

    def _edit_schedule(self):
        key = self._selected_schedule_key()
        if not key:
            return
        d = next((x for x in self.schedule_defs if x["key"] == key), None)
        if not d:
            return
        data = self._ask_schedule_details("Edit schedule", d["name"], d["color"])
        if not data:
            return
        d["name"], d["color"] = data["name"], data["color"]
        self._schedules_changed()

    def _move_schedule(self, step):
        key = self._selected_schedule_key()
        if not key:
            return
        idx = next((i for i, d in enumerate(self.schedule_defs) if d["key"] == key), None)
        if idx is None:
            return
        new_idx = idx + step
        if not (0 <= new_idx < len(self.schedule_defs)):
            return
        self.schedule_defs[idx], self.schedule_defs[new_idx] = (
            self.schedule_defs[new_idx], self.schedule_defs[idx])
        self._schedules_changed()
        self.tree_schedules.selection_set(key)

    def _delete_schedule(self):
        key = self._selected_schedule_key()
        if not key:
            return
        d = next((x for x in self.schedule_defs if x["key"] == key), None)
        if not d:
            return
        if d["key"] == "lesson":
            messagebox.showinfo("Delete schedule",
                                "The base tutoring schedule cannot be deleted - it is what the "
                                "Base Schedule tab fills in. You can rename and recolour it "
                                "instead.", parent=self.root)
            return
        rows = self.personal_schedules.get(key, [])
        overrides = [o for o in self.temp_overrides if o.get("category") == key]
        if not messagebox.askyesno(
                "Delete schedule",
                f'Delete "{d["name"]}"?\n\n'
                f"This also removes its {len(rows)} weekly row(s) and "
                f"{len(overrides)} override(s). This cannot be undone.",
                parent=self.root):
            return
        for row in rows:
            self._purge_alarm_state_for_row(row.get("id"))
        self.personal_schedules.pop(key, None)
        self.temp_overrides = [o for o in self.temp_overrides if o.get("category") != key]
        self.schedule_defs = [x for x in self.schedule_defs if x["key"] != key]
        save_json_list(PERSONAL_SCHEDULES_PATH, self.personal_schedules)
        save_json_list(OVERRIDES_PATH, self.temp_overrides)
        self._schedules_changed()

    # -- "the user changed a list" handlers -------------------------------
    def _apps_changed(self):
        save_json_list(CONTACT_APPS_PATH, self.contact_apps)
        self._refresh_contact_choice_lists()
        if hasattr(self, "_apps_refresh"):
            self._apps_refresh()      # keep the Settings listbox in step too

    def _roles_changed(self):
        save_json_list(CONTACT_ROLES_PATH, self.contact_roles)
        self._refresh_contact_choice_lists()
        if hasattr(self, "_roles_refresh"):
            self._roles_refresh()

    def _schedules_changed(self):
        """One place that republishes the schedule definitions and redraws
        every part of the program that is built from them."""
        apply_schedule_defs(self.schedule_defs)
        save_json_list(SCHEDULE_TYPES_PATH, self.schedule_defs)
        for key in FAMILY_SCHEDULE_FIELDS:
            self.personal_schedules.setdefault(key, [])
        self._sync_layer_vars()
        self._rebuild_month_layer_row()
        self._rebuild_week_layer_row()
        self._rebuild_export_layer_row()
        self._rebuild_family_tab()
        self._refresh_override_schedule_choices()
        self._reload_tree_overrides()
        self._reload_schedule_tree()
        self._refresh_month_view()

    def _reload_all_treeviews(self):
        self._reload_tree_calendar()
        self._reload_tree_base()
        self._reload_tree_overrides()
        self._reload_tree_contacts()
        for reload_family in getattr(self, "family_reloaders", {}).values():
            reload_family()

    def _save_all(self):
        save_json_list(EVENTS_PATH, self.calendar_events)
        save_json_list(BASE_SCHEDULE_PATH, self.base_schedule)
        save_json_list(OVERRIDES_PATH, self.temp_overrides)
        save_json_list(PERSONAL_SCHEDULES_PATH, self.personal_schedules)
        save_json_list(CONTACTS_PATH, self.contacts)

    def _on_close(self):
        self.settings["geometry"] = self.root.geometry()
        try:
            self.settings["last_tab"] = self.notebook.index(self.notebook.select())
        except Exception:
            pass
        try:
            self.settings["last_calendar_tab"] = self.calendar_sub_notebook.index(
                self.calendar_sub_notebook.select())
        except Exception:
            pass
        self.settings["export_range"] = self.export_range_var.get()
        self.settings["export_layers"] = {key: var.get() for key, var in self.export_layer_vars.items()}
        save_settings(self.settings)
        self._save_all()
        self._phone_final_push()     # DEL 10: a change made seconds before closing still reaches the phone page
        self._stop_alarm_loop()
        remove_tray_icon()      # nothing left behind in the notification area (DEL 07f)
        self.root.destroy()

    # ---------------- About dialog ----------------
    def _show_about(self):
        top = tk.Toplevel(self.root)
        top.title(f"About {APP_NAME}")
        top.configure(bg=COLOR_BG_PANEL)
        top.resizable(False, False)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _e: top.destroy())

        hdr = tk.Frame(top, bg=COLOR_BG_PANEL)
        hdr.pack(fill="x")
        tk.Label(hdr, text="📅", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                 font=("Segoe UI", 36)).pack(pady=(18, 0))
        tk.Label(hdr, text=APP_NAME, bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                 font=("Segoe UI", 20, "bold")).pack()
        tk.Label(hdr, text="Calendar & schedule manager for private tutoring",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM,
                 font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))

        tk.Frame(top, bg=COLOR_SEPARATOR, height=1).pack(fill="x", padx=20)

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

        if DOC_URL:
            doc_lbl = tk.Label(top, text="📄  View documentation", bg=COLOR_BG_PANEL,
                                fg=COLOR_BG_HEADER, font=("Segoe UI", 9, "underline"), cursor="hand2")
            doc_lbl.pack(pady=(6, 2))
            doc_lbl.bind("<Button-1>", lambda _e: open_url(DOC_URL))

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

        tk.Label(top, text="☕  If you enjoy TutorCal, a small gift is always welcome!",
                 bg=COLOR_BG_PANEL, fg=COLOR_TEXT_DIM, font=("Segoe UI", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

        donate_frame = tk.Frame(top, bg="#f0eee8", padx=16, pady=10)
        donate_frame.pack(fill="x", padx=20, pady=(0, 6))
        for label, url in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL), ("Wise", WISE_URL)):
            lbl = tk.Label(donate_frame, text=label, bg="#f0eee8", fg=COLOR_BG_HEADER,
                           font=("Segoe UI", 9, "underline"), cursor="hand2")
            lbl.pack(anchor="w")
            lbl.bind("<Button-1>", lambda _e, u=url: open_url(u))

        tk.Frame(top, bg=COLOR_SEPARATOR, height=1).pack(fill="x", padx=20, pady=(4, 0))
        styled_button(top, "Close", top.destroy, COLOR_BTN_NORMAL, COLOR_BTN_NORMAL_FG).pack(pady=14)
        _center_over(top, self.root)

    # ---------------- Help dialog ----------------
    def _show_help(self):
        top = tk.Toplevel(self.root)
        top.title(f"{APP_NAME} Help")
        top.configure(bg=COLOR_BG_PANEL)
        top.geometry("620x520")
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _e: top.destroy())

        tk.Label(top, text=f"{APP_NAME} - Help", bg=COLOR_BG_PANEL, fg=COLOR_BG_HEADER,
                 font=("Segoe UI", 14, "bold")).pack(pady=(14, 6))

        outer, inner = make_scrollable_frame(top, bg=COLOR_BG_PANEL)
        outer.pack(fill="both", expand=True, padx=14, pady=(0, 10))

        help_text = (
            "The window, tabs, saved settings, and add/delete/edit/save for "
            "each list all work, and the Calendar tab has a real Month View, "
            "Week View, and Day View. One thing is still only partly built - "
            "sharing the exported agenda straight to a chosen recipient "
            "(see EXPORT TAB below):\n\n"
            "CALENDAR TAB - Month View\n"
            "A proper month grid with Prev/Next/Today navigation, with today's "
            "full date spelled out next to the buttons and today's cell marked "
            "with a thick orange outline and an orange day-number badge. It merges "
            "everything: your base weekly lesson schedule, one-off entries, "
            "cancelled/moved occurrences, and (optionally) family schedules - "
            "use the checkboxes above the grid to show or hide each layer. "
            "Click any day to see everything on it, double-click a line in that "
            "day box to edit whatever made it, jump straight to adding a new "
            "entry for that date, or open that day in Day View for a closer "
            "look. NOTE: you can't drag entries around on the grid itself yet.\n\n"
            "CALENDAR TAB - Week View\n"
            "The same information as a real timetable: seven day columns, one "
            "row per hour, and every lesson or appointment drawn as a block as "
            "tall as it is long - so a two-hour lesson is twice the height of a "
            "one-hour one, and you can see at a glance where the gaps are. Two "
            "things at the same time sit side by side instead of hiding each "
            "other. Anything without a clock time (a plain note, 'book the "
            "dentist') sits in the strip just under the day names. The grid "
            "normally runs 07:00-21:00 and stretches by itself if something "
            "that week starts earlier or ends later. Prev/This/Next week move "
            "between weeks, and the layer checkboxes are shared with the Month "
            "View. Click a date at the top of a column to see that whole day "
            "(and optionally open it in Day View); "
            "double-click a block to edit whatever made it (the entry, the "
            "recurring slot, or the override); double-click empty space to "
            "start a new entry on that day at that time, already filled in. "
            "You can also drag a block to a new day/time to move it, or drag "
            "its bottom edge to resize it by changing its end time - both "
            "snap to the quarter hour and show a dashed preview while you "
            "drag. A cancelled slot or a plain note can't be dragged, since "
            "there's nothing sensible to drag it to. When the week on screen "
            "is the current one, a thin red line runs across today's column at "
            "the time it is now (with the time written at its end) and moves "
            "down by itself once a minute, so 'what's next' is one glance.\n\n"
            "CALENDAR TAB - Day View\n"
            "The same time-grid drawing as Week View, zoomed into one day so a "
            "busy day is easier to read than squinting at its Week View sliver: "
            "hour lines, blocks sized to their real duration, overlapping ones "
            "tiled side by side, untimed ones in a strip at the top. Prev "
            "day/Today/Next day move between days, and the layer checkboxes are "
            "shared with Month and Week View. Reach it either from its own tab "
            "or by clicking a day in Month or Week View and choosing 'Open Day "
            "View'. Double-click a block to edit whatever made it; double-click "
            "empty space to start a new entry at that time. Same as Week View, "
            "you can also drag a block to move it to a new time, or drag its "
            "bottom edge to resize it by changing its end time.\n\n"
            "CALENDAR TAB - List View\n"
            "A Search box at the top filters the list as you type - it matches "
            "the date, times, title, note and reminder settings, and also "
            "understands words that aren't stored anywhere: type 'today', a "
            "weekday ('tuesday') or a month ('october'). The label on the right "
            "says how many entries are showing. Adding a new entry clears the "
            "filter, so what you just added is never hidden. The list is sorted "
            "oldest first but opens scrolled to today, so you start at what's "
            "coming rather than at the first lesson you ever entered.\n"
            "Add a dated note or lesson entry with a title, time range, and an "
            "optional note. You can also pick how far in advance you want to be "
            "warned ('Warn before') and, once that is picked, choose a repeat "
            "interval from the choices offered - the choices automatically narrow "
            "down based on how far out the warning is. Reminders now actually "
            "fire: once 'now' enters the warning window, a popup (with a sound) "
            "appears and keeps coming back at the chosen repeat interval until "
            "you click 'Dismiss' or the event's start time passes. Each one also "
            "raises a real OS notification (a Windows Action Center toast, a "
            "macOS notification banner, or a Linux notify-send toast) at the same "
            "time, plus a few flashes of the taskbar button, so it's still "
            "noticed if TutorCal is minimized or behind other windows. The clock "
            "is only watched while TutorCal itself is open - so when you start "
            "it, anything whose reminder fell due while it was closed (and that "
            "has already started, within the last 12 hours) is listed once in a "
            "'While TutorCal was closed' window. Clicking 'Got it' there marks "
            "those as handled; a reminder for something that hasn't started yet "
            "simply fires as usual.\n\n"
            "BASE SCHEDULE TAB\n"
            "Set up recurring weekly lesson slots (the 17-18 / 18-19 / 19-20 "
            "buttons fill in the common times, but any time can be typed in "
            "instead) - these now auto-generate onto the Month View. Each slot "
            "can also have its own 'Warn before' / 'Repeat reminder', just "
            "like a Calendar > List View entry - once set, that slot's weekly "
            "occurrence pops up a reminder the same way, and a Cancelled "
            "occurrence never alarms while a Moved one alarms at its new time "
            "instead. Below that, record a Cancel, Move, or Note-only override "
            "for a specific date; a 'Schedule' dropdown lets you pick whether "
            "the override applies to the lesson schedule or to any of the "
            "other schedules you defined, and if that day has more than one "
            "slot on the chosen schedule you can pick which one it applies to, "
            "otherwise it affects all of them.\n\n"
            "FAMILY SCHEDULES TAB\n"
            "One sub-tab per schedule you created on the Settings tab - it "
            "starts out with your own schedule, your son's school schedule, "
            "his school bus times and his daycare, but you can rename those, "
            "recolour them, remove them, or add as many more as you like. Each "
            "is a simple add/delete list with its own optional 'Warn before' / "
            "'Repeat reminder' per row (same alarm behaviour as the Base "
            "Schedule tab), and each also appears as an optional layer on the "
            "Month View. One-off cancellations or moves for any of them are "
            "recorded on the Base Schedule tab (choose the schedule there).\n\n"
            "SETTINGS TAB\n"
            "The lists everything else picks from:\n"
            " - Contact apps: type in the apps you actually use (WhatsApp, "
            "Signal, SMS, ...). The list starts empty, and the Contacts tab's "
            "'App' dropdown stays blank until you fill it in. 'Add suggested "
            "apps' fills in the common ones in one click if you'd rather start "
            "from those.\n"
            " - Contact roles: the same thing for the 'Role' dropdown. Only "
            "'Student' is fixed, because the 'Linked student' feature looks for "
            "it.\n"
            " - Schedules & colours: every recurring schedule the calendar "
            "knows about. Add one, name it whatever you want, and give it a "
            "colour - either one of the suggested swatches or your own via "
            "'Custom colour...'. It immediately gets its own Family Schedules "
            "sub-tab, its own Month View layer checkbox, its own entry in the "
            "override dropdown, and its own Export checkbox. Renaming or "
            "recolouring one keeps all its rows; deleting one asks first and "
            "then removes its rows and overrides with it. 'Lesson' (the base "
            "tutoring schedule) can be renamed and recoloured but not "
            "deleted.\n\n"
            "CONTACTS TAB\n"
            "Add contacts for school, daycare, students, or guardians. 'App' "
            "and 'Role' are dropdowns fed by your own lists on the Settings "
            "tab - App is blank by default - while 'Contact value' is free "
            "text, so you can pair e.g. 'WhatsApp' with a number. Use "
            "the Search box to filter the list (matches name, role, app, "
            "contact value, note, and any linked student/event).\n"
            "'Contact selected' reaches the picked person the way their App "
            "field implies: an email address opens a mail draft, WhatsApp "
            "opens that chat (it needs the number in international form, "
            "+46..., and warns you if yours isn't), SMS and Phone open your "
            "messaging app and dialler, and a saved web link just opens. For "
            "apps with no reliable link format (Signal, Telegram, a handle "
            "rather than a number) the value is copied to the clipboard "
            "instead of opening something wrong.\n"
            "Optionally link a contact to a specific Student contact "
            "('Linked student' - e.g. tie a Guardian to their child) and/or to "
            "a specific Calendar > List View event ('Linked event' - e.g. tie a "
            "School contact to a particular meeting); both dropdowns update "
            "automatically as you add contacts and events elsewhere in the "
            "app, and a link to something you later delete shows as "
            "'(deleted)' rather than disappearing silently.\n\n"
            "EXPORT TAB\n"
            "'Hours summary' answers 'how much did I actually teach?' for the "
            "chosen date range: how many times each student (or each entry) "
            "appeared and how many hours that adds up to, with a total at the "
            "bottom and a 'Copy to Clipboard' button for pasting into an "
            "invoice. A cancelled lesson isn't counted, and a moved one is "
            "counted on the day it really happened.\n"
            "'Preview Agenda' shows the merged agenda as text with a live "
            "character count before you send anything, so you can check "
            "whether it's short enough for WhatsApp/Email. Builds the same "
            "merged agenda as the Month View for a date range (this week or "
            "next week - the same Monday-to-Sunday week the Week View shows - "
            "the next 7/30 days, this month, or a custom range) and saves it as a "
            "phone-friendly .txt, .png, or .pdf under Helpfiles/Export - each "
            "opens automatically once saved (Image needs Pillow, PDF needs "
            "fpdf2; Text has no extra dependency). Saving as Image also copies "
            "the picture onto your clipboard, so right after it's saved you can "
            "just press Ctrl+V (Cmd+V on Mac) inside WhatsApp Desktop, Telegram, "
            "Signal, or an email compose box to attach it - no dragging needed. "
            "'Copy to Clipboard' puts the "
            "agenda text straight on the clipboard with no length limit, ready "
            "to paste into SMS, Signal, Telegram, or anywhere else. 'Share as "
            "WhatsApp Message' and 'Share as Email' send the same agenda "
            "straight into a WhatsApp chat picker or a new email draft as "
            "text, ready to address and send - no file is attached "
            "automatically there either, and the PDF export still has to be "
            "dragged in by hand since nothing accepts a PDF as a paste.\n"
            "'Export to Calendar (.ics)' is the odd one out and the useful one "
            "if you want the schedule on your phone: instead of a picture of the "
            "agenda it writes a standard calendar file that Google Calendar, "
            "Outlook, Thunderbird and both iPhone and Android understand. Open "
            "it on the phone (or import it) and every lesson in the range "
            "becomes a real calendar entry you can set the phone's own alerts "
            "on. Times are written as plain local times, so 17:00 stays 17:00, "
            "and exporting the same week again updates those entries rather "
            "than creating a second copy of each.\n\n"
            "DATES\n"
            "Anywhere a date is asked for, the little calendar button next to "
            "the field opens a month grid: click a day and it fills the field "
            "in. 'Today' picks today, the arrows move a month at a time, and "
            "Escape closes it without changing anything. Typing the date by "
            "hand as YYYY-MM-DD still works everywhere it did before.\n\n"
            "CHANGING SOMETHING YOU ALREADY ADDED\n"
            "Every list has an 'Edit selected...' button, and double-clicking a "
            "row does the same thing: it opens a small form with that row's "
            "current values. Enter saves, Escape cancels, and Enter inside a "
            "multi-line Note just starts a new line. If you change something "
            "that decides when a reminder is due (the date or weekday, the "
            "start time, 'Warn before' or 'Repeat'), that row's reminder is "
            "re-armed, so an entry you push later in the day still warns you at "
            "the new time instead of staying quiet because it had already "
            "fired.\n\n"
            "YOUR DATA\n"
            "Everything is stored as plain JSON files under the Helpfiles "
            "folder next to the program - nothing is in the cloud and nothing "
            "leaves the machine. Each save is written to a temporary file first "
            "and only then swapped into place, and the previous version is kept "
            "alongside it as a '.bak', so an interrupted save can't leave a "
            "damaged file. Once a day at startup a copy of all of it is put in "
            "Helpfiles/Backups under that day's date, and the last 14 days are "
            "kept - so something deleted by mistake last Tuesday can still be "
            "fetched back. If a data file ever does turn out to be unreadable, "
            "it is renamed rather than overwritten, the '.bak' beside it is used "
            "instead, and you get a message at startup saying so.\n"
            "To go back to one of those daily copies, use File > 'Restore from "
            "a backup...', pick the day, and confirm. What is in the program "
            "right now is copied aside first (into a 'before-restore' folder "
            "next to the backups), so a restore can itself be undone, and "
            "TutorCal closes afterwards - start it again and the restored data "
            "is there.\n\n"
            "GENERAL\n"
            "Window size, the tab you were on, and which calendar view you were "
            "using (Month/Week/Day/List) are remembered between runs. "
            "If something goes wrong, a crash report is saved automatically to "
            "the Helpfiles/0---Empty folder next to the program."
        )
        txt = make_text(inner, wrap="word", width=68, height=28, font=FONT_MAIN,
                        bg=COLOR_BG_PANEL, relief="flat")
        txt.insert("1.0", help_text)
        txt.configure(state="disabled")
        txt.pack(fill="both", expand=True)

        styled_button(top, "Close (Esc)", top.destroy, COLOR_BTN_NORMAL,
                      COLOR_BTN_NORMAL_FG).pack(pady=10)
        _center_over(top, self.root)


# *************** DEL 09 - MAIN ENTRYPOINT ***************

def main():
    install_crash_catcher()
    apply_app_user_model_id()   # must run BEFORE tk.Tk()

    settings = load_settings()

    root = tk.Tk()
    root.title(APP_TITLE)
    root.configure(bg=COLOR_BG_MAIN)
    root.geometry(settings.get("geometry", DEFAULT_SETTINGS["geometry"]))

    # Parked on root so the app object is reachable for as long as the
    # window is (and so this doesn't read as an unused variable).
    root.app = TutorCalApp(root, settings)

    root.after(0, lambda: set_window_icon(root))  # icon set AFTER mainloop starts, never directly

    root.mainloop()


if __name__ == "__main__":
    main()
